@hydra-acp/cli 0.1.94 → 0.1.96

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,32 +1,34 @@
1
1
  #!/usr/bin/env node
2
- var sv=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var qc=(t,e)=>{for(var n in e)sv(t,n,{get:e[n],enumerable:!0})};import*as ge from"path";import*as zc from"os";function Xe(t){let e=zc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function cv(){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 Ce(){let t=process.env[dv];if(t&&t.length>0)return ge.resolve(t);let e=cv();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 ge.join(zc.homedir(),".hydra-acp")}var dv,_,he=J(()=>{"use strict";dv="HYDRA_ACP_HOME";_={home:Ce,config:()=>ge.join(Ce(),"config.json"),authToken:()=>ge.join(Ce(),"auth-token"),remotes:()=>ge.join(Ce(),"remotes.json"),pidFile:()=>ge.join(Ce(),"daemon.pid"),logFile:()=>ge.join(Ce(),"daemon.log"),currentLogFile:()=>ge.join(Ce(),"current.log"),registryCache:()=>ge.join(Ce(),"registry.json"),agentsDir:()=>ge.join(Ce(),"agents"),agentLogFile:t=>ge.join(Ce(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ge.join(Ce(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ge.join(Ce(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ge.join(Ce(),"sessions"),sessionDir:t=>ge.join(Ce(),"sessions",t),sessionFile:t=>ge.join(Ce(),"sessions",t,"meta.json"),historyFile:t=>ge.join(Ce(),"sessions",t,"history.jsonl"),toolsDir:t=>ge.join(Ce(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ge.join(Ce(),"sessions",t,"tools",e),queueFile:t=>ge.join(Ce(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ge.join(Ce(),"sessions",".tombstones"),tombstoneAgentDir:t=>ge.join(Ce(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ge.join(Ce(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ge.join(Ce(),"extensions"),extensionLogFile:t=>ge.join(Ce(),"extensions",`${t}.log`),extensionPidFile:t=>ge.join(Ce(),"extensions",`${t}.pid`),transformersDir:()=>ge.join(Ce(),"transformers"),transformerLogFile:t=>ge.join(Ce(),"transformers",`${t}.log`),transformerPidFile:t=>ge.join(Ce(),"transformers",`${t}.pid`),transformerState:(t,e)=>ge.join(Ce(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ge.join(Ce(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ge.join(Ce(),"prompt-history"),tuiLogFile:()=>ge.join(Ce(),"tui.log"),shimWireLogFile:()=>ge.join(Ce(),"shim-wire.log")}});import*as oi from"fs/promises";function ai(){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 di(){try{let e=(await oi.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function gr(){let t=await di();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function ci(t){await oi.mkdir(_.home(),{recursive:!0}),await oi.writeFile(_.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function Io(){let t=await di();if(t)return t;let e=ai();return await ci(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
- `),e}var ds=J(()=>{"use strict";he()});import*as xt from"fs/promises";import*as np from"fs";import*as An from"path";import{randomBytes as lv}from"crypto";async function Qt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await uv(t,r,n)}async function uv(t,e,n={}){let s=await fv(t),r=pv(s);await xt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${hv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await xt.writeFile(i,e,o),await xt.rename(i,s)}catch(o){throw await xt.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{np.chmodSync(s,n.mode)}catch{}}async function fv(t){let e;try{e=await xt.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await xt.readlink(t),s=An.isAbsolute(n)?n:An.resolve(An.dirname(t),n);try{let r=await xt.realpath(An.dirname(s));return An.join(r,An.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function hn(t){let e;try{e=await xt.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 pv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function hv(){return lv(4).toString("hex")}var yr=J(()=>{"use strict"});import*as _s from"fs/promises";import{homedir as Kc}from"os";import{z as q}from"zod";function ip(t){return t.tui.inAppSelection??t.tui.mouse}function op(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function ap(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function $a(){return await Iv(),await hn(_.config())??{}}async function Iv(){let t;try{t=await _s.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await _s.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await _s.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 Fa(){let t=await $a(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await _s.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 ci(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Qt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
- `)}async function we(){return await Fa(),Jc.parse(await $a())}async function cs(t){await Fa();let e=await $a();t(e),Jc.parse(e),await Qt(_.config(),e,{mode:384})}async function xo(t,e){await cs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Oa(t){await cs(e=>{e.defaultAgent=t})}async function dp(t,e){await cs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function cp(t,e){await cs(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 Yc(t,e){await cs(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 lp(t){await cs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function up(){let t=await $a();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Ze(t){return t==="~"||t==="$HOME"?Kc():t.startsWith("~/")?Kc()+t.slice(1):t.startsWith("$HOME/")?Kc()+t.slice(5):t}var rp,mv,Rn,gv,yv,wv,bv,vv,sp,Sv,kv,Jc,Ye=J(()=>{"use strict";he();ds();yr();rp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",mv=q.object({cert:q.string(),key:q.string()}),Rn=55514,gv=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Rn),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:mv.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)}),yv=q.object({url:q.string().url().default(rp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),wv=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()}),bv=q.object({packageSpec:q.string().optional()}),vv=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()}),sp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Sv=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)}),kv=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)}),Jc=q.object({daemon:gv.default({}),registry:yv.default({url:rp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),wv).default({}),agentOverrides:q.record(q.string(),bv).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(sp,Sv).default({}),transformers:q.record(sp,kv).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:vv.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 wr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Vc(t){return{httpScheme:"https",wsScheme:"wss"}}function Qc(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 ${La(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${La(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=xv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${La(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${La(t)}`);let i=wr(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=Rn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function fp(t){let e=t.port!==void 0&&t.port!==Rn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function xv(t){try{return new URL(t)}catch{return null}}function La(t){return t.length>80?`${t.slice(0,77)}...`:t}var Co=J(()=>{"use strict";Ye()});function br(t,e){return`${t}:${e}`}function pp(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Cv(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 Av(){let t=await hn(_.remotes());return t===void 0?{version:1,entries:{}}:Rv(t)}function Rv(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 Gc(t){await Qt(_.remotes(),t,{mode:384})}var Ba,Xc=J(()=>{"use strict";he();yr();Ba=class t{data;constructor(e){this.data=e}static async load(){let e=await Av(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(pp(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Gc(i),new t(i)}get(e,n){let s=this.data.entries[br(e,n)];if(s&&!pp(s,Date.now()))return s}async set(e,n,s){this.data.entries[br(e,n)]=s,await Gc(this.data)}async delete(e,n){let s=br(e,n);return s in this.data.entries?(delete this.data.entries[s],await Gc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Cv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function li(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)}):Tv()}function Tv(){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 Zc=J(()=>{"use strict"});import*as hp from"path";function Ln(){let t=process.argv[1];if(!t)return"hydra-acp";let e=hp.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Ao=J(()=>{"use strict"});import*as Na from"fs/promises";async function ls(){try{let t=await Na.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 mp(t){await Na.writeFile(_.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function Tn(t){try{return process.kill(t,0),!0}catch{return!1}}var ui=J(()=>{"use strict";he()});var Sp={};qc(Sp,{_resetForTests:()=>Bv,clearPin:()=>Ov,fetchPeerFingerprint:()=>sl,formatFingerprint:()=>Da,getPin:()=>tl,installGlobalTlsTrust:()=>il,loadPinsFromStore:()=>nl,setPin:()=>Ro,sha256Hex:()=>rl,wsTlsOptions:()=>To});import{createHash as Ev}from"crypto";import*as gp from"tls";import{Agent as Pv,Dispatcher as Mv,buildConnector as _v,getGlobalDispatcher as $v,setGlobalDispatcher as Fv}from"undici";function Ro(t,e,n){vr.set(br(t,e),yp(n))}function Ov(t,e){vr.delete(br(t,e))}function tl(t,e){return vr.get(br(t,e))}function nl(t){vr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Ro(e.host,e.port,e.entry.pinnedFingerprint)}async function sl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=gp.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,rl(l.raw))}),o.once("error",l=>c(l))})}function rl(t){return Ev("sha256").update(t).digest("hex")}function Da(t){let e=yp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function yp(t){return t.replace(/:/g,"").toLowerCase()}function il(){if(el)return;el=!0;let t=$v(),e=new Pv({connect:_v({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>bp(s,r)})}),n=new Mv;n.dispatch=(s,r)=>{let i=Lv(s.origin);return(i&&wp(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(()=>{})),Fv(n)}function Lv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function wp(t){for(let e of vr.keys())if(vp(e)?.host===t)return!0;return!1}function bp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=rl(e.raw);for(let[s,r]of vr.entries()){let i=vp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Da(n)})`)}function vp(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 To(t){return wp(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>bp(e,n)}:{autoSelectFamily:!0}}function Bv(){vr.clear(),el=!1}var vr,el,Eo=J(()=>{"use strict";Xc();vr=new Map,el=!1});import*as Cp from"os";async function jt(t){let e=await Io(),n=await ls();if(n&&Tn(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:wr(r)}}function kp(t,e){let{httpScheme:n,wsScheme:s}=Vc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Rp(t),isLocal:t.isLoopback}}async function Ap(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??li,r=e.confirmImpl??Uv,i=e.tlsHandshakeImpl??Nv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let v=await di();if(v)return Hv(t,v)}let c=e.store??await Ba.load();nl(c),il();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Ro(t.host,t.port,d.pinnedFingerprint),kp(t,d.token);if(!a)throw new ol(t.host,t.port);let l=Rp(t),{httpScheme:u}=Vc(t.host),f;if(u==="https"&&tl(t.host,t.port)===void 0){let v=await i(t.host,t.port);if(v.kind==="untrusted"){let b=v.subject||v.issuer?`
10
- subject: ${v.subject??"(unknown)"}
11
- issuer: ${v.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${Da(v.fingerprint)}${b}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Ro(t.host,t.port,v.fingerprint),f=v.fingerprint}else if(v.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${v.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:xp()})});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:xp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),kp(t,y.session_token)}async function Nv(t,e){let n=await Dv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await sl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Dv(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?Ip(p.subject):void 0,issuer:p?.issuer?Ip(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 Ip(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 Hv(t,e){let n=await ls(),r=n&&Tn(n.pid)?n.loopbackPort:t.port,i=t.port===Rn?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 Uv(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 xp(){try{let t=Cp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Rp(t){return t.port===Rn?t.host:`${t.host}:${t.port}`}var ol,Sr=J(()=>{"use strict";Ye();ds();Co();Xc();Zc();Ao();ui();Eo();Co();ol=class extends Error{host;port;constructor(e,n){let s=n===Rn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Ln()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as jv,renameSync as qv,statSync as Wv}from"fs";function Pp(t){Ep=t}function st(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{zv(n);let s=JSON.stringify({t:new Date().toISOString(),...t});jv(n,`${s}
15
- `)}catch{}}function zv(t){try{if(Wv(t).size<Ep)return;qv(t,`${t}.0`)}catch{}}var Ep,dl=J(()=>{"use strict";he();Ep=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 _e}from"zod";var Zp,wS,eh,th,nh,vl=J(()=>{"use strict";Zp=_e.object({protocolVersion:_e.number().optional(),clientCapabilities:_e.record(_e.unknown()).optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional()}),wS=_e.enum(["full","pending_only","none","after_message"]),eh=_e.object({cwd:_e.string(),mcpServers:_e.array(_e.unknown()).optional(),_meta:_e.record(_e.unknown()).optional()}),th=_e.object({upstreamSessionId:_e.string(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),agentArgs:_e.array(_e.string()).optional()}),nh=_e.object({sessionId:_e.string(),historyPolicy:wS.default("full"),afterMessageId:_e.string().optional(),clientId:_e.string().optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional(),_meta:_e.record(_e.unknown()).optional()})});import{z as ae}from"zod";function Ka(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 ih(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Po(t._meta,Ka(t))};return t.title!==void 0&&(e.title=t.title),e}var sh,rh,Sl,LE,bS,BE,kl=J(()=>{"use strict";Ja();sh=ae.object({sessionId:ae.string()}),rh=ae.object({cwd:ae.string().optional(),cursor:ae.string().optional()}),Sl=ae.object({used:ae.number().optional(),size:ae.number().optional(),costAmount:ae.number().optional(),costCurrency:ae.string().optional()}),LE=ae.object({sessionId:ae.string(),upstreamSessionId:ae.string().optional(),cwd:ae.string(),title:ae.string().optional(),agentId:ae.string().optional(),currentModel:ae.string().optional(),currentUsage:Sl.optional(),importedFromMachine:ae.string().optional(),importedFromUpstreamSessionId:ae.string().optional(),parentSessionId:ae.string().optional(),forkedFromSessionId:ae.string().optional(),forkedFromMessageId:ae.string().optional(),originatingClient:ae.object({name:ae.string(),version:ae.string().optional()}).optional(),interactive:ae.boolean().optional(),priority:ae.number().int().nonnegative().optional(),updatedAt:ae.string(),attachedClients:ae.number().int().nonnegative(),status:ae.enum(["warm","cold"]).default("warm"),busy:ae.boolean().default(!1),awaitingInput:ae.boolean().default(!1),compactionState:ae.any().optional(),forkSynthesisState:ae.enum(["running","failed"]).optional(),_meta:ae.record(ae.unknown()).optional()}),bS=ae.object({sessionId:ae.string(),cwd:ae.string(),title:ae.string().optional(),updatedAt:ae.string().optional(),_meta:ae.record(ae.unknown()).optional()}),BE=ae.object({sessions:ae.array(bS),nextCursor:ae.string().optional()})});function vS(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 Xt(t){if(!t)return{};let e=t[At];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=th.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=Sl.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=vS(n.env);r!==void 0&&(s.env=r)}return s}function Po(t,e){return{...t??{},[At]:e}}var At,Ja=J(()=>{"use strict";vl();kl();At="hydra-acp"});import{z as ee}from"zod";var oh,Ya,ah,qE,WE,zE,dh,KE,ch,JE,lh,YE,VE,uh=J(()=>{"use strict";oh=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),Ya=ee.object({sessionId:ee.string()}),ah=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),qE=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:ah,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),WE=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),zE=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),dh=ee.object({sessionId:ee.string(),messageId:ee.string()}),KE=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),ch=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),JE=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),lh=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),YE=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),VE=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:ah,amendedAt:ee.number()})});import{z as Fs}from"zod";var fh,Va,gi,ph=J(()=>{"use strict";fh=Fs.object({agentId:Fs.string(),version:Fs.string(),source:Fs.enum(["binary","npm"]),phase:Fs.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Fs.number().optional(),totalBytes:Fs.number().optional(),packageSpec:Fs.string().optional()}),Va="hydra-acp/agents/install_progress",gi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Rt=J(()=>{"use strict";za();vl();Ja();kl();uh();ph()});import{nanoid as SS}from"nanoid";var Il,qt,Ir=J(()=>{"use strict";Rt();Il=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},qt=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 Il;let s=SS(),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 yi(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 wi(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 xl=J(()=>{"use strict"});import*as gh from"fs/promises";function $S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var AS,RS,bi,TS,ES,PS,MS,_S,mh,Xa,yh=J(()=>{"use strict";AS=64*1024*1024,RS=1*1024*1024,bi=64*1024,TS=6e4,ES=100,PS=1e3,MS=64*1024,_S=256*1024,mh=20;Xa=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??AS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(RS,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,bi));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,bi)),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,bi)),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,TS));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($S(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??ES,PS)),f=Math.max(1,Math.min(e.maxBytes??MS,_S)),p=Math.max(0,Math.min(e.contextBefore??0,mh)),h=Math.max(0,Math.min(e.contextAfter??0,mh)),m=[],y=[],v=[],b=0,S=!1,x=0,T=0,$=(K,H)=>{for(let G of v)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:K,line:H}),G.remaining--,b+=H.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(d.test(H)!==l&&m.length<u){let G={cursor:K,line:H};if(p>0&&y.length>0){G.before=y.slice();for(let be of G.before)b+=be.line.length}b+=H.length,m.push(G),h>0&&v.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:K,line:H});y.length>p;)y.shift();let D=m.length>=u&&v.length===0,Z=b>=f;return D||Z};for(let K=0;K<o.length;K++){if(o[K]!==10)continue;let H=o.subarray(x,K).toString("utf8"),L=r+x;if(x=K+1,T=x,$(L,H)){S=!0;break}}if(!S&&x<o.length&&this.closed){let K=o.subarray(x).toString("utf8"),H=r+x;$(H,K)&&(S=!0),T=o.length}let F=Math.min(r+T,this.writeCursor),j={matches:m,truncated:S,nextCursor:F,scannedBytes:T};return i>0&&(j.gap=i),this.closed&&F>=this.writeCursor&&(j.eof=!0),j}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(()=>gh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Za,wP,wh=J(()=>{"use strict";Za=[{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>",description:"Swap the agent backing this session, preserving context"},{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."}],wP=new Map(Za.map(t=>[t.verb,t]))});function bh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function vi(t,e){return Cl(t,e.map(n=>n.modelId))}function Cl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=bh(t),s=e.filter(i=>bh(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 ed=J(()=>{"use strict"});function vh(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=Al(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=Al(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?OS(r,i.outIndex,FS(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)?LS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!BS(f)&&(f=NS(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 Al(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function FS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function OS(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 LS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function BS(t){let n=Al(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function NS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Sh=J(()=>{"use strict"});function Si(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=Tl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=El(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Rl(c))):d==="turn_complete"&&i()}return i(),qS(s.join(`
16
- `),n)}function Rl(t){let e=HS(t),n=US(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function HS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function US(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of DS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${jS(r,200)}`)}return n}function Tl(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 El(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function jS(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function qS(t,e){if(t.length<=e)return t;let n=t.split(`
17
- `);for(;n.length>0;){let s=kh+n.join(`
18
- `);if(s.length<=e)return s;n.shift()}return kh}var kh,DS,td=J(()=>{"use strict";kh=`[older history truncated]
19
- `,DS=["file_path","filePath","path","command","pattern","query"]});function Pl(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??WS}`),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=Mo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=Mo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=Mo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=Mo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=Mo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Ih(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Ih(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=zS(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 Mo(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 Ih(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 zS(t,e){if(t.length===0||e<=0)return"";let n=KS(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 KS(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:Tl(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=El(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Rl(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var WS,xh=J(()=>{"use strict";td();WS="(untitled)"});import*as Dn from"fs/promises";async function _o(t,e){let n=_.queueFile(t);if(e.length===0){await Dn.unlink(n).catch(()=>{});return}await Dn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
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?`
10
+ subject: ${b.subject??"(unknown)"}
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(`
23
23
  `)+`
24
- `;await Dn.writeFile(n,s,"utf8")}async function Ch(t){let e=_.queueFile(t),n;try{n=await Dn.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 Ah(t){let e=_.queueFile(t);await Dn.unlink(e).catch(()=>{})}var Ml=J(()=>{"use strict";he()});import{customAlphabet as Mh}from"nanoid";import*as Fh from"fs/promises";function xr(){return`m_${$h()}`}function rt(t){return t.startsWith(gn)?t.slice(gn.length):t}function Wt(t,e){return t.code=e,t}function Eh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&QS.has(s)}function GS(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 XS(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 ZS(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 Ii(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 $o(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 ek(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 tk(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 nk(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 sk(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:xr()}}}function Fl(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 rk(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 ik(t){let e=ok(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=ak(t.resolver),n}function ok(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 ak(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 ki(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function $l(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Ph(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 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}
26
26
  ${s.join(`
27
- `)}`}function Ol(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 _h,$h,Rh,JS,Th,gn,YS,_l,VS,xi,QS,Hn=J(()=>{"use strict";xl();yh();wh();ed();Sh();xh();Ml();Rt();_h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",$h=Mh(_h,16),Rh=Mh(_h,16),JS=20,Th=20,gn="hydra_session_";YS=1e3,_l=300*1e3,VS=64,xi=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;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;_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;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;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??`${gn}${$h()}`,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.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.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??YS,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){tk(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),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){let r=e,i=this.injectCumulativeCost(e);for(let c=s;c<this.transformChain.length;c++){let d=this.transformChain[c];if(n.has(d.name)||!d.intercepts.has("response:session/update"))continue;let l=`t_${Rh()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on response:session/update: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return;if(f==="processing"){let p=c,h=i,m=new Set(n);await new Promise(y=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.runResponseChain(h,new Set([...m,d.name]),p+1).then(()=>y()).catch(()=>y()))},_l);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:()=>y(),timer:v,transformerName:d.name,method:"session/update",envelope:h,chainIdx:p,originatedBy:m,side:"response"})});return}n.add(d.name)}let o=nk(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=ek(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}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())}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");let s=this.agentId,r=this.cwd,i=this.agentArgs,o=this.forwardedEnv,a=this.currentModel,c=this.currentMode,d=this.spawnReplacementAgent;if(!d)throw new Error("agent spawning not configured for this session");let l=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],u=await d({agentId:s,cwd:r,agentArgs:i,...o?{forwardedEnv:o}:{},mcpServers:l});this.accumulateAndResetCost(),this.wireAgent(u.agent),await wi({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedModel:a,agentReportedModel:u.initialModel,logger:this.logger}),await yi({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedMode:c,agentReportedMode:u.initialMode,logger:this.logger}),u.agent.connection.drainBuffered("session/update");let f=[];if(this.historyStore)try{f=await this.historyStore.load(this.sessionId)}catch(b){this.logger?.warn(`swapUpstream: historyStore.load failed: ${b.message}`)}let p=Pl({synopsis:e.artifact,title:e.title,tail:f,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 u.agent.connection.request("session/prompt",{sessionId:u.upstreamSessionId,prompt:[{type:"text",text:p}]});let b=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${p.length} toolCalls=${b.toolCalls} thinkingChars=${b.thinkingChars} messageChars=${b.messageChars} used=${b.lastUsed??"?"} size=${b.lastSize??"?"} reply=${JSON.stringify(b.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let h=this.upstreamSessionId,m=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=u.agent,this.upstreamSessionId=u.upstreamSessionId,this.agentMeta=u.agentMeta,this.agentCapabilities=u.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let b of this.agentChangeHandlers)try{b({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(S){this.logger?.warn(`swapUpstream: agentChange handler failed: ${S.message}`)}if(this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...m!==void 0?{previousSummarizedThroughEntry:m}:{}})}catch(b){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${b.message}`)}await y.kill().catch(()=>{}),this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0});let v=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
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?`
28
+ Switched to ${r}.
29
+ `:`
28
30
  Compaction completed.
29
- `},_meta:{"hydra-acp":{synthetic:!0}}}});for(let b of this.clients.values())b.connection.notify("session/update",v).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 wi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await yi({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=JS){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(()=>{})}attach(e,n,s={}){if(this.closed)throw Wt(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw Wt(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:vh(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Eh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Fl(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 Wt(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw Wt(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=xr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Xt((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=ki(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:xr()};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>VS;){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 Wt(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=xr(),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=xr(),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 Wt(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_${Rh()}`,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??$l(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 v=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:$l(e))))},_l);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:y,timer:v,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)}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):_l,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{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:$l(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)}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(!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=ki((e??{}).prompt),r=Ol(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=Ii(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=Ii(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=$o(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=Ii(o.options);if(c.length>0){let d=$o(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(GS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(XS(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(",")}]`),ZS(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:"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(Za.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=Za.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=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:`
30
32
  ${e}
31
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}):
32
34
  ${s.join(`
@@ -39,7 +41,7 @@ ${s}
39
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(`
40
42
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
41
43
  ${a}
42
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=vi(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=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:`
43
45
  ${d}.
44
46
  ${l}:
45
47
  ${c.join(`
@@ -47,9 +49,9 @@ ${l}:
47
49
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(d=>d.id===i):!0,c=r.map(d=>{let l=d.id===i?"\u25B6 ":" ",u=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${u}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
48
50
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
49
51
  ${o}
50
- `},_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 Wt(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:`
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:`
51
53
  _(no config options advertised yet)_
52
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>Ph(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=>Uh(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
53
55
  ${u.join(`
54
56
 
55
57
  `)}
@@ -59,16 +61,16 @@ ${u.join(`
59
61
  Available options:
60
62
  ${l}
61
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:`
62
- ${Ph(o)}
63
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=Cl(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:`
64
+ ${Uh(o)}
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:`
64
66
  ${p}.
65
67
  ${h}:
66
68
  ${f.join(`
67
69
  `)}
68
- `},_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)throw Wt(new Error("/hydra agent requires an agent id"),z.InvalidParams);if(e===this.agentId)throw Wt(new Error(`already on agent ${e}`),z.InvalidParams);if(!this.spawnReplacementAgent)throw Wt(new Error("agent switching not configured for this session"),z.InternalError);let n=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await n({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let c of this.agentChangeHandlers)try{c(a)}catch{}return{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 Wt(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(`
69
- `)),{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 Wt(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=ki(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(`
70
- `)}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(-Th),i=Pl({synopsis:e,title:n,tail:r,tailK:Th});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}}}}),this.broadcastConfigOptions()}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 Xa(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??bi,bi)),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;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"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 n=this.promptQueue;this.promptQueue=[];for(let r of n){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ah(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>Fh.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(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.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}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(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Eh(e,r),o=i?sk(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.scheduleIdleEvent()}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 Wt(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=rk(s),i=xr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=b=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),b())},y=b=>b?.code===z.MethodNotFound;function v(b){if(l)return;let S=b.connection.request("session/request_permission",s);u.push({client:b}),f++,S.then(x=>{f--,m(()=>{let T=ik({toolCallId:r,result:x,resolver:b});for(let $ of u)$.client.clientId!==b.clientId&&$.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??Wt(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,v);for(let b of n)v(b)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:xr(),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(()=>_o(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}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=ki(e.prompt).replace(/\s+$/,""),s=!n.includes(`
71
- `)&&n.startsWith("/")?n.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(n):s==="/model"?i=await this.handleModelCommand(n):i=await this.handleSlashCommand(n,e.messageId),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})}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)}};QS=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 Ci}from"zod";var dk,Oh,Lh=J(()=>{"use strict";dk=Ci.object({source:Ci.string(),reason:Ci.string(),raisedAt:Ci.number(),payload:Ci.unknown()}),Oh=Ci.array(dk)});import{z as $e}from"zod";function Dh(t){let e=t.trim();if(e.length===0)return;let n=Ai(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Ai(e.slice(i,o+1)))}if(n===void 0){let i=Uh(e);i!==void 0&&(n=Ai(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,Nh))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Fo.safeParse(s.synopsis);i.success&&ck(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Hh(t){let e=t.trim();if(e.length===0)return;let n=Ai(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Ai(e.slice(d,l+1)))}if(n===void 0){let d=Uh(e);d!==void 0&&(n=Ai(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,Nh))}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=$e.array($e.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 Ai(t){try{return JSON.parse(t)}catch{return}}function Uh(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 ck(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 Bh,Fo,Nh,Ll,Bl,nd=J(()=>{"use strict";Bh=$e.object({status:$e.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:$e.number(),iter:$e.number().int().nonnegative().optional(),attempts:$e.number().int().nonnegative().optional(),lastError:$e.string().optional(),worker:$e.object({upstreamSessionId:$e.string(),pid:$e.number().int().nonnegative()}).optional()}),Fo=$e.object({goal:$e.string().optional(),outcome:$e.string().optional(),files_touched:$e.array($e.string()).optional(),tools_used:$e.array($e.string()).optional(),rejected_approaches:$e.array($e.string()).optional(),open_threads:$e.array($e.string()).optional(),decisions:$e.array($e.string()).optional(),file_edit_intentions:$e.array($e.string()).optional(),unresolved_errors:$e.array($e.string()).optional(),tool_state:$e.array($e.string()).optional()}),Nh=200,Ll=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
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:
72
74
  {
73
75
  "title": "short summary, max 80 chars",
74
76
  "synopsis": {
@@ -78,7 +80,7 @@ ${h}:
78
80
  "open_threads": ["work started but not finished"]
79
81
  }
80
82
  }
81
- Use empty arrays/strings where a field doesn't apply.`;Bl=`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.`;Kl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
82
84
  {
83
85
  "title": "short summary, max 80 chars",
84
86
  "goal": "the user's original ask",
@@ -90,293 +92,293 @@ Use empty arrays/strings where a field doesn't apply.`;Bl=`Reply with ONLY a JSO
90
92
  "unresolved_errors": ["errors left open at session end"],
91
93
  "tool_state": ["runtime state relevant for recall"]
92
94
  }
93
- Use empty arrays/strings where a field doesn't apply.`});import*as Ri from"fs/promises";import*as UP from"path";import{customAlphabet as lk}from"nanoid";import{z as ne}from"zod";function Oo(){return`${pk}${fk()}`}function yk(t){if(!Nl.test(t))throw new Error(`unsafe session id: ${t}`)}function ql(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,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 uk,fk,pk,Dl,Hl,hk,Ul,jl,mk,gk,Nl,sd,Wl=J(()=>{"use strict";he();yr();Lh();nd();uk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",fk=lk(uk,16),pk="hydra_lineage_";Dl=ne.object({name:ne.string(),description:ne.string().optional()}),Hl=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),hk=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Ul=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),jl=ne.object({name:ne.string(),version:ne.string().optional()}),mk=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),gk=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:Fo.optional(),compactionState:Bh.optional(),rollbackBreadcrumb:mk.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Ul.optional(),agentCommands:ne.array(Dl).optional(),agentModes:ne.array(Hl).optional(),agentModels:ne.array(hk).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:jl.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Oh.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Nl=/^[A-Za-z0-9_-]+$/;sd=class{async write(e){yk(e.sessionId);let n={version:1,...e};await Qt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Nl.test(e))return;let n=await hn(_.sessionFile(e));if(n!==void 0)try{return gk.parse(n)}catch{return}}async delete(e){if(Nl.test(e)){try{await Ri.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Ri.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 Ri.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 bk}from"url";import*as Lo from"path";import*as id from"fs";function vk(){try{let t=Lo.dirname(bk(import.meta.url));for(let e=0;e<8;e+=1){let n=Lo.join(t,"package.json");if(id.existsSync(n)){let r=JSON.parse(id.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=Lo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var pe,Cr,Zt=J(()=>{"use strict";pe=vk(),Cr="hydra-acp-cat"});function zl(t){let e=new Map;for(let n of Gh(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 Yh(t){return zl(t).map(e=>e.name)}function Kl(t){let e=new Map;for(let n of Gh(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 Vh(t){return Kl(t).map(e=>e.path)}function Qh(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Gh(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:Kh(i),paths:new Set},e.set(c,d)):d.toolName=Kh(i);for(let l of Jh(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 Jh(i.rawInput,i.locations))a.paths.add(c)}return e}function Kh(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Jh(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 Jl=J(()=>{"use strict"});import{promises as No}from"fs";import*as Zl from"path";async function Do(t){let e;try{e=await No.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Pk(e)}function Pk(t){let e=[];for(let n of t.split(`
94
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Ho(t,e,n=dm){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 Ar(t,e){await No.mkdir(Zl.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await No.writeFile(t,n.length>0?n.join(`
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
97
  `)+`
96
- `:"")}async function cm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await No.mkdir(Zl.dirname(t),{recursive:!0}),await No.appendFile(t,JSON.stringify(n)+`
97
- `,{encoding:"utf8"}))}function cd(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function eu(t,e,n=dm){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=Ho(r,o,n)))}return r}var dm,ld=J(()=>{"use strict";dm=500});import{z as Re}from"zod";function Uo(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 En(t){return $k.parse(t)}var Mk,_k,$k,Rr=J(()=>{"use strict";Wl();nd();Mk=Re.object({method:Re.string(),params:Re.unknown(),recordedAt:Re.number()}),_k=Re.object({sessionId:Re.string(),lineageId:Re.string(),upstreamSessionId:Re.string().optional(),agentId:Re.string(),cwd:Re.string(),title:Re.string().optional(),synopsis:Fo.optional(),summarizedThroughEntry:Re.number().int().nonnegative().optional(),currentModel:Re.string().optional(),currentMode:Re.string().optional(),currentUsage:Ul.optional(),agentCommands:Re.array(Dl).optional(),agentModes:Re.array(Hl).optional(),interactive:Re.boolean().optional(),originatingClient:jl.optional(),priority:Re.number().int().nonnegative().optional(),createdAt:Re.string(),updatedAt:Re.string()}),$k=Re.object({version:Re.literal(1),exportedAt:Re.string(),exportedFrom:Re.object({hydraVersion:Re.string(),machine:Re.string(),hydraHost:Re.string().optional()}),session:_k,history:Re.array(Mk),promptHistory:Re.array(Re.string()).optional(),toolBlobs:Re.record(Re.string()).optional()})});import{createHash as Jk}from"crypto";function lu(t){if(Array.isArray(t))return t.map(lu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=lu(t[n]);return e}return t}function Ns(t){let{tui:e,...n}=t,s=JSON.stringify(lu(n));return Jk("sha256").update(s).digest("hex").slice(0,16)}var Yo=J(()=>{"use strict";Ye()});function uu(t){return Math.floor(t/4)}function Pm(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=uu(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 Mm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var fu=J(()=>{"use strict"});function Vo(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var _m=J(()=>{"use strict"});import{posix as iI}from"path";import oI from"strip-ansi";function ct(t){return oI(t).replace(aI,"")}function Ae(t){return ct(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function qn(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 pI(n);case"agent_thought_chunk":case"agent_thought":return hI(n);case"user_message_chunk":return mI(n);case"prompt_received":return gI(n);case"tool_call":return yI(n,e);case"tool_call_update":return kI(n,e);case"plan":return CI(n);case"current_mode_update":return AI(n);case"current_model_update":return RI(n);case"turn_complete":return TI(n);case"usage_update":return fI(n);case"available_commands_update":return lI(n);case"available_modes_update":return uI(n);case"session_info_update":return cI(n);case"config_option_update":return dI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function dI(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 cI(t){let e=et(t,"title"),n=e!==void 0?Ae(e):void 0,s=t._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(n===void 0&&r===void 0)return null;let i={kind:"session-info"};return n!==void 0&&(i.title=n),r!==void 0&&(i.agentId=r),i}function Ad(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:Ae(r)};typeof s.description=="string"&&(i.description=Ae(s.description)),e.push(i)}return e}function lI(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Ad(e)}:null}function uI(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:Ae(r.id)};typeof r.name=="string"&&(i.name=Ae(r.name)),typeof r.description=="string"&&(i.description=Ae(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function fI(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 pI(t){let e=Qo(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Vo(t)}}function hI(t){let e=typeof t.text=="string"?ct(t.text):Qo(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Vo(t)}}function mI(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=Qo(t.content);return n===null?null:{kind:"user-text",text:n}}function gI(t){let e=EI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Om(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function $m(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 Rd(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=$m(r.oldText),o=$m(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 Lm(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:ct(n)}function yI(t,e={}){let n=et(t,"toolCallId")??et(t,"id");if(!n)return null;let s=et(t,"title")??et(t,"name")??et(t,"label")??"tool call",r=et(t,"name")??et(t,"title");if(Om(r)){let h=Lm(t);if(h!==null){let m=et(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Dm(Ae(s),t,e),o=et(t,"status"),a=et(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Rd(t);d!==null&&(c.editDiff=d);let l=Nm(t);l!==void 0&&(c.detail=l);let u=pu(t);u!==void 0&&(c.detailFull=u);let f=Bm(t);f!==void 0&&(c.locations=f);let p=Vo(t);return p!==void 0&&(c.workerTaskId=p),c}function Bm(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 Nm(t){let e=pu(t);if(e===void 0)return;let n=Ae(e),s=t.rawInput;return s&&typeof s.command=="string"?vI(n,Fm):SI(n,Fm)}function pu(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 ct(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 Xe(Ae(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 Xe(Ae(s))}}}function bI(t){for(let e of wI)if(t.startsWith(e))return!0;return!1}function Dm(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Xe(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 Xe(o)}return bI(t)?Xe(`/${t}`):n.cwd&&n.cwd.length>0?Xe(iI.resolve(n.cwd,t)):t}function vI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function SI(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 kI(t,e={}){let n=et(t,"toolCallId")??et(t,"id");if(!n)return null;let s=et(t,"title"),r=s!==void 0?Dm(Ae(s),t,e):void 0,i=et(t,"status"),o=Rd(t),a=Nm(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=et(t,"name")??s;if(Om(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=Lm(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=pu(t);u!==void 0&&(l.detailFull=u);let f=Bm(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=II(t);h!==null&&(l.errorText=h),xI(t,h)&&(l.upstreamInterrupted=!0)}let p=Vo(t);return p!==void 0&&(l.workerTaskId=p),l}function II(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Qo(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 ct(s)}return null}function xI(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 CI(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"?Ae(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 AI(t){let e=et(t,"currentModeId")??et(t,"currentMode")??et(t,"mode");return e?{kind:"mode-changed",mode:Ae(e)}:null}function RI(t){let e=et(t,"currentModel")??et(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:Ae(e),...s&&s.length>0?{availableModels:s}:{}}}function TI(t){let e=et(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 Qo(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ct(e.text):null}function EI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Qo(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function et(t,e){let n=t[e];return typeof n=="string"?n:void 0}var aI,Fm,wI,Ds=J(()=>{"use strict";he();_m();aI=/[\x00-\x08\x0b-\x1f\x7f]/g;Fm=64;wI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Mi(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=MI(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)PI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function _i(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 PI(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 MI(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=Rd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Td=J(()=>{"use strict";Ds()});function Wn(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 Oi=J(()=>{"use strict";Rt()});import{spawn as Qx}from"child_process";import{setTimeout as Gx}from"timers/promises";async function xg(){let t=await ls();if(t&&Tn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function Xx(t){let e=await Pr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===Ns(t)?"match":"mismatch":"missing"}async function js(t){let e=await Xx(t);if(e!=="match"){if(e==="mismatch"){let n=Ln();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...
98
- `),Hd(),await Ud(t)}}async function Dd(t){let e=await xg();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Pr(t,e=1e3){let n=await xg();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 Hd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Qx(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Ud(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Dd(t))return;await Gx(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Mr=J(()=>{"use strict";Ao();Yo();ui()});import*as Cg from"fs";import*as Ni from"fs/promises";async function Di(t,e,n){let s=eC(e),r;try{r=await Ni.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
99
- `),process.exit(1);return}throw c}let i=await Zx(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
100
- `);let o=!1,a=Cg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Ni.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Ni.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 Zx(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Ni.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 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(`
101
103
  `).slice(-n-1);process.stdout.write(d.join(`
102
104
  `)),o.endsWith(`
103
105
  `)||process.stdout.write(`
104
- `)}finally{await r.close()}return e}function jd(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 eC(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 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}
105
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}
106
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var Zo=J(()=>{"use strict"});import{WebSocket as sC}from"ws";async function _r(t,e,n=rC){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=To(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 sC(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 Cu(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 rC,Cu,ea=J(()=>{"use strict";Eo();rC=1e4,Cu=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 qd from"fs/promises";function iC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Ui(){let t=await ls();if(t&&Tn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await we();return _g(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function _g(t,e,n){return`${n?"https":"http"}://${iC(t)}:${e}`}async function Me(t,e={}){let n=await gr(),s=await Ui(),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 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}
107
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}
108
- `),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 Wd(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
109
- `),process.exit(2)),s=n?oC(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 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
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
111
113
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
112
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}
113
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function oC(t){return t.split(/\s+/).filter(e=>e.length>0)}async function qi(){let t=await qd.readFile(_.config(),"utf8");return JSON.parse(t)}async function Au(t){await qd.writeFile(_.config(),JSON.stringify(t,null,2)+`
114
- `,{encoding:"utf8",mode:384})}var qs=J(()=>{"use strict";Ye();ds();he();ui();ea()});async function nn(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 Ru(t,n):c}finally{clearTimeout(a)}}async function zn(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 nn(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 $g(t,e=fetch){let n=await nn(`${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 nn(`${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 nn(`${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 Kd(t,e,n={},s=fetch){let r=await nn(`${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 Kn(t,e,n=fetch){let s=await nn(`${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 Fg(t,e,n,s=fetch){let r=await nn(`${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 Og(t,e,n,s=fetch){let r=await nn(`${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 Lg(t,e,n=fetch){let s=await nn(`${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 Bg(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await nn(`${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 Ng(t,e,n=fetch){let s=await nn(`${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 Jd(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 Ru,ta=J(()=>{"use strict";Ru=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 Tu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Dg(t,e){let n=t??"?",s=Tu(e);return s?`${n}${aC}${s}`:n}function Hg(t){return t??"?"}function Ug(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Eu(e,n)}function Eu(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var aC,Pu=J(()=>{"use strict";aC="\u2022"});function jg(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(!Vd.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Vd.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Ki(t,e=Date.now()){return{session:rt(t.sessionId),upstream:lC(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:uC(t.status,t.busy,t.awaitingInput,cC(t.compactionState),t.forkSynthesisState),agent:Hg(t.agentId),model:Tu(t.currentModel)??"-",age:fC(t.updatedAt,e),title:t.title??"-",cwd:Xe(t.cwd),cost:Ug(t.currentUsage)}}function cC(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 lC(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function uC(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 Ji(t,e={}){let n=e.columns??Wi,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]=pC(zi[r],t.map(i=>i[r]));return s}function fC(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 pC(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ws(t,e,n,s={}){let r=s.columns??Wi,i=s.cwdMaxWidth??dC,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(Yd);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>Mu.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Yd);return b.length>n?b.slice(0,n):b}let d=r.filter(b=>!Mu.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*Yd.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:S}of a){if(S===c)continue;let x=b==="cwd"?Math.min(e[b],i):e[b],T=Math.min(x,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=(b,S,x)=>{if(b==="cwd")return na(t[b],S).padEnd(S);let T=hC(t[b],S);return x?T:T.padEnd(S)},v=r.map((b,S)=>Mu.has(b)?m(b,f.get(S)??0,S===h):o(b)).join(Yd);return v.length>n?v.slice(0,n):v}function hC(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function na(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 Vd,Wi,Mu,zi,Yd,dC,Qd=J(()=>{"use strict";Pu();he();Hn();Vd=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Wi=["session","state","age","cwd","title","agent","cost"],Mu=new Set(["cwd","title"]),zi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Yd=" ",dC=32});import{spawn as xC}from"child_process";import{Writable as CC}from"stream";function Gd(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=AC(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??xC,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}
115
- `)});let c=new CC({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}
116
- `)});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 AC(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 _u=J(()=>{"use strict"});import RC from"chalk";import{highlight as TC,supportsLanguage as Xd}from"cli-highlight";import ec from"string-width";function zs(t,e={}){switch(t.kind){case"user-text":{let n=$u(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 $u(t.text," ","agent");case"agent-thought":return $u(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return QC(t,e.maxPlanItems??YC);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 Fu(t,e){return Yi(t,e).styled}function Yi(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=Yi(h,e),y=c;a+=`^+${m.styled}${r}`;for(let v of m.links)l.push({start:y+v.start,end:y+v.end,url:v.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 v=t[y];if(v==="\\"&&y+1<t.length){y+=2;continue}if(v==="(")m+=1;else if(v===")"&&(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),v=Yi(m,e),b=c,S=y.startsWith("file://");S?a+=`${i}${v.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${v.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let x of v.links)l.push({start:b+x.start,end:b+x.end,url:x.url});c+=v.cleanLength,S&&l.push({start:b,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function EC(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 ey(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 ty(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
117
- `),l=!1,u="",f=[],p=i!==" ",h=(v,b,S=" ",x,T)=>{let $={prefix:S,body:v,bodyStyle:b};r!==void 0&&($.prefixStyle=r),x&&x.length>0&&($.links=x),T&&($.ansi=!0),c.push($)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let v=sy(u,f);for(let b of v){let S={prefix:" ",body:b.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),b.ansi&&(S.ansi=!0),c.push(S)}}else for(let v of f)h(v.replace(/\^/g,"^^"),n);f=[],u=""}};for(let v=0;v<d.length;v++){let b=d[v],S=b.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(b);continue}let x=b.match(/^(#{1,6})\s+(.*)$/);if(x){let H=x[1].length,L=x[2]??"",D=s?H===1?"heading-1":H===2?"heading-2":"heading-3":n,Z=s?ey(D):o;h(Fu(L,Z),D,m());continue}let T=d[v+1];if(b.includes("|")&&T!==void 0&&PC(T)&&sa(b).length===sa(T).length){let H=sa(b),L=[],D=v+2;for(;D<d.length&&d[D].includes("|");)L.push(sa(d[D])),D++;let Z=BC(H,L,a);for(let G of Z)r!==void 0&&(G.prefixStyle=r),c.push(G);v=D-1;continue}let $=b.match(/^(\s*)[-*+]\s+(.*)$/);if($){let H=$[1]??"",L=$[2]??"",D=Yi(L,o),Z=H.length+2,G=D.links.map(be=>({start:be.start+Z,end:be.end+Z,url:be.url}));h(`${H}\u2022 ${D.styled}`,n,m(),G,D.ansi);continue}let F=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(F){let H=F[1]??"",L=F[2]??"",D=F[3]??"",Z=Yi(D,o),G=H.length+L.length+2,be=Z.links.map(X=>({start:X.start+G,end:X.end+G,url:X.url}));h(`${H}${L}. ${Z.styled}`,n,m(),be,Z.ansi);continue}let j=b.trim()==="",K=Yi(b,o);h(K.styled,n,j?" ":m(),K.links,K.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Ks(t,e){return ty(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Vi(t){return ty(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function sa(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 PC(t){if(!t.includes("|"))return!1;let e=sa(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Zd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return ec(e)}function $C(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:ec(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:Zd(r)}),n=i}return e}function FC(t,e){let n=[],s="",r=0;for(let i of t){let o=ec(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 OC(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=FC(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=ec(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 LC(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,ny)),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 BC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Zd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Zd(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*ny,n-MC-(s-1)*_C);i=LC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",v=i[m],b=OC($C(y),v);f.push(b),b.length>p&&(p=b.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let v=0;v<s;v++){let b=f[v][m]??"",S=i[v],x=Zd(b),T=Fu(b,u);y.push(T+" ".repeat(Math.max(0,S-x)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(t,"heading-3",ey("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 sy(t,e){if(t.length===0||!Xd(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=TC(e.join(`
118
- `),{language:t,theme:NC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
119
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function HC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Xd("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Xd("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=DC[s];return r&&Xd(r)?r:""}function $u(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
120
- `),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 UC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Jn(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 ry(t){if(t.length<=4096&&t.split(`
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(`
121
123
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
122
124
  `);return i.length>40&&(s=i.slice(0,40).join(`
123
- `),r=!0),{text:s,truncated:r}}function ra(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 ${Jn(l-t.startedAt)}`}let c={prefix:` ${zC(t.status)} `,prefixStyle:KC(t.status),body:o,bodyStyle:GC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Ae(t.errorText),bodyStyle:"tool-status-fail"}),d}function iy(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
124
- `))e.push({prefix:" ",body:Ae(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Ae(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
125
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=HC(r);if(i.length>0){let o=sy(i,s.map(a=>Ae(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:Ae(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function ay(t){oy=t>=0?t:0}function Ou(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=` (~${UC(d)})`}else{let d=qC(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 ${Ae(Xe(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=Lu(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(...Ks(c)),s.length>0&&s.unshift({body:""}),s}function dy(t){let e=ct(t.oldText).split(`
126
- `),n=ct(t.newText).split(`
127
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function qC(t){let{oldLines:e,newLines:n}=dy(t),s=0,r=0;for(let i of cy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Zg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Lu(t,e={}){let n=e.maxLines??jC,s=e.contextLines??oy,{oldLines:r,newLines:i}=dy(t),o=cy(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(Zg(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(Zg(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(`
128
- `)}function cy(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(...WC(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 WC(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 Bu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function zC(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 KC(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 ly(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ks(t.plan));let n=t.status;if(n!==void 0){let s=JC(n);s!==null&&e.push(s)}return e}function JC(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 VC(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 QC(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}=VC(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"?"[~]":"[ ]",v=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Fu(b,EC(v));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:v})}return f}function GC(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 ny,MC,_C,tt,NC,DC,jC,oy,YC,Qi=J(()=>{"use strict";he();Ds();ny=6,MC=2,_C=3;tt=new RC.Instance({level:3}),NC={keyword:tt.blueBright,built_in:tt.cyan,type:tt.cyanBright,literal:tt.blue,number:tt.greenBright,string:tt.yellow,regexp:tt.red,comment:tt.gray,function:tt.yellow,title:tt.yellow,class:tt.yellowBright,attr:tt.cyan,attribute:tt.cyan,variable:tt.white,params:tt.white,meta:tt.magenta,symbol:tt.magenta,addition:tt.greenBright,deletion:tt.redBright,section:tt.cyan,tag:tt.cyan,name:tt.cyanBright};DC={".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"};jC=40,oy=Number.POSITIVE_INFINITY;YC=5});import{highlight as XC,supportsLanguage as ZC}from"cli-highlight";async function fy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
129
- `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Me(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Me(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=En(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
130
- `),process.exit(1)}let u=Mi(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:_i(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
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(`
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(`
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}
131
133
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
132
- `);return}let i=Gd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Nu(r,a)),await i.flush()}function Nu(t,e){if(t.length===0)return`No file edits found in this session.
133
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=nA(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
134
- `:n.join("")}function eA(t){let e=[];for(let n of t.hunks){let s=Lu(n,{maxLines:1/0});tA(s)&&e.push({body:s,oldCount:uy(n.oldText),newCount:uy(n.newText)})}return e}function tA(t){if(t.length===0)return!1;for(let e of t.split(`
135
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function nA(t,e){let n=eA(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(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(`
136
138
  `)+`
137
139
 
138
- `;return!e||!ZC("diff")?i:XC(i,{language:"diff"})}function uy(t){if(t.length===0)return 0;let e=t.split(`
139
- `);return e[e.length-1]===""&&e.pop(),e.length}var Du=J(()=>{"use strict";qs();Rr();Td();Qi();_u()});async function py(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
140
- `),process.exit(2));let n=await Me(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Me(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=En(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
141
- `),process.exit(1)}let a=ju(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Mi(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:_i(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
142
- `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=Gd({disabled:e.noPager===!0});f.stream.write(tc(a,e.verbose===!0)),f.stream.write(`
143
- `),f.stream.write(Nu(d??[],u)),await f.flush();return}process.stdout.write(tc(a,e.verbose===!0))}function ju(t,e){let n=t.session,s=t.history,r=Qh(s),i=zl(s),o=Kl(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 tc(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:")}${rA(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,Hu),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>Hu&&n.push(` ... ${t.tools.length-Hu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>sA.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,Uu),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>Uu&&n.push(` ... ${o.length-Uu} more (use --verbose to see all)`)}return n.join(`
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)+`
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(`
144
146
  `)+`
145
- `}function rA(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 Hu,Uu,sA,qu=J(()=>{"use strict";qs();Rr();Jl();Td();_u();Du();Hu=10,Uu=15,sA=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var _y={};qc(_y,{assertKnownAgent:()=>rc,resolveAgentIdOrExit:()=>Ku,runAgentsAdd:()=>Xu,runAgentsInstall:()=>Ju,runAgentsList:()=>zu,runAgentsLogs:()=>Vu,runAgentsPin:()=>Gu,runAgentsRefresh:()=>ic,runAgentsRemove:()=>Zu,runAgentsSet:()=>Qu,runAgentsSync:()=>Yu,runRegistryPin:()=>oc});async function zu(){let e=(await Me("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
146
- `);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:fs(s.id,n.map(a=>a.id)),name:fs(s.name,n.map(a=>a.name)),version:fs(s.version,n.map(a=>a.version)),source:fs(s.source,n.map(a=>a.source)),distributions:fs(s.distributions,n.map(a=>a.distributions)),installed:fs(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 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
149
  `);for(let a of n)process.stdout.write(i(a)+`
148
- `);let o=e.fetchedAt!==void 0?` (synced ${ji(e.fetchedAt)})`:"";process.stdout.write(`
150
+ `);let o=e.fetchedAt!==void 0?` (synced ${Ki(e.fetchedAt)})`:"";process.stdout.write(`
149
151
  Registry version: ${e.version}${o}
150
- `)}async function rc(t){if((await we()).agents[t]!==void 0)return;let n;try{let r=await Me("/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.
151
- `),process.exit(2))}async function Ku(t,e){let n;try{let r=await Me("/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 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
154
  `),process.exit(2))}process.stderr.write(`${e}: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
153
- `),process.exit(2)}async function Ju(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
154
- `),process.exit(2);return}let e=await Ku(t,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
155
- `);let s=(await Me(`/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 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"}
156
158
  `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
157
159
  `),s.command&&process.stdout.write(` \u2192 ${s.command}
158
- `)}async function Yu(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
159
- `),process.exit(2);return}let e=await Ku(t,"hydra agent sync"),s=(await Me(`/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).
160
- `);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:fs(i.id,r.map(c=>c.id)),upstream:fs(i.upstream,r.map(c=>c.upstream)),cwd:fs(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 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)+`
161
163
  `);for(let c of r)process.stdout.write(a(c)+`
162
164
  `);process.stdout.write(`
163
165
  Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
164
- `)}async function Vu(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
165
- `),process.exit(2);return}let n=_.agentLogFile(t);await Di(n,e,"No log file (agent never ran?)")}async function Qu(t,e){let n=await we();if(!t){let c=await Py()??Wu(await qi());process.stdout.write(`${Ey(c)}
166
- `);return}let s;try{let a=await Me("/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 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(", ")}).
167
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(", ")}
168
- `),process.exit(1);return}}e!==void 0?await dp(t,e):await Oa(t);let i=Wu(await qi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
169
- `),process.stdout.write(`${Ey(i)}
170
- `);let o=await Py();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${My(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
171
- `))}function Ey(t){return`Default agent is ${My(t)}`}function My(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function Wu(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 Py(){try{let t=await Me("/v1/config",{rethrowNetworkError:!0});return t.ok?Wu(t.body):void 0}catch{return}}async function ic(){let e=(await Me("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
172
- `)}async function Gu(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
173
- `),process.exit(2);return}await cp(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
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}.
174
176
  `):process.stdout.write(`Pinned ${t} to ${e}.
175
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Xu(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 df(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
176
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._-]+
177
- `),process.exit(2);return}let n=Wd(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 Yc(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(" "):""}
178
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Zu(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
179
- `),process.exit(2);return}await Yc(t,void 0),process.stdout.write(`Removed local agent ${t}.
180
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function oc(t){await lp(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.
181
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function fs(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var ef=J(()=>{"use strict";Ye();he();Zo();qs()});var ac,ps,Xi,ia,$y,oa,tf,dc,Or,Fy,Lr,Oy,Br,Ly,Nr,Zi,eo,By,to,Ny,Dy,Hy,nf,Uy,cc,lc,aa,jy,qy,da=J(()=>{"use strict";ac="\x1B[?2004h",ps="\x1B[?2004l",Xi="\x1B[200~",ia="\x1B[201~",$y="\x1B[?1049l",oa="\x1B[?7h",tf="\x1B[?7l",dc="\x1B[?25h",Or="\x1B[?1l",Fy="\x1B[>1u",Lr="\x1B[<u",Oy="\x1B[>4;2m",Br="\x1B[>4;0m",Ly="\x1B[>5;1m",Nr="\x1B[>5;0m",Zi="\x1B[?1000l",eo="\x1B[?1002l",By="\x1B[?1003l",to="\x1B[?1006l",Ny="\x1B[?1015l",Dy="\x1B[?w",Hy="\x1B[=24;1w",nf="\x1B[=0;0w",Uy="\x1B]22;pointer\x07",cc="\x1B]22;default\x07",lc="\x1B[?1004h",aa="\x1B[?1004l",jy="\x1B[?2026h",qy="\x1B[?2026l"});function Pn(){process.stdout.write(Lr),process.stdout.write(ps),process.stdout.write(Br),process.stdout.write(Nr),process.stdout.write(Zi),process.stdout.write(eo),process.stdout.write(to),process.stdout.write(Or),process.stdout.write("\x1B>")}function sn(t){return t.width??80}function hs(t){return t.height??24}function Mn(t,e){let n=sn(t),s=hs(t),r=e.contentWidth??oA,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=Wy.repeat(a-2),p=uA(f,e.title);t.moveTo(l,u),t.dim.noFormat(aA),fA(t,p),t.dim.noFormat(dA);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(zy),t.moveTo(l+a-1,u+h),t.dim.noFormat(zy);return t.moveTo(l,u+d-1),t.dim.noFormat(cA+Wy.repeat(a-2)+lA),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function uA(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 fA(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 We(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function uc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Yn(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),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),e.on("key",d),e.on("resize",c)})}var oA,Wy,zy,aA,dA,cA,lA,Dr=J(()=>{"use strict";da();oA=64,Wy="\u2500",zy="\u2502",aA="\u250C",dA="\u2510",cA="\u2514",lA="\u2518"});function Ky(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 mA(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??pA,footer:hA};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}] ${Ky(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 gA(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 yA(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function Jy(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[At];if(!(typeof s!="object"||s===null))return s}function wA(t){let e=Jy(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function bA(t){let e=Jy(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 Yy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!yA(e))throw e;let n=wA(e)??t.fallbackAgentId??"",s=bA(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 vA(t,e,n){t.grabInput(!1),Pn(),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+`
182
- `);let r=n?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{t.grabInput({})}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(`
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+`
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(`
183
185
  failed to spawn ${e.command}: ${c.message}
184
186
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
185
187
  failed to spawn ${e.command}: ${a.message}
186
- `),i({exitCode:-1})}})}function SA(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 sf(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(SA(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 Vy(t,e,n,s,r){Pn();let i=mA(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=Mn(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(We(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(We(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(We(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(We(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(We(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(We(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(We(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 Yn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=gA(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 ${Ky(y)}\u2026`,d();let v=r.runTerminalAuth??(b=>vA(t,b));(async()=>{let b=await sf(y,{authenticate:r.authenticate,runTerminalAuth:v});if(b.kind==="terminal-completed"){h("terminal-completed");return}if(b.kind==="retry"){h("retry");return}if(b.kind==="error"){c=b.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${b.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var pA,hA,rf=J(()=>{"use strict";za();Ja();Dr();pA="This agent requires authentication before use.",hA="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as ew}from"timers/promises";function PA(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var AA,RA,TA,EA,so,of=J(()=>{"use strict";ea();Oi();AA=200,RA=5e3,TA=2,EA=60,so=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(()=>{}),ew(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=AA;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await _r(s,this.opts.subprotocols);this.bindStream(Wn(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>=EA)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 ew(n),this.destroyed)return;n=Math.min(n*TA,RA)}}bindStream(e){this.current=e,e.onMessage(n=>{if(PA(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}
187
- `)}}});function tw(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 Hr(t){return{outcome:{outcome:"selected",optionId:tw(t,["allow_once","allow_always"])}}}function nw(t){return{outcome:{outcome:"selected",optionId:tw(t,["reject_once","reject_always"])}}}function hc(t){return t&&typeof t=="object"?t:void 0}function ca(t){return typeof t=="string"&&t.length>0?t:void 0}function sw(t){let e=hc(t),n=hc(e?.toolCall),s={paths:[]};if(!n)return s;let r=ca(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=ca(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(hc(d)?.path);let c=hc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=ca(c.command);d&&(s.command=d);let l=ca(c.url);l&&(s.url=l);let u=ca(c.description);u&&(s.description=u)}return s}function rw(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 mc=J(()=>{"use strict"});function ER(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Iw(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 PR(t,e){let n=Iw(t),s=Iw(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 la(){if(Ys!==void 0)return Ys;if(ER())return Ys=null,Ys;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:xw,version:pe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&PR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Ys={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{}Ys=null}}catch{Ys=null}return Ys}function ua(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${xw}`}var xw,Ys,cf=J(()=>{"use strict";Zt();xw="@hydra-acp/cli"});import*as fa from"fs/promises";import*as lf from"path";async function pa(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=lf.resolve(Ze(e)),s;try{s=await fa.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 Cw(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 fa.stat(r)).isDirectory())return r}catch{}return null}async function Aw(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=lf.resolve(Ze(r)),o;try{o=(await fa.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 uf=J(()=>{"use strict";Ye()});var Rw,Tw,Ew,Pw=J(()=>{"use strict";Rw="hydra-acp/question/list",Tw="hydra-acp/question/answer",Ew="hydra-acp/question/dismiss"});import{EventEmitter as MR}from"events";import{WebSocket as _R}from"ws";function $R(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=To(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 _R(t,e,n),o=()=>{i.off("error",a),s(Wn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Mw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??$R,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new qt(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 Kd(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 ff(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(()=>{}),Kn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[At]:{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 ff,_w=J(()=>{"use strict";Eo();ta();Ir();Oi();Rt();ff=class extends MR{_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(()=>{}),Kn(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 pf,vc,$w=J(()=>{"use strict";Qi();Ds();pf=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())}},vc=class extends pf{_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=qn(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=Vi(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Vi(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=ra(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=ra(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=zs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Ks(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 OR(t,e){return`[pasted #${t} +${e} lines]`}var FR,Sc,hf,LR,ms,mf=J(()=>{"use strict";FR=/\[pasted #(\d+) \+\d+ lines\]/g,Sc=/\[pasted #(\d+) \+\d+ lines\]$/,hf=/^\[pasted #(\d+) \+\d+ lines\]/;LR=500,ms=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;lastEscapeAt=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>LR&&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.lastEscapeAt=null,this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){this.lastEscapeAt=null,this.recordEdit();let n=e.text.split(`
188
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(OR(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e!=="escape"&&(this.lastEscapeAt=null),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.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":{if(this.turnRunning)return this.lastEscapeAt=null,[{type:"cancel",prefill:!0}];let n=Date.now();return this.lastEscapeAt!==null&&n-this.lastEscapeAt<=500?(this.lastEscapeAt=null,[{type:"switch-session"}]):(this.lastEscapeAt=n,[])}}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
189
- `)}expandPastes(e){return e.replace(FR,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}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 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(`
190
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(`
191
- `);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(Sc);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(hf);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(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=`
192
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+`
193
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=`
194
196
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
195
- `+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(Sc);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(Sc);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(hf);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(Sc);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(hf);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(`
196
- `),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 oo,kc,gf=J(()=>{"use strict";oo=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())}},kc=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 BR from"path";function ha(t){return Fw[BR.extname(t).toLowerCase()]??null}function NR(t){return ha(t)!==null}function yf(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(!DR.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 HR(t){return yf(t)!==null}function bn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Ow(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(!HR(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!NR(o))return null;n.push(o)}return n.length>0?n:null}var Vn,Fw,DR,Ic=J(()=>{"use strict";Vn=10*1024*1024,Fw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};DR=new Set(Object.values(Fw))});import UR from"string-width";function Lw(t,e){if(!t||e<=0)return 0;let n=0;for(let s of jR.segment(t)){let r=UR(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Bw(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 jR,Nw=J(()=>{"use strict";jR=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as qR}from"child_process";import wf from"fs/promises";import WR from"os";import zR from"path";async function Uw(t={}){let e={...bf,...t};return e.platform==="darwin"?VR(e):e.platform==="linux"?QR(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function jw(t={}){let e={...bf,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await ao(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await ao(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 ma(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:vf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function qw(t,e={}){let{target:n="both",...s}=e,r={...bf,...s},i=await KR(r,t,n);if(i.ok)return i;let o=JR(r,t,n);return o.ok||o.reason!==Ww?o:i}async function KR(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await xc(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 ao(t,"wl-copy")?Hw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await ao(t,"xclip")?Hw(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 Hw(t,e,n,s,r,i,o){let a=n;if(i){try{await xc(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await xc(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await xc(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function JR(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Dw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Dw} 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??YR)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Ww}}function YR(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 VR(t){let e=zR.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 zw(t.spawn,"osascript",s);let r=await t0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await wf.unlink(e).catch(()=>{})}try{let r=await ma(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:vf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function QR(t){let e=await GR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await e0(t,e),s=ZR(n);if(s)try{let r=await ma(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Vn?{ok:!1,reason:`clipboard image is ${bn(r.length)}, max ${bn(Vn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await ma(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:vf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function GR(t){return t.env.WAYLAND_DISPLAY&&await ao(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await ao(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function ZR(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of XR)if(e.has(n))return n;return null}async function e0(t,e){try{return(await ma(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
197
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function vf(t){return t.replace(/\r\n?/g,`
198
- `)}async function ao(t,e){try{return await zw(t.spawn,"which",[e]),!0}catch{return!1}}async function t0(t,e){try{let n=await wf.readFile(t);return e&&await wf.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Vn?{ok:!1,reason:`clipboard image is ${bn(n.length)}, max ${bn(Vn)}`}:{ok:!0,kind:"image",attachment:{mimeType:ha(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function zw(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 xc(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 ma(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 bf,Dw,Ww,XR,Sf=J(()=>{"use strict";Ic();bf={platform:process.platform,env:process.env,spawn:qR,tmpdir:WR.tmpdir};Dw=74994;Ww="no TTY available for OSC 52 clipboard write";XR=["image/png","image/jpeg","image/gif","image/webp"]});function n0(){ga===0&&process.stdout.write(jy),ga++}function s0(){ga!==0&&(ga--,ga===0&&process.stdout.write(qy))}function Oe(t){n0();try{t()}finally{s0()}}var ga,kf=J(()=>{"use strict";da();ga=0});import{spawn as r0}from"child_process";import{statSync as i0}from"fs";import{homedir as Kw}from"os";import{isAbsolute as Jw,resolve as o0}from"path";import ze from"string-width";import a0 from"wrap-ansi";function g0(t){let e=t.replace(/\r\n?$|\n$/,"");return m0.test(e)?e:null}function y0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function Yw(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 ys(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 Qs(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 Vw(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){gs(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){gs(t,e.slice(c),n,o);return}d>c&&gs(t,e.slice(c,d),n,o);let l=r!==null&&d===r;gs(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function ya(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function gs(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 w0(t,e){return e<=0?[t]:t.length===0?[""]:a0(t,e,{hard:!0,trim:!1}).split(`
199
- `)}function rb(t){sb=t}function ib(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 Vs(t){return ze(t,{ambiguousIsNarrow:!sb})}function co(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 b0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Qw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=co(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 Gw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=co(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function v0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=co(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function ob(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(co(t,e))return!0;return!1}function*$f(t){let e=0;for(;e<t.length;){let n=co(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(co(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 _f.segment(t.slice(e,s)))yield{text:i,width:Vs(i)};e=s}}function S0(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 k0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&ob(t);return!s&&!nb.test(t)?I0(t,e):x0(t,e,s)}function I0(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 x0(t,e,n){let s=[],r=n?[...$f(t)]:C0(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 C0(t){let e=[];for(let{segment:n}of _f.segment(t))e.push({text:n,width:Vs(n)});return e}function bt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&ob(t);if(!s&&t.length<=e&&!nb.test(t))return t;if(!s)return Vs(t)<=e?t:e<=1?Xw(t,e):Xw(t,e-1)+"\u2026";let r=[...$f(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?Zw(r,e):Zw(r,e-1)+"\u2026"}function Xw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of _f.segment(t)){let i=Vs(r);if(s+i>e)break;n+=r,s+=i}return n}function Zw(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 A0(t){let e=t.indexOf(`
200
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function eb(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Ac(t.used)}/${Ac(t.size)}`):e.push(Ac(t.used)):typeof t.size=="number"&&e.push(`/${Ac(t.size)}`),typeof t.costAmount=="number"&&e.push(Eu(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Ac(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Tc(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 jr(){let t=[Zi,eo,By,to,Ny,nf,ps,Br,Nr,Lr,Or,"\x1B>",oa,dc,cc,"\x1B]9;4;0\x07",$y].join("");try{process.stdout.write(t)}catch{}}function ab(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 tb(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 If,Cc,xf,Cf,d0,He,Ve,c0,Qe,Af,Rf,l0,u0,f0,Tf,Ef,Pf,p0,h0,m0,Rc,nb,_f,sb,b0,Mf,Ff=J(()=>{"use strict";gf();Pu();he();Hn();Ic();Qi();Nw();Sf();kf();da();If=500,Cc=1,xf=/[A-Za-z0-9_]/,Cf=/[A-Za-z0-9_./\-~+@]/,d0=/\x1b\[[0-9;]*[A-Za-z]/g,He=1,Ve=0,c0=1,Qe=1,Af=8,Rf=5,l0=12,u0=12,f0=30,Tf=6,Ef=4,Pf=2,p0=1e3,h0=1e4,m0=/^(https?|ftp):\/\/\S+$/;Rc=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??p0,this.painter=new oo(this.term),this.scheduler=new kc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??h0,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(tf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!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),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(cc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(oa),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(jr(),this.term.fullscreen(!1),this.term(`
201
- `)))}installBracketedPaste(){process.stdout.write(ac),process.stdout.write(Oy),process.stdout.write(Ly),process.stdout.write(Fy),process.stdout.write(lc);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(ps),process.stdout.write(Br),process.stdout.write(Nr),process.stdout.write(Lr),process.stdout.write(aa),process.stdout.write(Or),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(Dy),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(nf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>jr(),this.onProcessSignal=e=>{jr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{jr(),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(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(`
202
204
  uncaught: ${e.stack??e.message}
203
- `),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(Hy),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(Xi)){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(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(`
204
206
  `)){let s=n.split(`
205
- `);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=tb(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=tb(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=Xi,s=ia;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,`
206
- `);this.pasteBuffer="";let a=Ow(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=g0(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(`
207
- `),[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=Mf(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&&Oe(()=>{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)),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(d0,""):(c=a.slice(o.start,o.end),ya(r.bodyStyle)&&(c=Gw(c))),n.push(c)}return n.join(`
208
- `)}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(tf),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=Tc(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=y0(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);if(this.setPointerShape(d!==null?"pointer":"default"),c==="move"){let l=d?.key??null,u=d?.sub??null;(l!==this.hoveredBlockKey||u!==this.hoveredSubKey)&&(this.hoveredBlockKey=l,this.hoveredSubKey=u,this.hoveredRunKeys=l!==null&&this.onHoverRun?this.onHoverRun(l)??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)<=Cc&&Math.abs(o.y-d.y)<=Cc&&Date.now()-d.t<=If||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<=If&&Math.abs(e.x-r.x)<=Cc&&Math.abs(e.y-r.y)<=Cc){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}=Qw(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),!xf.test(r[a]))return null;let c=a;for(;c>0&&xf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&xf.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}=Qw(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),!Cf.test(r[a]))return null;let c=a;for(;c>0&&Cf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Cf.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==="~"?Kw():`${Kw()}/${n.slice(2)}`);let s=Jw(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=Jw(n)?n:o0(this.sessionbar.cwd,n);if(s)return i;try{if(i0(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=r0(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)},If);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&&qw(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"?Uy:cc))}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=Vs(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let v=ya(p.bodyStyle)?Bw($f(p.body),y):Lw(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+v}}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()-He-Qe-Ve-c0-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),Oe(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Ve-Qe-He;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(n-He),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=Dg(this.sessionbar.agent,this.sessionbar.model),i=Xe(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=ze(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=ze(l),f,p;if(s){let b=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-b)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=bt(i,f),m=s?bt(s,p):"",y=ze(h)+(s?u+ze(m):0),v=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(v)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=Mf(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?Jn(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=eb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+ze(o)+ze(u)+f.length+ze(s);for(let T of c)y+=ze(" \xB7 ")+ze(T.text);y+=ze(p);let v=ze(h)+ze(d)+ze(m),b=Math.max(0,n-y-v),S="\u2500".repeat(b),x=`sep|${n}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,x,()=>{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=ze(i)+ze(a)+ze(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 v=0;v<m.length;v++){v>0&&this.term.dim(" \xB7 ");let b=m[v],S=null;b.includes("mode")?S="mode":b.includes("pick")?S="pick":b.includes("guide")?S="guide":b.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(b):this.term.dim(b)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+ze(i)+1,y=r.split(" \xB7 ");for(let v of y){let b=ze(v),S=[m,m+b-1];v.includes("mode")&&h.mode===null?h.mode=S:v.includes("pick")&&h.pick===null?h.pick=S:v.includes("guide")&&h.guide===null?h.guide=S:v.includes("detach")&&h.detach===null&&(h.detach=S),m+=b+ze(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Mf(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=eb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+ze(n)+i.length+ze(r)+o.length+ze(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),v=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),x=Yw("sb",e,m,this.scrollbackHighlight,y,v)+(S?"|H":"");this.paintRow(p,x,()=>{m&&this.writeFormattedLine(m,e,y,u,v,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(Rf,this.queuedTexts.length)}chipRows(){return Math.min(Ef,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(Tf,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-He-Qe-Ve,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>Tf,h=this.completions.length-Tf+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),v=f.description??"",b=n-y.length-4,S=b>0?bt(v,b):"";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-He-Qe-Ve-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Ef,u=this.attachments.length-Ef,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${bn(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(S0(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-He-Qe-Ve,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>Rf,p=this.queuedTexts.length-Rf,h=u===void 0?"":f?`+ ${p+1} more queued`:bt(A0(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 v=`\u23F3 ${h}`,b=v+" ".repeat(Math.max(0,n-1-v.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(b)})}}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=ys(s.buffer,n),i=Qs(r,s,Af),o=this.term.height-i.rendered-Ve-Qe-He+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-Pf-Ve-Qe-He+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${bt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${bt(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-Ve-Qe-He+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(` ${bt(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}. ${bt(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-Ve-Qe-He+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 ${bt(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(` ${bt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${bt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(f0,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-Ve-Qe-He+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} ${bt(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(` ${bt(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}. ${bt(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-Ve-Qe-He;this.drawSeparator(s),this.drawBottomSeparator(e-He)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Ve-Qe-He+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ve-Qe-He;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Ve-Qe-He+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ve-Qe-He;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Pf-Ve-Qe-He+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Ve-Qe-He+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Ve-Qe-He;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Ve-Qe-He+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=ys(s.buffer,n),i=Qs(r,s,Af),a=this.term.height-i.rendered-Ve-Qe-He+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Ve-Qe-He;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 Pf;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=ys(s.buffer,n);return Math.min(Af,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(l0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(u0,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-Ve-Qe-He+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 ${bt(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}${bt(`${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()-Ve-Qe-He,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=Yw(`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=Vs(r),o=Math.max(1,n-i-1),a=ya(e.bodyStyle),c=e.ansi?w0(e.body,o):k0(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&&gs(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-Vs(e.prefix??"")),c=ya(e.bodyStyle),d=e.ansi?e.body:bt(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;Vw(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else gs(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=ya(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Gw(m)),gs(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=v0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Vw(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):gs(this.term,d,e.bodyStyle,o);if(e.fillRow){let u=e.ansi?ze(d):Vs(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;gs(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)}};nb=/[^\x20-\x7e]/,_f=new Intl.Segmenter(void 0,{granularity:"grapheme"}),sb=!1;b0=/[a-zA-Z+\-:_!#/]/;Mf=rt});function R0(t,e,n=Ec){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 db(t,e){Pn();let n=rt(e.sessionId),s=e.importedFromMachine??"another machine",r=Xe(e.cwd),i=Ec.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Ec.length*2+2,d=Mn(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(We(p.value,l-p.label.length-2)),f++;return f++,cb(t,d,f,{intro:"What do you want to do?",choices:Ec,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Yn({term:t,render:o,onKey:(a,c,d,l)=>{let u=T0(a,d);if(!u)return;let f=R0(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 cb(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(uc(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 T0(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 lb(t,e,n){let s=rt(e.sessionId),r=e.title??Xe(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=Mn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(We(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+We(r,d-2)),l++,l++,cb(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 Ec,Of=J(()=>{"use strict";he();Hn();Dr();Ec=[{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 ba(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 ub(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=ba(e);return o.length<=r.length?null:o+i}var Pc=J(()=>{"use strict"});import*as fb from"os";async function Wr(t,e,n={}){let s=n.defaultCwd??(e?await Cw(e.cwd):void 0)??fb.homedir();Pn();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:Xe(e.cwd)}]:[],a=s,c=null,d=!1,l=null,u=[],f=[],p=()=>{u.push(a),u.length>500&&u.shift(),f=[]},h=()=>{let x=u.pop();x!==void 0&&(f.push(a),a=x)},m=()=>{let x=f.pop();x!==void 0&&(u.push(a),a=x)},y=()=>{let x=o.length+6;l=Mn(t,{contentHeight:x,title:r});let T=l.contentW,$=0;for(let F of o)t.moveTo(l.contentX,l.contentY+$),t.dim.noFormat(` ${F.label}`),t.noFormat(We(F.value,T-F.label.length-2)),$++;$++,t.moveTo(l.contentX,l.contentY+$),t.noFormat(` ${i}`),$+=2,b($),$+=2,c!==null?(t.moveTo(l.contentX,l.contentY+$),t.red.noFormat(` ${We(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+$),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},v=()=>o.length+3,b=x=>{if(!l)return;let T=x??v();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 $=l.contentW-6-2;t.noFormat(E0(a,$)),d||t.bgWhite(" ")},S=()=>{if(b(),!l)return;let x=v()+2;t.moveTo(l.contentX,l.contentY+x).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+x),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+x),c!==null?t.red.noFormat(` ${We(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Yn({term:t,render:y,hideCursor:!1,onKey:(x,T,$,F)=>{if(!d){if(x==="ENTER"||x==="KP_ENTER"){let j=a;d=!0,c=null,S(),pa(j).then(K=>{if(d=!1,K.ok){F({kind:"ok",path:K.path});return}c=K.reason,S()});return}if(x==="ESCAPE"){F({kind:"back"});return}if(x==="CTRL_C"||x==="CTRL_D"){F({kind:"cancel"});return}if(x==="TAB"){d=!0,Aw(a).then(j=>{if(d=!1,j.matches.length===0)return;let K;if(j.matches.length===1)K=j.prefix+j.matches[0];else{let H=ba(j.matches);if(H.length<=j.basePrefix.length)return;K=j.prefix+H}K!==a&&(p(),a=K,c=null,S())});return}if(x==="BACKSPACE"){a.length>0&&(p(),a=a.slice(0,-1),c=null,S());return}if(x==="CTRL_U"){a.length>0&&(p(),a="",c=null,S());return}if(x==="CTRL_W"){let j=a.replace(/[/\s]+$/,""),K=Math.max(j.lastIndexOf("/"),j.lastIndexOf(" ")),H=K>=0?j.slice(0,K+1):"";H!==a&&(p(),a=H,c=null,S());return}if(x===""){h(),c=null,S();return}if(x==="\x1B_"||x==="\x1B"){m(),c=null,S();return}if($?.isCharacter){p(),a+=x,c=null,S();return}}}})}function E0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Lf=J(()=>{"use strict";he();Hn();uf();Pc();Dr()});function Nf(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Df(t,e){let n=()=>{process.stdout.write(Lr),process.stdout.write(ps),process.stdout.write(Br),process.stdout.write(Nr),process.stdout.write(Zi),process.stdout.write(eo),process.stdout.write(to),process.stdout.write(Or),process.stdout.write("\x1B>")};n();let s=e.prefs??Nf();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=_c(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(N=>N.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(N=>N.interactive===!0)),P=F0(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??Wi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Ki(R,Date.now())),l=Ji(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,v=!1,b=0,S="normal",x=null,T=!1,$="input",F=new ms({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,D=null,Z=!1,G="",be=[],X=[],de=()=>{be.push(G),be.length>500&&be.shift(),X=[]},Ke=()=>{let R=be.pop();R!==void 0&&(X.push(G),G=R)},Xs=()=>{let R=X.pop();R!==void 0&&(be.push(G),G=R)},ws=()=>{be=[],X=[]},Le=null,Y=!1,Se=new ms({history:[]});e.initialPrompt&&Se.setBuffer(e.initialPrompt);let Qn=e.config.tui.promptHistoryMaxEntries;Do(_.globalTuiHistoryFile()).then(R=>{let P=R.length>Qn?R.slice(R.length-Qn):R;Se.setHistory(P)}).catch(()=>{});let ye=new oo(t),bs=hs(t),it=sn(t),Be=0,lo="",vs=0,Et=[],rn=1,Ss=0,Zs=0,uo=0,Kr="",Te=[],_n=1,va=0,er=[],vt=1,$n=0,fo=0,Jr=0,po=()=>{bs=hs(t),it=sn(t);let R=Math.max(10,it-Bf-1);vs=Math.max(10,it-pb);let P=Math.max(10,it-8);lo=$0(r,P);let N=Se.state();Et=ys(N.buffer,vs);let V=Qs(Et,N,Mc);rn=V.rendered,Ss=V.windowStart,Zs=V.cursorVisualRow,uo=V.cursorVisualCol;let oe=6+rn,fe=Math.max(3,bs-oe);Be=Math.min(a.length,fe),Kr=Ws(zi,l,R,c).padEnd(R),Te=d.map(Fe=>Ws(Fe,l,R,c).padEnd(R))},ke=()=>{d=a.map(R=>Ki(R,Date.now())),l=Ji(d,c),u=1+a.length,po()},nt=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>O0(P,m)):a=R,ke(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+Be>a.length&&(p=Math.max(0,a.length-Be)),on()},lt=R=>{if(R!==void 0){let P=a.findIndex(N=>N.sessionId===R);if(P>=0){f=P+1,on();return}}f=a.length>0?1:0,p=0,on()},on=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+Be?p=R-Be+1:p+Be>a.length&&(p=Math.max(0,a.length-Be))},an=()=>Math.max(2,it-3),gt=!1,yt=!0,ut=!1,Yr=[],Vr=()=>{let R=an(),P=`\u2500 ${lo} `,N=Math.max(1,R-P.length),V="\u2500".repeat(N);(f===0||gt)&&yt?t.brightBlue.noFormat(`\u256D${P}${V}\u256E`):t.dim.noFormat(`\u256D${P}${V}\u256E`)},ks=()=>{let R=an(),P="\u2500".repeat(R);(f===0||gt)&&yt?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},Qr=R=>{let P=Et[R];return P?(Se.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},vn=R=>{let P=an(),N=Qr(R),V=Math.max(0,P-1-N.length),oe=" ".repeat(V);(f===0||gt)&&yt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${N}${oe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${N}${oe}`),t.dim.noFormat("\u2502"))},tr=R=>{let P=Te[R]??"",N=a[R],V=N&&N.priority&&N.priority>0?"* ":" ";f===R+1&&!gt&&yt?t.brightWhite.bgBlue.noFormat(`${V}${P}`):t.noFormat(`${V}${P}`)},Is=()=>{let R=p,P=Math.max(0,a.length-p-Be),N=[];if(s.filters.cwdOnly&&N.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let V=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;N.push({kind:"host",text:V})}return s.filters.includeNonInteractive&&N.push({kind:"plain",text:"+non-interactive"}),R>0&&N.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&N.push({kind:"plain",text:`\u2193 ${P} below`}),N},ho=()=>{let R=Is();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},St=R=>rt(R),dn=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,G,Le??"",h?`1|${m}|${a.length}`:"0",ho(),Rs?"h1":"h0",cr?"ho1":"ho0"].join("")},me=()=>{Oe(()=>{ye.paintRow(cn(),dn(),()=>{let R=()=>{Yt=null,Sn=null};if(S==="confirm-kill"&&x)R(),t.brightYellow.noFormat(` kill ${St(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="warm"?t.brightRed.noFormat(` kill + delete ${St(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${St(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),t.dim.noFormat(` working on ${St(x.sessionId)}\u2026`);else if(S==="rename"&&x)R(),t.brightYellow.noFormat(` title: ${G}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(Le!==null)R(),t.dim.noFormat(` ${Le}`);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=Is(),N=ho(),V="Esc \xB7 Go Back",oe=V.length,fe=5,Fe=N.length,Dt=Math.max(1,it-Fe-oe-fe);if(Sn=null,P.length>0){t.dim.noFormat(" ");let Mt=3;for(let Je=0;Je<P.length;Je++){let ft=P[Je];Je>0&&(t.dim.noFormat(" \xB7 "),Mt+=3),ft.kind==="host"?(Sn={start:Mt,end:Mt+ft.text.length-1},cr?t.noFormat(ft.text):t.dim.noFormat(ft.text)):t.dim.noFormat(ft.text),Mt+=ft.text.length}}t.dim(" ".repeat(Dt)),Rs?t.noFormat(V):t.dim.noFormat(V),Yt={start:it-fe-oe+1,end:it-fe}}})})},Ie=R=>_n+1+R,nr=()=>_n+rn+1,Ft=()=>_n+rn+3,zt=R=>Ft()+1+(R-p),cn=()=>Ft()+1+Be,Ot=()=>{let R=Zs-Ss;if(R<0||R>=rn)return;let P=3+uo;t.moveTo(P,Ie(R))},k=()=>yt?f===0?"f":gt?"h":"u":"x",mo=()=>`ct|${k()}|${an()}|${lo}`,Sa=()=>`cb|${k()}|${an()}`,xs=R=>`cbb|${k()}|${an()}|${Qr(R)}`,Gr=()=>`h|${Kr}`,sr=R=>{let P=a[R],N=P&&P.priority&&P.priority>0?"* ":" ",V=Te[R]??"";return`sr|${f===R+1&&!gt&&yt?"1":"0"}|${N}${V}`},Ue=()=>{Oe(()=>{t.hideCursor(),po(),on(),_n=1,ye.ensureSize(it,bs),ye.paintRow(_n,mo(),()=>{Vr()});for(let R=0;R<rn;R++){let P=Ss+R;ye.paintRow(Ie(R),xs(P),()=>{vn(P)})}ye.paintRow(nr(),Sa(),()=>{ks()}),ye.paintRow(nr()+1,"blank",()=>{}),ye.paintRow(Ft(),Gr(),()=>{t.dim.noFormat(` ${Kr}`)});for(let R=0;R<Be;R++){let P=p+R,N=Ft()+1+R;P<a.length?ye.paintRow(N,sr(P),()=>{tr(P)}):ye.paintRow(N,"blank",()=>{})}me();for(let R=cn()+1;R<=bs;R++)ye.paintRow(R,"blank",()=>{});f===0&&(Ot(),t.hideCursor(!1))})},Gn=()=>{ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ue()},go=()=>{Oe(()=>{t.hideCursor(),ye.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=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")(`
209
211
 
210
- `);for(let R of _0){if(R===null){t(`
211
- `);continue}let[P,N]=R;t.brightCyan.noFormat(` ${P.padEnd(M0)}`),t.noFormat(N)(`
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
214
  `)}t(`
213
215
  `),t.dim.noFormat(" press any key to dismiss")(`
214
- `)})},Kt=()=>vt+4,Oc=2,ot=0,Lt=()=>{bs=hs(t);let R=Math.max(2,bs-(vt+3)-Oc);return Math.max(1,Math.floor(R/2))},yo=()=>{let R=Lt();H<ot?ot=H:H>=ot+R&&(ot=H-R+1),ot+R>j.length&&(ot=Math.max(0,j.length-R)),ot<0&&(ot=0)},ka=R=>{it=sn(t);let P=Math.max(2,it-3),N="\u2500 Find sessions ",V="\u2500".repeat(Math.max(1,P-N.length));R?t.brightBlue.noFormat(`\u256D${N}${V}\u256E`):t.dim.noFormat(`\u256D${N}${V}\u256E`),t.styleReset()},rr=()=>{it=sn(t),va=Math.max(10,it-pb);let R=F.state();er=ys(R.buffer,va);let P=Qs(er,R,P0);vt=P.rendered,$n=P.windowStart,fo=P.cursorVisualRow,Jr=P.cursorVisualCol},wo=(R,P)=>{it=sn(t);let N=Math.max(2,it-3),V=er[R],oe="";V&&(oe=(F.state().buffer[V.bufferIdx]??"").slice(V.startCol,V.endCol));let fe=Math.max(0,N-1-oe.length),Fe=" ".repeat(fe);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${oe}${Fe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${oe}${Fe}`),t.dim.noFormat("\u2502")),t.styleReset()},Ia=R=>{it=sn(t);let P=Math.max(2,it-3),N="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${N}\u256F`):t.dim.noFormat(`\u2570${N}\u256F`),t.styleReset()},ir=()=>3+Jr,or=()=>2+(fo-$n),Bt=()=>{let R=$==="input";Oe(()=>{R&&t.hideCursor(),t.moveTo(1,1),ka(R);for(let P=0;P<vt;P++)t.moveTo(1,2+P),wo($n+P,R);t.moveTo(1,2+vt),Ia(R),R&&(t.moveTo(ir(),or()),t.hideCursor(!1))})},kt=()=>{Oe(()=>{t.hideCursor();for(let R=0;R<vt;R++)t.moveTo(1,2+R),wo($n+R,!0);t.moveTo(ir(),or()),t.hideCursor(!1)})},Lc={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},bo=(R,P)=>{let N=j[R];if(!N)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let V=sn(t),oe=Math.max(20,V-Bf),fe=rt(N.sessionId),Fe=N.title??Xe(N.cwd),Dt=P&&N.snippets.length>1?` [${L+1}/${N.snippets.length}]`:P&&N.totalMatches>N.snippets.length?` [${N.snippets.length} of ${N.totalMatches}]`:"",Mt=`${fe} ${N.status==="warm"?"warm":"cold"}`,Je=Math.max(5,oe-Mt.length-Dt.length-2),ft=na(Fe,Je),un=`${Mt} ${ft}${Dt}`.padEnd(oe),wt=N.snippets[P?L:0],je=wt?Lc[wt.kind]??wt.kind:"",kn=wt?.toolName?`${je} \xB7 ${wt.toolName}`:je,si=Math.max(10,oe-kn.length-6),In=wt?na(wt.text,si):"",lr=wt?` ${kn} ${In}`:" (no snippet)";return{rowBudget:oe,line1:un,line2:lr.padEnd(oe+Bf),focusedRow:P}},ar=(R,P)=>{let{line1:N,focusedRow:V}=bo(R,P);V?t.brightWhite.bgBlue.noFormat(`\u276F ${N}`):t.noFormat(` ${N}`),t.styleReset()},Xn=(R,P)=>{let{line2:N}=bo(R,P);t.dim.noFormat(N),t.styleReset()},Cs=()=>{if(Z)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(D!==null)t.brightRed.noFormat(` ${D}`),t.styleReset(),t.eraseLineAfter();else if($==="input")j.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=j.length,P=K?" \xB7 truncated":"",N=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${N}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},Zn=()=>{rr();let R=$==="input",P=F.state().buffer.join(`
215
- `);Oe(()=>{t.hideCursor(),ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),ka(R);for(let V=0;V<vt;V++)t.moveTo(1,2+V),wo($n+V,R);t.moveTo(1,2+vt),Ia(R);let N=j.length;if(N===0)t.moveTo(1,Kt()),Z||(D===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):D===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,Kt()+1),Cs();else{yo();let V=Lt(),oe=$!=="input";for(let fe=0;fe<V;fe++){let Fe=ot+fe;t.moveTo(1,Kt()+fe*2),Fe<N?ar(Fe,oe&&Fe===H):t.eraseLineAfter(),t.moveTo(1,Kt()+fe*2+1),Fe<N?Xn(Fe,oe&&Fe===H):t.eraseLineAfter()}t.moveTo(1,Kt()+V*2),Cs()}R&&(t.moveTo(ir(),or()),t.hideCursor(!1))})},As=(R,P)=>{let N=R-ot;N<0||N>=Lt()||Oe(()=>{t.moveTo(1,Kt()+N*2),ar(R,P),t.moveTo(1,Kt()+N*2+1),Xn(R,P)})},dr=()=>{Oe(()=>{t.moveTo(1,Kt()+Lt()*2),Cs()})},Xr=()=>{Oe(()=>{let R=Lt(),P=j.length,N=$!=="input";for(let V=0;V<R;V++){let oe=ot+V;t.moveTo(1,Kt()+V*2),oe<P?ar(oe,N&&oe===H):t.eraseLineAfter(),t.moveTo(1,Kt()+V*2+1),oe<P?Xn(oe,N&&oe===H):t.eraseLineAfter()}t.moveTo(1,Kt()+R*2),Cs()})},vo=()=>F.state().buffer.join(`
216
- `),Bc=R=>{let P=vt;F.feed({type:"paste",text:R}),rr(),vt!==P?Zn():kt()},Nc=async()=>{let R=vo().trim();if(R.length!==0){if(a.length===0){D="no sessions in view to search",Zn();return}Z=!0,D=null,Zn();try{let P=await Bg(e.target,R,{sessionIds:a.map(N=>N.sessionId)});j=P.results,K=P.truncated,H=0,L=0,ot=0,$=P.results.length>0?"results":"input",rr()}catch(P){D=`search failed: ${P.message}`}finally{Z=!1,Zn()}}},es=()=>{},Nt=()=>{Oe(()=>{let R=f===0;R&&t.hideCursor(),ye.paintRow(_n,mo(),()=>{Vr()}),ye.paintRow(nr(),Sa(),()=>{ks()});for(let P=0;P<rn;P++){let N=Ss+P;ye.paintRow(Ie(P),xs(N),()=>{vn(N)})}R&&(Ot(),t.hideCursor(!1))})},ln=()=>{Oe(()=>{let R=Se.state();Et=ys(R.buffer,vs);let P=Qs(Et,R,Mc);Ss=P.windowStart,Zs=P.cursorVisualRow,uo=P.cursorVisualCol;let N=f===0;N&&t.hideCursor();for(let V=0;V<rn;V++){let oe=Ss+V;ye.paintRow(Ie(V),xs(oe),()=>{vn(oe)})}N&&(Ot(),t.hideCursor(!1))})},Zr=R=>{R<p||R>=p+Be||Oe(()=>{ye.paintRow(zt(R),sr(R),()=>{tr(R)})})},Pt=()=>{Oe(()=>{for(let R=0;R<Be;R++){let P=Ft()+1+R,N=p+R;N<a.length?ye.paintRow(P,sr(N),()=>{tr(N)}):ye.paintRow(P,"blank",()=>{})}me()})},Fn=()=>{Oe(()=>{ye.paintRow(Ft(),Gr(),()=>{t.dim.noFormat(` ${Kr}`)});for(let R=0;R<Be;R++){let P=Ft()+1+R,N=p+R;N<a.length?ye.paintRow(P,sr(N),()=>{tr(N)}):ye.paintRow(P,"blank",()=>{})}me(),f===0&&(Ot(),t.hideCursor(!1))})},Jt=!1,ts="",ei=0,xa=200,ns=null,ti=!1,Yt=null,Rs=!1,Sn=null,cr=!1,Vt=null,So=null,Ca=null,ni=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let V=P.indexOf("\x1B[I"),oe=P.indexOf("\x1B[O"),fe=V===-1?oe:oe===-1?V:Math.min(V,oe);if(fe===-1)break;let Fe=yt;yt=fe===V,yt&&(ei=Date.now()),Fe!==yt&&!ut&&Yr.length<=1&&Oe(()=>{Nt(),Pt()}),P=P.slice(0,fe)+P.slice(fe+"\x1B[I".length)}if(P.length===0)return}if(!Jt&&P===""&&So){So();return}if(!Jt&&(P===""||P==="\x1B_"||P==="\x1B")){Ca?.(P);return}if(Jt){let V=P.indexOf(ia);if(V===-1){ts+=P;return}ts+=P.slice(0,V),Jt=!1;let oe=Buffer.from(ts,"binary").toString("utf-8").replace(/\r\n?/g,`
217
- `);ts="";let fe=P.slice(V+ia.length);if(T)$==="input"&&!Z&&Bc(oe);else if(f===0&&!h){Se.feed({type:"paste",text:oe});let Fe=Se.state(),Dt=ys(Fe.buffer,vs);Qs(Dt,Fe,Mc).rendered!==rn?Ue():ln()}fe.length>0&&Vt&&Vt(Buffer.from(fe,"binary"));return}let N=P.indexOf(Xi);if(N===-1){Vt?.(R);return}N>0&&Vt?.(Buffer.from(P.slice(0,N),"binary")),P=P.slice(N+Xi.length),Jt=!0,P.length>0&&ni(Buffer.from(P,"binary"))};return Ue(),await new Promise(R=>{let P=null,N=!1,V=null,oe=!1,fe=Yr,Fe=E=>{fe.push(E)},Dt=()=>{fe.pop(),ut||fe[fe.length-1]?.onResize()},Mt={push:Fe,pop:Dt},Je=()=>({kind:"new",cwd:r}),ft=async()=>{Es(),ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Fe({onKey:()=>{},onResize:()=>{}});let U;try{U=await Wr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Dt(),On()}U.kind==="ok"&&U.path!==r&&(r=U.path,i=_c(i,r),nt()),ut||Ue()};es=()=>{F=new ms({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,ot=0,D=null,Z=!1,$="input",T=!1,Dt()};let un=(E,U,re)=>{si(),fe[fe.length-1]?.onKey(E,U,re)},wt=()=>{ut||fe[fe.length-1]?.onResize()};Ca=E=>{ut||fe[fe.length-1]?.onKey(E,null,{})};let je=()=>{if(ut)return;ut=!0,fe.length=0,P&&(clearInterval(P),P=null),V&&(V.abort(),V=null,N=!1),t.off("key",un),t.off("mouse",os),t.off("resize",wt),process.stdout.write(ps),process.stdout.write(aa);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",ni),E.stdin.on("data",Vt),Vt=null),Jt=!1,ts="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,cn()+1),t(`
218
- `)},kn=()=>{if(ut||fe.length>1||S!=="normal"||h||oe)return;N&&V&&(V.abort(),V=null,N=!1);let E=f>0?a[f-1]?.sessionId:void 0;N=!0;let U=new AbortController;V=U,Ts(E,{silent:!0,signal:U.signal}).finally(()=>{V===U&&(V=null),N=!1})},si=()=>{ut||(P&&clearInterval(P),P=setInterval(kn,3e3))},In=()=>(je(),R({kind:Y?"exit":"abort"}),!0),lr=()=>{let E=d.map(U=>`${U.session}|${U.upstream}|${U.host}|${U.state}|${U.agent}|${U.model}|${U.age}|${U.title}|${U.cwd}|${U.cost}`).join(`
219
- `);return`${f}:${p}:${Le??""}
220
- ${E}`},Ts=async(E,U={})=>{try{let re=U.silent?lr():"",W=u,te=await zn(e.target,{includeNonInteractive:!0,signal:U.signal}),se=E??(f>0?a[f-1]?.sessionId:void 0);if(i=_c(te,r),nt(),se!==void 0){let ve=a.findIndex(qe=>qe.sessionId===se);ve>=0?f=ve+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+Be>a.length&&(p=Math.max(0,a.length-Be)),on(),U.silent&&lr()===re)return;u===W?Fn():Ue()}catch(re){if(U.silent)return;Le=`refresh failed: ${re.message}`,Ue()}},Aa=async E=>{if(!x)return;let U=x;S="busy",me();try{await Fg(e.target,U.sessionId,E),S="normal",x=null,G="",await Ts(U.sessionId)}catch(re){S="normal",x=null,G="",Le=`rename failed: ${re.message}`,me()}},ko=async E=>{try{await Lg(e.target,E.sessionId),Le="title regen queued (press r to refresh)",me()}catch(U){Le=`regen failed: ${U.message}`,me()}},pt=async E=>{let re=(E.priority&&E.priority>0?E.priority:0)>0?null:1,W=re??0;for(let se of i)se.sessionId===E.sessionId&&(se.priority=W>0?W:void 0);let te=E.sessionId;i=_c(i,r),nt(),lt(te),Ue(),Le=W>0?"priority: high":"priority: normal",me();try{await Og(e.target,E.sessionId,re)}catch(se){Le=`priority failed: ${se.message}`,me()}},ss=async()=>{if(oe)return;oe=!0;let E=f>0?a[f-1]?.sessionId:void 0;Le="syncing agents\u2026",me();try{let{synced:U,skipped:re,agents:W}=await $g(e.target);await Ts(E),Le=`synced ${U} new (${re} known) from ${W} agent${W===1?"":"s"}`,me()}catch(U){Le=`sync failed: ${U.message}`,me()}finally{oe=!1}},rs=async E=>{if(!x)return;let U=x;S="busy",me();try{E==="kill"?await Kn(e.target,U.sessionId):await Ng(e.target,U.sessionId),S="normal",x=null,U.sessionId===e.currentSessionId&&(Y=!0);let re;if(E==="kill")re=U.sessionId;else{let W=a.findIndex(te=>te.sessionId===U.sessionId);W>=0&&(re=a[W+1]?.sessionId??a[W-1]?.sessionId)}await Ts(re)}catch(re){S="normal",x=null,Le=`${E} failed: ${re.message}`,me()}},xn=(E,U)=>{E===0!=(U===0)&&(Nt(),U===0?(t.hideCursor(!1),Ot()):t.hideCursor())},at=E=>{let U=Math.min(u-1,Math.max(0,f+E));if(U===f)return;let re=f;f=U,on(),Oe(()=>{Pt(),xn(re,f)})},ur=()=>Le===null?!1:(Le=null,me(),!0),Cn=()=>{go(),Fe({onKey:E=>{if(E==="CTRL_C"){je(),R({kind:"abort"});return}Dt()},onResize:()=>go()})},is=E=>{let U=null,re=null,W=!0,te=()=>{Oe(()=>{if(t.hideCursor(),ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${rt(E.sessionId)}`)(`
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(`
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)}`)(`
221
223
 
222
224
  `),W)t.dim.noFormat(" loading\u2026")(`
223
- `);else if(re!==null)t.brightRed.noFormat(` ${re}`)(`
224
- `);else if(U!==null)for(let qe of U)t.noFormat(` ${qe}`)(`
225
+ `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
226
+ `);else if(j!==null)for(let We of j)t.noFormat(` ${We}`)(`
225
227
  `);t(`
226
228
  `),t.dim.noFormat(" Esc / ^C to return")(`
227
- `)})};te();let se=new AbortController,ve={onKey:qe=>{if(qe==="ESCAPE"||qe==="CTRL_C"){se.abort(),Dt();return}},onResize:()=>te()};Fe(ve),(async()=>{try{let qe=await nn(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(E.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:se.signal});if(!qe.ok)throw new Error(`daemon returned HTTP ${qe.status}`);let Ge=await qe.json(),dt=En(Ge),xe=ju(dt,E.status);U=tc(xe,!1).replace(/\n$/,"").split(`
228
- `)}catch(qe){if(se.signal.aborted)return;re=`failed to load info: ${qe.message}`}finally{W=!1,!ut&&fe[fe.length-1]===ve&&te()}})()},fr=()=>{if(a.length===0){Le="no sessions to search",me();return}F=new ms({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,ot=0,D=null,Z=!1,$="input",T=!0,rr(),Zn(),Fe({onKey:(U,re,W)=>{if($==="input"){if(Z)return;if(U==="ESCAPE"||U==="CTRL_C"){es();return}if(U==="ENTER"||U==="KP_ENTER"){if(vo().trim().length===0)return;Nc();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&j.length>0){$="results",H=0,L=0,Oe(()=>{Bt(),As(0,!0),dr(),t.hideCursor()});return}let te=F.state(),se=null;if(U==="")se={type:"key",name:"ctrl-underscore"};else if(U==="\x1B_"||U==="\x1B")se={type:"key",name:"alt-underscore"};else if(W?.isCharacter)se={type:"char",ch:U};else{let dt=Tc(U);dt!==null&&(se={type:"key",name:dt})}if(se===null){t.moveTo(ir(),or());return}F.feed(se);let ve=F.state();if(te.buffer.length===ve.buffer.length&&te.buffer.every((dt,xe)=>dt===ve.buffer[xe])&&te.row===ve.row&&te.col===ve.col){t.moveTo(ir(),or());return}let Ge=vt;rr(),vt!==Ge?Zn():kt();return}if($==="results"){if(U==="ESCAPE"||U==="CTRL_C"){es();return}if(U==="CTRL_F"){$="input",Xr(),dr(),Bt();return}if(U==="ENTER"||U==="KP_ENTER"){let se=j[H];if(!se)return;let ve=a.find(Ge=>Ge.sessionId===se.sessionId);if(!!ve?.importedFromMachine&&!ve.upstreamSessionId){je();let Ge={kind:"attach",sessionId:se.sessionId};ve.agentId!==void 0&&(Ge.agentId=ve.agentId),R(Ge);return}(async()=>{let Ge=await lb(t,{sessionId:se.sessionId,title:se.title,cwd:se.cwd},Mt);if(Ge==="cancel"){je(),R({kind:"abort"});return}if(Ge==="back")return;je();let dt={kind:"attach",sessionId:se.sessionId,readonly:Ge==="view"};ve?.agentId!==void 0&&(dt.agentId=ve.agentId),R(dt)})();return}if(W?.isCharacter&&(U==="n"||U==="N")){let se=j[H];if(!se||se.snippets.length<=1)return;L=(L+1)%se.snippets.length,As(H,!0);return}if(W?.isCharacter&&(U==="p"||U==="P")){let se=j[H];if(!se||se.snippets.length<=1)return;L=(L-1+se.snippets.length)%se.snippets.length,As(H,!0);return}let te=se=>{if(se<0&&H===0){$="input",Oe(()=>{As(0,!1),dr(),Bt()});return}let ve=Math.min(j.length-1,Math.max(0,H+se));if(ve===H)return;let qe=H,Ge=ot;H=ve,L=0,yo(),ot!==Ge?Xr():(Oe(()=>{As(qe,!1),As(H,!0)}),dr())};switch(U){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(-Lt());return;case"PAGE_DOWN":te(Lt());return;case"HOME":te(-H);return;case"END":te(j.length);return}return}},onResize:()=>Zn()})},ri=(E,U,re)=>{if(S!=="busy"){if(E==="CTRL_O"){ft();return}if(E==="CTRL_L"){Gn();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let W=G.trim();if(W.length===0){S="normal",x=null,G="",me();return}Aa(W);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",x=null,G="",ws(),me();return}if(E==="BACKSPACE"){G.length>0&&(de(),G=G.slice(0,-1),me());return}if(E==="CTRL_U"){G.length>0&&(de(),G="",me());return}if(E==="CTRL_W"){let W=G.replace(/\s+$/,""),te=W.lastIndexOf(" "),se=te>=0?W.slice(0,te):"";se!==G&&(de(),G=se,me());return}if(E===""){Ke(),me();return}if(E==="\x1B_"||E==="\x1B"){Xs(),me();return}if(re?.isCharacter){de(),G+=E,me();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(re?.isCharacter&&(E==="y"||E==="Y")){rs(S==="confirm-kill"?"kill":"delete");return}if(E==="ESCAPE"||E==="CTRL_C"||E==="ENTER"||E==="KP_ENTER"||re?.isCharacter&&(E==="n"||E==="N")){S="normal",x=null,me();return}return}if(ur(),E==="CTRL_F"&&f!==0){fr();return}if(f===0&&!h){if(E==="ESCAPE"){In();return}if(E==="ENTER"||E==="KP_ENTER"){je();let xe=Se.expandedText(),It=Je();xe.trim().length>0&&(It.prompt=xe),R(It);return}if(E==="UP"&&v){let xe=Date.now(),It=xe-b;if(b=xe,It<y){Ot();return}v=!1}if(E==="DOWN"){let xe=Se.state(),It=xe.historyIndex!==-1||xe.queueIndex!==-1,Ht=Et.length===0||Zs===Et.length-1;if(!It&&Ht&&a.length>0){at(1);return}}if(E==="PAGE_DOWN"&&(Et.length===0||Zs===Et.length-1)&&a.length>0){at(1);return}if(E==="CTRL_P"){a.length>0&&at(1);return}v=!1;let W=Se.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(re?.isCharacter)te={type:"char",ch:E};else{let xe=Tc(E);xe!==null&&(te={type:"key",name:xe})}if(te===null){Ot();return}let se=Se.feed(te),ve=Se.state(),qe=W.buffer.length===ve.buffer.length&&W.buffer.every((xe,It)=>xe===ve.buffer[It])&&W.row===ve.row&&W.col===ve.col;if(se.some(xe=>xe.type==="exit")){In();return}if(qe){Ot();return}let Ge=ys(ve.buffer,vs);if(Qs(Ge,ve,Mc).rendered!==rn){Ue();return}ln();return}if(!h&&re?.isCharacter&&E==="?"){Cn();return}if(h){if(re?.isCharacter){m+=E,nt(),Ue();return}if(E==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),nt(),Ue()):(h=!1,nt(),Ue());return}if(E==="ESCAPE"||E==="CTRL_C"){h=!1,m="",nt(),Ue();return}}if(re?.isCharacter){if(E==="/"){h=!0,m="",nt(),Ue();return}if(E==="n"||E==="N"){at(1);return}if(E==="p"||E==="P"){at(-1);return}if(E==="c"||E==="C"){let W=f>0?a[f-1]:void 0,te=Je();W?.cwd&&(te.cwd=W.cwd),je(),R(te);return}if(E==="q"||E==="Q"){In();return}if(E==="o"||E==="O"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,nt(),lt(W),Ue();return}if(E==="h"||E==="H"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=hb(s.filters.hostFilter,i),nt(),lt(W),Ue();return}if(E==="i"&&f>0){let W=a[f-1];if(!W)return;is(W);return}if(E==="I"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,nt(),lt(W),Ue();return}if(E==="r"||E==="R"){let W=f>0?a[f-1]?.sessionId:void 0;Ts(W);return}if(E==="s"||E==="S"){ss();return}if((E==="v"||E==="V")&&f>0){let W=a[f-1];if(!W)return;je();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;je();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;x={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;x={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;ko({sessionId:W.sessionId});return}if(E==="*"&&f>0){let W=a[f-1];if(!W)return;pt(W);return}if((E==="d"||E==="D")&&f>0){let W=a[f-1];if(!W)return;x={sessionId:W.sessionId,cwd:W.cwd,status:W.status},S="confirm-delete",me();return}gt=!1,f=0,Se.feed({type:"char",ch:E}),Ue();return}switch(E){case"UP":case"SHIFT_TAB":case"CTRL_P":E==="UP"&&(f===1&&(v=!0),b=Date.now()),at(-1);return;case"DOWN":case"TAB":case"CTRL_N":at(1);return;case"PAGE_UP":at(-Be);return;case"PAGE_DOWN":at(Be);return;case"HOME":at(1-f);return;case"END":at(u);return;case"ENTER":case"KP_ENTER":{if(gt){je();let se=Se.expandedText(),ve=Je();se.trim().length>0&&(ve.prompt=se),R(ve);return}if(je(),f===0){R(Je());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":In();return}}};Fe({onKey:(E,U,re)=>ri(E,U,re),onResize:()=>{ut||Ue()}});let os=(E,U)=>{if(ut||fe.length!==1||S!=="normal")return;let re=E==="MOUSE_MOTION",W=E==="MOUSE_LEFT_BUTTON_PRESSED",te=E==="MOUSE_LEFT_BUTTON_RELEASED",se=E==="MOUSE_WHEEL_UP",ve=E==="MOUSE_WHEEL_DOWN",qe=yt&&Date.now()-ei<xa,Ge=!yt||qe;if(W){ns={x:U?.x??-1,y:U?.y??-1},ti=Ge;return}if(re&&Ge)return;let dt=te&&ns!==null&&U?.x===ns.x&&U?.y===ns.y,xe=dt&&!ti,It=dt&&ti;if(te&&(ns=null,ti=!1,!dt))return;if(se||ve){if(a.length===0)return;let Ee=se?-3:3,as=Math.max(0,a.length-Be),Ms=Math.min(as,Math.max(0,p+Ee));if(Ms===p)return;if(p=Ms,f>0){let Ut=f-1;Ut<p?f=p+1:Ut>=p+Be&&(f=p+Be)}Pt();return}if(!re&&!xe)return;let Ht=U?.y;if(typeof Ht!="number")return;{let Ee=U?.x,as=Yt!==null&&Ht===cn()&&typeof Ee=="number"&&Ee>=Yt.start&&Ee<=Yt.end,Ms=Sn!==null&&Ht===cn()&&typeof Ee=="number"&&Ee>=Sn.start&&Ee<=Sn.end;(as!==Rs||Ms!==cr)&&(Rs=as,cr=Ms,me(),f===0?(Ot(),t.hideCursor(!1)):t.hideCursor(!0))}if(xe&&Yt!==null&&Ht===cn()){let Ee=U?.x;if(typeof Ee=="number"&&Ee>=Yt.start&&Ee<=Yt.end){In();return}}if(xe&&Sn!==null&&Ht===cn()){let Ee=U?.x;if(typeof Ee=="number"&&Ee>=Sn.start&&Ee<=Sn.end){let as=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=hb(s.filters.hostFilter,i),nt(),lt(as),Ue();return}}if(Ht>=_n&&Ht<=nr()){if((xe||It)&&f!==0){gt=!1;let Ee=f;f=0,Oe(()=>{Pt(),xn(Ee,f)});return}re&&!gt&&f!==0&&(gt=!0,Oe(()=>{Nt(),Pt()}));return}gt&&(gt=!1,Oe(()=>{Nt(),Pt()}));let fn=Ft()+1,Ps=fn+Be-1;if(Ht<fn||Ht>Ps)return;let pn=p+(Ht-fn);if(pn<0||pn>=a.length)return;let pr=a[pn];if(!pr)return;let hr=pn+1;if(re&&f===0)return;let Dc=f===0,Hc=f===hr;if(It&&f!==hr){let Ee=f;f=hr,on(),Oe(()=>{Pt(),xn(Ee,f)});return}if(It)return;if(f!==hr){let Ee=f;f=hr,on(),Oe(()=>{Pt(),xn(Ee,f)})}if(!xe||Dc||!Hc)return;je();let Ra={kind:"attach",sessionId:pr.sessionId};pr.agentId!==void 0&&(Ra.agentId=pr.agentId),R(Ra)},On=()=>{t.grabInput({mouse:"motion"});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Vt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",ni),process.stdout.write(ac),process.stdout.write(lc)),t.on("key",un),t.on("mouse",os),t.on("resize",wt)},Es=()=>{process.stdout.write(ps),process.stdout.write(aa);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",ni),E.stdin.on("data",Vt),Vt=null),Jt=!1,ts="",t.off("key",un),t.off("mouse",os),t.off("resize",wt),t.grabInput(!1),t.hideCursor(!1)};if(On(),process.platform!=="win32"){let E=!1,U=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),On(),ut||Gn())};So=()=>{E||ut||(E=!0,Es(),t.fullscreen(!1),process.stdout.write(`${oa}${dc}
229
- `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(kn,3e3)})}function $0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+na(Xe(t),s)}function _c(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 F0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function hb(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 O0(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[rt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Xe(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Bf,Mc,P0,pb,M0,_0,mb=J(()=>{"use strict";Qd();he();Hn();ta();ld();mf();Ff();Of();Lf();Dr();gf();kf();da();Rr();qu();Bf=2,Mc=4,P0=4,pb=4,M0=20,_0=[["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 D0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Hf(t,e,n,s){Pn();let r=D0(e,n??L0),i=0,o=()=>{let u=hs(t)-8;return Math.max(1,Math.min(B0,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(N0,Math.max(40,sn(t)-8)),h=Mn(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 v=Math.min(e.length,i+u);for(let S=i;S<v;S++){let x=e[S];if(!x)continue;let T=S===r?"\u276F":" ",$=x.description??x.name,F=` ${T} ${x.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let j=`${F} ${$}`;t.brightWhite.bgBlue.noFormat(uc(We(j,m),m))}else{t.noFormat(F);let j=m-F.length-2;j>1&&t.dim.noFormat(` ${We($,j)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let b=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${b}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return Yn({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 L0,B0,N0,gb=J(()=>{"use strict";Dr();L0="opencode",B0=20,N0=88});import H0 from"wrap-ansi";async function yb(t,e,n,s){Pn();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=n.split(`
230
- `).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=sn(t),l=hs(t),u=Math.min(U0,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>H0(T,f,{hard:!0,trim:!1}).split(`
231
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,v=y.length+(m?1:0)+4,b=Mn(t,{contentHeight:v,contentWidth:u,title:"Agent failed to start"}),S=b.contentW,x=0;t.moveTo(b.contentX,b.contentY+x),t.brightWhite.bold.noFormat(We(` ${i}`,S)),x+=2;for(let T of y)t.moveTo(b.contentX,b.contentY+x),t.brightRed.noFormat(We(` ${T}`,S)),x++;return m&&(t.moveTo(b.contentX,b.contentY+x),t.dim.noFormat(We(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),x++),x++,t.moveTo(b.contentX,b.contentY+x),t.dim.noFormat(We(` ${a}`,S)),b};return Yn({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 U0,wb=J(()=>{"use strict";Dr();U0=100});import*as vb from"fs";import*as Sb from"os";import*as $c from"path";function kb(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 j0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function q0(t){return t.replace(/\\ /g," ")}function bb(t){return t.replace(/ /g,"\\ ")}function W0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function z0(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Sb.homedir()+n.slice(1)),$c.isAbsolute(n)?n:$c.resolve(e,n)}function K0(t){let e;try{e=vb.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Ib(t,e,n=K0){if(!j0(t))return null;let s=q0(t),{dirPrefix:r,base:i}=W0(s),o=z0(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:bb(r+p),candidates:l}}let u=ba(d.map(f=>f.name));return{replacement:bb(r+u),candidates:l}}var xb=J(()=>{"use strict";Pc()});function Cb(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 Ab(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Rb(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 Tb=J(()=>{"use strict"});import{readFileSync as J0}from"fs";import{nanoid as Eb}from"nanoid";import Y0 from"terminal-kit";import Uf from"fs/promises";import zr from"path";function V0(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function Q0(t){let e=Fc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function G0(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 Fc(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 X0(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function Z0(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=Fc(o.representative),d=e[a]??0,l=n[a]?qf:c[d]??c[0]??"";return{label:X0(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 eT(t,e,n){return t===qf?{type:"dismiss",method:Ew,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Tw,params:{sessionId:n,questionId:e.id,answer:t}}}function tT(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]?qf:Fc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=eT(c,l,r);u!==null&&i.push(u)}}return i}function nT(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=Fc(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:tT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Pb(t){if(!Array.isArray(t))return;let e=qn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function jf(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 iT(t,e){e.has(t)?e.delete(t):e.add(t)}function oT(){if(Mb)return;Mb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{st({src:"uncaughtException",stack:t(e)}),jr(),process.stderr.write(`
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(`
232
234
  uncaught: ${t(e)}
233
- `),process.exit(1)}),process.on("unhandledRejection",e=>{st({src:"unhandledRejection",stack:t(e)}),jr(),process.stderr.write(`
235
+ `),process.exit(1)}),process.on("unhandledRejection",e=>{se({src:"unhandledRejection",stack:t(e)}),Kr(),process.stderr.write(`
234
236
  unhandled rejection: ${t(e)}
235
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&st({src:"process-exit",code:e})})}async function Fb(t){oT();let e=await we(),n=t.target??await jt(e);Pp(e.tui.logMaxBytes),n.isLocal&&!t.target&&await js(e);let s=Y0.terminal;ab(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:ip(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Nf(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
236
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await dT(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await la();if(f&&process.stderr.write(`\u2728 ${ua(f)}
237
- `),process.stdout.isTTY){let p=await Pr(e);if(p?.version!==void 0){let h=p.version!==pe,m=Ns(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let v=h?`daemon ${p.version} \u2260 cli ${pe}`:"config changed since daemon started",b=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(b(`! ${v} \u2014 run \`${Ln()} daemon restart\` to apply.`)+`
238
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=rt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Ln()} --session ${p}${h}
239
- `)}}function aT(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),H=e.slice(K),L=[];for(let D=0;D<K;D++){let Z=e[D];if(Z===void 0)continue;let G=n.get(Z);G&&!Bu(G.status)&&L.push(Z)}l=[...L,...H]}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",v=y?`amended \xB7 ${Jn(h)}`:`stopped (${m}) \xB7 ${Jn(h)}`,b;if(c===0)m!==null?b=v:b=f?`thinking \xB7 ${Jn(h)}`:`thought \xB7 ${Jn(h)}`;else{let K=c===1?"tool":"tools",H=m!==null?v:f?Jn(h):`took ${Jn(h)}`,L=[`${c} ${K}`,H];f&&d&&u>0&&L.push(`${u} hidden`),b=L.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",F=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?x:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?x:"dim"}],j=[null];for(let K of l){let H=n.get(K);if(H){let L=ra(H,p);for(let D of L)D.hoverSubKey=K;if(F.push(...L),j.push(...L.map(()=>K)),o?.has(K)){let D=iy(H);for(let Z of D)Z.hoverSubKey=K;F.push(...D),j.push(...D.map(()=>K))}}}return{lines:F,rowOwners:j}}async function dT(t,e,n,s,r,i,o){let a=await cT(t,e,n,s,o,i);if(!a)return t.grabInput(!1),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=uT(t,c);d.write(c);let l=n.isLocal?async()=>(await jt(await we())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new so({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>st({src:"resilient-ws",line:g})}),m=new qt(h);await h.start(),m.onNotification(Va,g=>{let w=fh.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],v=null,b=!1,S=!1,x=(g,w)=>{g&&(v?v(g,w):y.push({event:g,rawUpdate:w}))},T,$=g=>{g!==T&&(T=g,g!==void 0&&k.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},F=null,j=null,K=!1,H=0,L=0,D=!1,Z=!1,G,be=null,X=null,de=null,Ke=null,Xs=()=>setInterval(()=>{if(be===null||Y===null)return;let g=Ke===null?0:Date.now()-Ke;Y.setBanner({elapsedMs:Date.now()-be,stalled:g>=sT}),Ut()},1e3),ws=!1,Le=g=>{let w=L;L=Math.max(0,L+g);let I=typeof Y<"u"&&Y!==null;w===0&&L>0?(Z=!1,be=Date.now(),Ke=Date.now(),Se?.setTurnRunning(!0),I&&Y.setBanner({status:"busy",elapsedMs:0,stalled:!1}),X===null&&I&&(X=Xs())):w>0&&L===0?(Z=!1,be=null,Ke=null,Se?.setTurnRunning(!1),X!==null&&(clearInterval(X),X=null),I&&Y.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&Z&&(Z=!1,I&&Y.setBanner({status:"busy",stalled:!1}))},Y=null,Se=null,Qn,ye=null,bs=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"]),it=g=>{let{update:w}=g??{},I=qn(w,{cwd:lt});lT(w,I),Ke=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!bs.has(C)){let A=w??{};typeof A.messageId=="string"&&(Qn=A.messageId)}if(C==="prompt_received"?Le(1):I?.kind==="turn-complete"&&(Le(-1),K=!0),C==="permission_resolved"){Kr(w);return}if(C==="hydra_compaction"){Ss(w);return}if(C==="clarifier_question_asked"){let A=w,M=typeof A.question?.question=="string"?A.question.question:"",B=M.length>50?M.slice(0,49)+"\u2026":M;k.notify(B?`new question: ${B} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(x(I,w),va(w))};m.onNotification("session/update",g=>{if(!b){if(ye!==null){ye.push(g);return}it(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(b)return;L>0&&Le(-L),typeof Y<"u"&&Y!==null&&Y.setBanner({status:"cold",elapsedMs:void 0})});let Be=new Map,lo=200,vs=0,Et=!1,rn=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(b)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(()=>{b||(Be.delete(C),Je.set(C,Mt(C,A)),Y&&Se&&kn())},lo);Be.set(C,M)}else Je.set(w.messageId,Mt(w.messageId,w.prompt)),Y&&Se&&kn();if(an!==void 0&&w.originator?.clientId===an){let C=ft.shift();C&&(C.messageId=w.messageId,un.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(b)return;let w=g??{};if(typeof w.messageId!="string"||!Je.has(w.messageId))return;Je.set(w.messageId,Mt(w.messageId,w.prompt));let I=un.get(w.messageId);if(I){let C=Array.isArray(w.prompt)?w.prompt:[],A="",M=[];for(let B of C){if(!B||typeof B!="object")continue;let O=B;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)})}I.text=A,I.attachments=M}Y&&Se&&kn()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(b)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(G=w.messageId);let I=Be.get(w.messageId);I!==void 0&&(clearTimeout(I),Be.delete(w.messageId)),Je.delete(w.messageId)&&Y&&Se&&kn();let A=un.get(w.messageId);A&&(un.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),je=A))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(b)return;let w=g??{};if(!(typeof Y<"u"&&Y!==null))return;vs=Date.now(),Et=!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(b)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let I=w.cancelledMessageId;wt.add(I),je!==null&&je.messageId!==void 0&&je.messageId===I&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),je=null,wt.delete(I))});let Ss=g=>{let w=g??{},I=typeof w.phase=="string"?w.phase:void 0;if(I==="started")k.setCompactionIndicator("compacting...");else if(I==="iteration")k.setCompactionIndicator("compacting...");else if(I==="deferred")k.setCompactionIndicator("compaction queued (waiting for idle)");else if(I==="swapped")k.setCompactionIndicator(null),k.notify("compacted",2e3);else if(I==="rolled_back")k.setCompactionIndicator(null),k.notify("rolled back",2e3);else if(I==="failed"){k.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;k.notify(`compaction failed: ${A}`,5e3)}},Zs=()=>{de===null&&(de=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(ke)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(k.setSynthesisIndicator(null),k.notify("synthesis complete",2e3),de!==null&&(clearInterval(de),de=null)):w.forkSynthesisState==="failed"&&(k.setSynthesisIndicator("\u26A0 synthesis failed"),k.notify("synthesis failed \u2014 fork still usable via recall",8e3),de!==null&&(clearInterval(de),de=null))}catch{}},5e3))},uo=()=>{de!==null&&(clearInterval(de),de=null)},Kr=g=>{let w=g??{},I=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}),_n(I,C?{outcome:C}:void 0)},Te=null,_n=(g,w)=>{if(!Te||Te.toolCallId&&g&&Te.toolCallId!==g)return;let I=Te.resolve;Te=null,k.setPermissionPrompt(null),I(w??{outcome:{outcome:"cancelled"}})},va=g=>{if(!Te?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===Te.toolCallId&&(!w.status||w.status==="pending"||_n(w.toolCallId,void 0))},er=()=>{if(!Te){k.setPermissionPrompt(null);return}k.setPermissionPrompt({title:Te.title,detail:Te.detail,options:Te.options.map(g=>({label:g.name})),selectedIndex:Te.selectedIndex})},vt=g=>{if(!Te)return;let{options:w,resolve:I}=Te;if(Te=null,k.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};m.onRequest("session/request_permission",async g=>{if(b)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Hr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(Q=>({optionId:Q.optionId,name:Ae(Q.name??""),...Q.kind!==void 0?{kind:Q.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",M=Ae(A),B=Ae(rw(sw(g))),O=w.toolCall?.toolCallId;return C.length===0?(k.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${M} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Q=>{Te={title:M,detail:B,options:C,selectedIndex:0,resolve:Q,toolCallId:O},er()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let $n,fo,Jr=!0,po=!1;try{let g=await m.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}});fo=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(Jr=!1),po=Xt(g?._meta??void 0).prompt?.amending===!0}catch{}let ke=a.sessionId,nt=a.agentId,lt=a.cwd,on,an,gt,yt,ut,Yr,Vr,ks,Qr,vn,tr=!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:{[At]:g}}:{}},I;try{I=await Yy({request:()=>m.request("session/new",w),showBanner:(M,B,O)=>Vy(t,M,B,O,{authenticate:Q=>m.request("authenticate",{methodId:Q})}),resolveOnboarding:async M=>{if(M)try{return(await zd(n)).find(Q=>Q.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(M){t.grabInput(!1),h.close().catch(()=>{});let B=M instanceof Error?M.message:String(M);st({src:"session-new-failed",agentId:s.agentId??null,message:B});let O=await yb(t,s.agentId,B,{canGoBack:!s.forceNew});if(O==="cancel")return null;let Q={...s};return delete Q.sessionId,delete Q.resume,O==="retry"?Q.forceNew=!0:(delete Q.forceNew,delete Q.agentId),Q}if(I.kind==="cancel")return t.grabInput(!1),h.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),h.close().catch(()=>{});let M={...s};return delete M.sessionId,delete M.forceNew,delete M.resume,delete M.agentId,M}let C=I.result;d.write(c),ke=C.sessionId,r.sessionId=ke,r.readonly=!1;let A=Xt(C._meta??void 0);A.clientId&&(an=A.clientId),$n=A.upstreamSessionId,A.agentId&&(nt=A.agentId),A.cwd&&(lt=A.cwd),A.title&&(on=A.title),gt=A.currentModel,yt=A.currentMode,Qr=A.currentUsage,vn=A.turnStartedAt,A.availableCommands&&(ut=Ad(A.availableCommands)),A.availableModes&&(Yr=A.availableModes),Vr=Pb(C.configOptions),ks=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:pe},...Object.keys(g).length>0?{_meta:{[At]:g}}:{}});ke=w.sessionId,w.clientId&&(an=w.clientId),r.sessionId=ke,r.readonly=s.readonly===!0;let I=Xt(w._meta??void 0);tr=I.resurrected===!0,$n=I.upstreamSessionId,I.agentId&&(nt=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(on=I.title),gt=I.currentModel,yt=I.currentMode,Qr=I.currentUsage,vn=I.turnStartedAt,I.availableCommands&&(ut=Ad(I.availableCommands)),I.availableModes&&(Yr=I.availableModes),Vr=Pb(w.configOptions),ks=I.queue}let Is=_.tuiHistoryFile(ke),ho=_.globalTuiHistoryFile(),St=await Do(Is).catch(()=>[]),dn=await Do(ho).catch(()=>[]);dn.length>e.tui.promptHistoryMaxEntries&&(dn=dn.slice(dn.length-e.tui.promptHistoryMaxEntries));let me=[...St],Ie=new ms({history:cd(dn,me)});Se=Ie;let nr=!1,Ft=(g,w)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Ho(St,I),M=A!==St;St=A,me=Ho(me,C);let B=Ho(dn,I,e.tui.promptHistoryMaxEntries),O=B!==dn;dn=B,Ie.setHistory(cd(dn,me)),M&&Ar(Is,St).catch(()=>{}),O&&cm(ho,I).catch(()=>{})};L>0&&Ie.setTurnRunning(!0);let zt=null,cn=null;rb(ib(e.tui.ambiguousWidth,process.env)),ay(e.tui.diffContextLines);let Ot=!1,k,mo=()=>{Ot&&(Ot=!1,k.start())},Sa=()=>{Ot||(Ot=!0,k.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",mo);let xs=null,Gr=null;k=new Rc({term:t,dispatcher:Ie,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"?Sa:void 0,onBlockClick:(g,w)=>{tv(g,w)},onBlockDoubleClick:(g,w)=>ev(g,w),onBlockVisible:g=>{Gb(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=Es.get(g);if(w!==void 0&&w.length>0)return new Set(w);let I=k.contiguousRun(g,new Set(On.keys()));return I.length>0?new Set(I):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){xs=k.bannerHitAt(g.x,g.y),Gr=xs?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let I=Gr,C=xs;if(Gr=null,xs=null,C!==null&&I!==null&&I.x===g.x&&I.y===g.y&&k.bannerHitAt(g.x,g.y)===C){if(C==="mode"){Ts(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&jf(A))return;oe(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&jf(w)||oe(w)},onKey:g=>{for(let w of g){if(D&&Bc(w)||Te&&ir(w)||Nc(w)||Ca(w)||So(w)||Ia(w)||ka(w)||wo(w))continue;if(w.type==="key"&&w.name==="escape"&&k.isScrolledBack()){k.scrollToBottom();continue}if(w.type==="attachment-paths"){fe(w.paths);continue}let I=Ie.feed(w);for(let C of I)s.readonly===!0&&jf(C)||oe(C)}yo(),k.setBannerSearchIndicator(Ie.state().historySearchQuery),k.setAttachments(Ie.state().attachments),k.refreshPrompt()}}),Y=k,k.setStickyBottomKey("plan");let sr=[{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]"}],Ue=ut??[],Gn=Yr??[],go=Vr??[],Kt=()=>go.find(g=>g.id==="agent"),Oc=()=>{let g=new Set,w=[];for(let I of[...sr,...Ue])g.has(I.name)||(g.add(I.name),w.push(I));return w},ot=()=>{let g=Ie.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let I=w.indexOf(" "),C=I===-1?w:w.slice(0,I);if(C.lastIndexOf("/")>0)return[];let A=Oc().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Lt=[],yo=()=>{let g=ot();if(g.length>0){Lt=[],k.setCompletions(g);return}k.setCompletions(Lt)},ka=g=>{if(g.type!=="key"||g.name!=="tab")return Lt.length>0&&(Lt=[]),!1;let w=ot();if(k.isOverlayOpen()&&w.length===0)return k.toggleFocusedPane(),!0;if(w.length>0){Lt=[];let I=Ie.state().buffer[0]??"",C=ub({matches:w.map(A=>A.name),firstLine:I});return C===null||Ie.replaceFirstLine(C),!0}return rr()},rr=()=>{let g=Ie.state(),w=g.buffer[g.row]??"",I=kb(w,g.col);if(I===null)return!1;let C=Ib(I.token,lt);return C===null?!1:(C.replacement!==I.token&&Ie.replaceRangeOnCurrentLine(I.start,g.col,C.replacement),Lt=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},wo=g=>!k.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(F&&(F.cancel(),F=null,j=null),k.closeBtwOverlay(),!0),Ia=g=>{if(!k.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&k.isScrolledBack()?(k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=k.scrollbackSearchTerm()+g.ch;return k.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=k.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return k.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return k.advanceScrollbackSearch(),!0;case"ctrl-s":return k.retreatScrollbackSearch(),!0;case"backspace":{let w=k.scrollbackSearchTerm();return w.length===0?k.cancelScrollbackSearch():k.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return k.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return k.cancelScrollbackSearch(),!0;default:return!0}return!0},ir=g=>{if(!Te)return!1;let w=Te.options;if(g.type==="key")switch(g.name){case"up":return Te.selectedIndex=Math.max(0,Te.selectedIndex-1),er(),!0;case"down":return Te.selectedIndex=Math.min(w.length-1,Te.selectedIndex+1),er(),!0;case"enter":{let I=w[Te.selectedIndex];return I&&vt(I.optionId),!0}case"escape":case"ctrl-c":return vt(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,C=w[I];return C&&vt(C.optionId),!0}return!0},or=nt||fo||"?",Bt={...Qr??{}};d.finalize(),k.start({skipFullscreen:!0}),k.setHideThoughts(!i.showThoughts),k.setSessionbar({agent:or,cwd:lt,sessionId:ke,title:on,model:gt,usage:{...Bt}}),yt&&k.setBanner({currentMode:yt}),la().then(g=>{g&&k.notify(`\u2728 ${ua(g)}`,3e4)}).catch(()=>{});let kt=null,Lc=new Promise(g=>{kt=g}),bo=()=>{m.notify("session/cancel",{sessionId:ke}).catch(()=>{})},ar=()=>{Y!==null&&L===1&&(Z=!0,Y.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Xn=()=>{if(zt){zt.cancel(),ar();return}if(L>0){bo(),ar();return}Cs()},Cs=()=>{R(0)},Zn=()=>{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]],...rT]},As=()=>{if(k.isHelpPromptActive()){k.setHelpPrompt(null);return}k.setHelpPrompt({title:"Hotkeys",entries:Zn(),hint:"any key dismisses \xB7 /help lists commands"})},dr=()=>{D=!1,k.setCompactionPrompt(null),k.setCompactionIndicator("compaction queued...");let g=ke;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},Xr=()=>{D=!1,k.setCompactionPrompt(null)},vo=g=>{let w=k.compactionPromptSpec();if(!w)return;let I=w.options.length;if(I===0)return;let C=((w.selectedIndex+g)%I+I)%I;C!==w.selectedIndex&&k.setCompactionPrompt({...w,selectedIndex:C})},Bc=g=>{if(!D)return!1;if(g.type==="key"){if(g.name==="escape")return Xr(),!0;if(g.name==="up")return vo(-1),!0;if(g.name==="down")return vo(1),!0;if(g.name==="enter"){let w=k.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?dr():Xr(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return dr(),!0;if(w==="n"||w==="2")return Xr(),!0}return!0},Nc=g=>k.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",k.setHelpPrompt(null),!0):!1,es=["tools","plan","thoughts","diffs","mouse","enter"],Nt=0,ln=null,Zr=[],Pt=[],Fn=[],Jt=0,ts=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}},ei=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"}},xa=()=>({title:"Session options",options:es.map(g=>({label:ei(g),value:ts(g)})),selectedIndex:Nt}),ns=()=>{k.isOptionsPromptActive()&&ln===null&&k.setOptionsPrompt(xa())},ti=()=>{if(k.isOptionsPromptActive()){k.setOptionsPrompt(null);return}Nt=0,k.setOptionsPrompt(xa())},Yt=()=>{if(ln===null)return;let g=Z0(ln,Zr,Fn,Jt);k.setOptionsPrompt(g)},Rs=()=>{ln=null,Zr=[],Pt=[],Fn=[],Jt=0,k.setOptionsPrompt(null)},Sn=async()=>{if(ln!==null){Rs();return}try{let w=await m.request(Rw,{sessionId:ke}),I=V0(w.questions??[]);if(I.length===0){k.notify("no open questions");return}let C=G0(I);ln=C,Jt=0,Zr=C.map(A=>Q0(A.representative)),Pt=C.map(()=>!1),Fn=C.map(()=>!1),Yt()}catch(g){k.notify("clarifier unavailable"),st({src:"questions",step:"list_failed",error:g.message})}},cr=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,fr.clear(),ri.clear(),Jb();break;case"plan":i.planExpanded=!i.planExpanded,te=null,Ge();break;case"thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",rs.clear(),Xb();break;case"mouse":{let w=!k.isMouseEnabled();k.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}ns()},Vt=g=>{(async()=>{try{switch(g){case"tools":case"plan":k.notify(`${ei(g)} is session-only \u2014 not saved`);return;case"thoughts":await xo("showThoughts",i.showThoughts);break;case"diffs":await xo("showFileUpdates",i.showFileUpdates);break;case"mouse":await xo("mouse",i.mouseEnabled);break;case"enter":await xo("defaultEnterAction",i.defaultEnterAction);break}k.notify(`saved default: ${ei(g)} ${ts(g)}`)}catch(w){k.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},So=g=>{if(ln!==null||!k.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Nt=Math.max(0,Nt-1),ns(),!0;case"down":return Nt=Math.min(es.length-1,Nt+1),ns(),!0;case"enter":{let w=es[Nt];return w&&cr(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return k.setOptionsPrompt(null),!0;case"ctrl-d":return k.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,I=es[w];return I&&(Nt=w,cr(I)),!0}if(g.ch==="s"||g.ch==="S"){let w=es[Nt];return w&&Vt(w),!0}}return!0},Ca=g=>{if(ln===null)return!1;let w=nT(g,!0,ln,Zr,Pt,Fn,Jt,ke);switch(w.type){case"noop":return!0;case"row":return Jt=w.selectedRow,Yt(),!0;case"cycle":return Zr[w.selectedRow]=w.newValueIndex,Pt[w.selectedRow]=!0,Fn[w.selectedRow]=!1,Yt(),!0;case"dismiss-toggle":{let I=w.selectedRow;return Fn[I]?(Fn[I]=!1,Pt[I]=!1):(Fn[I]=!0,Pt[I]=!0),Yt(),!0}case"discard":return Rs(),!0;case"save":{let I=w.dispatches;return Rs(),I.length===0||(async()=>{let C=0,A=0,M=0;for(let O of I)try{await m.request(O.method,O.params),O.type==="dismiss"?A++:C++}catch(Q){M++,st({src:"questions",step:"dispatch_failed",method:O.method,error:Q.message})}let B=[];C>0&&B.push(`${C} answered`),A>0&&B.push(`${A} dismissed`),M>0&&B.push(`${M} failed`),B.length>0&&k.notify(`clarifier: ${B.join(", ")}`)})(),!0}}return!1},ni=()=>{b=!0,F?(F.cancel(),F=null,j=null):j!==null&&(Kn(n,j).catch(()=>{}),j=null),process.off("SIGINT",Xn),process.platform!=="win32"&&process.off("SIGCONT",mo),X!==null&&(clearInterval(X),X=null),de!==null&&(clearInterval(de),de=null);for(let g of Be.values())clearTimeout(g);Be.clear(),k.clearWindowTitle(),k.stop({keepFullscreen:!0}),Ar(Is,St).catch(()=>{}),h.close().catch(()=>{})},R=(g=0)=>{ni(),kt&&(kt(null),kt=null),g!==0&&process.exit(g)},P=async()=>{if(!kt)return;F?(F.cancel(),F=null,j=null):j!==null&&(Kn(n,j).catch(()=>{}),j=null),uo(),k.setSynthesisIndicator(null);let g=Ie.state().buffer.join(`
240
- `);g.replace(/\s+$/,"").length>0&&Ft(g),k.pauseRepaint(),k.stop({keepFullscreen:!0}),Ar(Is,St).catch(()=>{});let w=null,I=null;for(;w===null;){let B=await zn(n,{includeNonInteractive:!0}),O=await Df(t,{cwd:lt,sessions:B,config:e,target:n,currentSessionId:ke,prefs:o});if(O.kind==="abort"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(O.kind==="exit"){R(0);return}if(O.kind==="new"){w={choice:O,sessions:B};break}if(O.kind==="fork"){let ue=await Bb(t,n,O,B);if(ue.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(ue.kind==="back")continue;w={choice:{kind:"attach",sessionId:ue.ctx.sessionId,...ue.ctx.agentId?{agentId:ue.ctx.agentId}:{}},sessions:B},I={readonly:!1,cwd:ue.ctx.cwd},ue.ctx.resumeHint!==void 0&&(I.resumeHint=ue.ctx.resumeHint);break}let Q=B.find(ue=>ue.sessionId===O.sessionId);if(!(Q!==void 0&&!!Q.importedFromMachine&&!Q.upstreamSessionId&&O.readonly!==!0)){if(n.isLocal&&Q&&!Q.importedFromMachine&&O.readonly!==!0&&!(await pa(Q.cwd)).ok){let De=await Wr(t,Q,{defaultCwd:Ze(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(De.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(De.kind==="back")continue;w={choice:O,sessions:B},I={readonly:!1,cwd:De.path,resumeHint:{agentId:O.agentId??Q.agentId??"",cwd:De.path,upstreamSessionId:""}};break}w={choice:O,sessions:B};break}let Pe={...s,readonly:!1},le=await Ob(t,n,Q,O,Pe);if(le.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}le.kind!=="back"&&(w={choice:O,sessions:B},I={readonly:Pe.readonly===!0,cwd:le.ctx.cwd},le.ctx.resumeHint!==void 0&&(I.resumeHint=le.ctx.resumeHint))}let{choice:C}=w,A=kt;if(kt=null,process.off("SIGINT",Xn),h.close().catch(()=>{}),C.kind==="new"){let{sessionId:B,agentId:O,...Q}=s,Ne={...Q,cwd:C.cwd??lt,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Ne.initialPrompt=C.prompt),A(Ne);return}if(C.kind!=="attach")return;let M={...s,sessionId:C.sessionId,cwd:I?.cwd??lt,readonly:I?.readonly??C.readonly===!0};C.agentId!==void 0&&(M.agentId=C.agentId),I?.resumeHint!==void 0?M.resumeHint=I.resumeHint:delete M.resumeHint,A(M)},N=async(g="next")=>{if(!kt)return;let I=(await zn(n)).filter(Pe=>Pe.status==="warm");if(I.length<=1)return;let C=I.findIndex(Pe=>Pe.sessionId===ke),B=((C===-1?0:C)+(g==="prev"?-1:1)+I.length)%I.length,O=I[B],Q=kt;kt=null,process.off("SIGINT",Xn),h.close().catch(()=>{});let Ne={...s,sessionId:O.sessionId,cwd:lt,readonly:!1};O.agentId!==void 0&&(Ne.agentId=O.agentId),Q(Ne)},V=async g=>{if(!kt)return;let w=await zn(n,{includeNonInteractive:!0}),I=g.trim();if(!I){k.notify("usage: /session <id|next|prev>");return}let C=I.startsWith(gn)?[I]:[I,gn+I],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(Q=>C.some(Ne=>Q.sessionId.startsWith(Ne)));if(O.length===1)A=O[0];else if(O.length>1){k.notify(`ambiguous session id: ${I} (${O.length} matches)`);return}}if(!A){k.notify(`no session matches: ${I}`);return}if(A.sessionId===ke){k.notify("already on that session");return}let M=kt;kt=null,process.off("SIGINT",Xn),h.close().catch(()=>{});let B={...s,sessionId:A.sessionId,cwd:A.cwd??lt,readonly:A.status!=="warm"};A.agentId!==void 0&&(B.agentId=A.agentId),delete B.resumeHint,M(B)},oe=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?lr(g.text,g.attachments,g.displayText):In(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?In(g.text,g.attachments,g.displayText):lr(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=si(g.index);if(!w)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let C of g.attachments)I.push({type:"image",data:C.data,mimeType:C.mimeType});m.request("hydra-acp/prompt/update",{sessionId:ke,messageId:w,prompt:I}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&k.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{k.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=si(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:ke,messageId:w}).then(I=>{let C=I;!C.cancelled&&C.reason!=="ok"&&k.notify(`queue cancel skipped (${C.reason})`)}).catch(I=>{k.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(k.isOverlayOpen()){F&&(F.cancel(),F=null,j=null),k.closeBtwOverlay();return}if(g.prefill&&zt){let w=Je.size===0,I=Ie.state().buffer.every(C=>C==="");w&&I&&(cn={text:zt.text,attachments:zt.attachments})}zt?zt.cancel():L>0&&bo(),ar();return}case"exit":Cs();return;case"plan-toggle":Ts(g.on);return;case"redraw-banner":k.setBanner({});return;case"redraw":k.fullRedraw();return;case"scroll-to-top":k.scrollToTop();return;case"scroll-to-bottom":k.scrollToBottom();return;case"switch-session":P().catch(()=>{});return;case"next-live-session":N().catch(()=>{});return;case"toggle-options":ti();return;case"toggle-questions":Sn();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts),k.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!k.isMouseEnabled();k.setMouseEnabled(w),i.mouseEnabled=w,k.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":As();return;case"escalate-search":k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Fe(g.source);return}},fe=async g=>{if(!Jr){k.notify("agent does not accept image attachments");return}let w=0;for(let I of g){if(I.startsWith("data:")){let A=yf(I);if(!A){k.notify("unsupported data: URI");continue}if(A.sizeBytes>Vn){k.notify(`image too large (${bn(A.sizeBytes)}, max ${bn(Vn)})`);continue}Ie.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=ha(I);if(!C){k.notify(`unsupported image type: ${zr.basename(I)}`);continue}try{let A=await Uf.readFile(I);if(A.length>Vn){k.notify(`image too large (${bn(A.length)}, max ${bn(Vn)})`);continue}Ie.addAttachment({mimeType:C,data:A.toString("base64"),name:zr.basename(I),sizeBytes:A.length}),w++}catch(A){k.notify(`cannot read ${zr.basename(I)}: ${A.message}`)}}w>0&&(k.setAttachments(Ie.state().attachments),k.refreshPrompt())},Fe=async(g="clipboard")=>{let w=g==="primary"?await jw():await Uw();if(!w.ok){k.notify(w.reason);return}if(w.kind==="image"){if(!Jr){k.notify("agent does not accept image attachments");return}Ie.addAttachment(w.attachment),k.setAttachments(Ie.state().attachments),k.refreshPrompt();return}let I=Ie.feed({type:"paste",text:w.text});for(let C of I)oe(C);k.refreshPrompt()},Dt=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Mt=(g,w)=>{let I=Array.isArray(w)?w:[],C="",A=0;for(let M of I){if(!M||typeof M!="object")continue;let B=M;B.type==="text"&&typeof B.text=="string"?C+=B.text:B.type==="image"&&(A+=1)}return{messageId:g,text:Ae(C),attachmentCount:A}},Je=new Map,ft=[],un=new Map,wt=new Set,je=null,kn=()=>{let g=[...Je.values()],w=g.map(Dt);k.setQueuedPrompts(w),k.setBanner({queued:g.length}),Ie.setQueue(g.map(I=>I.text))},si=g=>[...Je.values()][g]?.messageId;if(ks&&ks.length>0){for(let g of ks){if(g.position===0){G=g.messageId;continue}Je.set(g.messageId,Mt(g.messageId,g.prompt))}Je.size>0&&kn()}let In=(g,w,I)=>{k.scrollToBottom(),!Aa(g)&&(Ft(g,I),ko(g,w,I))},lr=(g,w,I)=>{if(k.scrollToBottom(),Aa(g))return;if(Ft(g,I),!po||G===void 0){ko(g,w,I);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:I??g,attachments:w,flushed:!1};ft.push(M);let B=()=>{let O=ft.indexOf(M);O>=0&&ft.splice(O,1),M.messageId!==void 0&&un.delete(M.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:ke,targetMessageId:C,prompt:A}).then(O=>{let Q=O;if(Q.amended&&Q.reason==="ok"){Le(1);return}if(B(),Q.reason==="target_completed"){k.notify("previous response finished \u2014 press Enter to send as a new turn"),Ie.setBuffer(g,w),k.refreshPrompt();return}if(Q.reason==="target_cancelled"){k.notify("amend skipped \u2014 previous turn was cancelled"),Ie.setBuffer(g,w),k.refreshPrompt();return}if(Q.reason==="target_not_found"){k.notify("amend skipped \u2014 no matching prompt"),Ie.setBuffer(g,w),k.refreshPrompt();return}}).catch(O=>{B(),k.notify(`amend failed: ${O.message}`),Ie.setBuffer(g,w),k.refreshPrompt()})},Ts=async g=>{if(Gn.length===0){k.notify("no modes advertised by agent");return}let w=k.currentModeId(),I=Gn.findIndex(M=>M.id===w),C=I===-1?0:(I+1)%Gn.length,A=Gn[C]?.id;if(A){k.setBanner({currentMode:A});try{await m.request("session/set_mode",{sessionId:ke,modeId:A})}catch(M){k.notify(`set_mode failed: ${M.message}`)}}},Aa=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
241
- `))return!1;let I=w.indexOf(" ");switch(I===-1?w:w.slice(0,I)){case"/quit":case"/exit":return Cs(),!0;case"/clear":return pt.clear(),xn.clear(),at.length=0,E=null,U=null,re=null,ss.clear(),rs.clear(),is.clear(),fr.clear(),On.clear(),Es.clear(),k.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of sr)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(Ue.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of Ue)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return k.appendLines(A),!0}case"/agent":{let A=I===-1?"":w.slice(I+1).trim(),M=Kt();if(!M)return k.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let B=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of M.options){let Q=O.value===M.currentValue?"* ":" ";B.push({prefix:" ",body:`${Q}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return k.appendLines(B),!0}return M.options.some(B=>B.value===A)?A===M.currentValue?(k.notify(`already on agent ${A}`),!0):(k.notify(`switching to ${A}\u2026`),m.request("session/set_config_option",{sessionId:ke,configId:"agent",value:A}).catch(B=>{k.notify(`set_config_option failed: ${B.message}`)}),!0):(k.notify(`unknown agent: ${A}`),!0)}case"/sessions":return k.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return P().catch(()=>{}),!0;case"/session":{let A=I===-1?"":w.slice(I+1).trim();return A?A==="next"||A==="prev"?(N(A).catch(M=>{k.notify(`session ${A} failed: ${M.message}`)}),!0):(V(A).catch(M=>{k.notify(`session switch failed: ${M.message}`)}),!0):(P().catch(()=>{}),!0)}case"/rename":{let A=I===-1?"":w.slice(I+1).trim(),M=A.length>0?`/hydra title ${A}`:"/hydra title";return Ft(w,w),ko(M,[],w),!0}case"/btw":{let A=I===-1?"":w.slice(I+1).trim();if(!A)return k.isOverlayOpen()?(F&&(F.cancel(),F=null,j=null),k.closeBtwOverlay(),!0):(k.reopenBtwOverlay()||k.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(ke==="__new__")return k.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;H+=1;let M=H;F&&(F.cancel(),F=null);let B=null;j!==null&&!K?B=j:j!==null&&(Kn(n,j).catch(()=>{}),j=null),K=!1,k.openBtwOverlay(),k.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new vc({getMaxWidth:()=>{let le=k.width();return le>0?le:void 0}});O.on("changed",()=>{k.setBtwOverlayContent(O.getLines())});let Q={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Ne=le=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:le}})},Pe={};return B!==null&&(Pe.reuseSessionId=B),Mw(n,ke,A,Pe).then(le=>{if(M!==H){le.cancel();return}F=le,j=le.sessionId,k.setBtwOverlayMeta({sessionId:le.sessionId}),le.on("event",ue=>{if(M===H)if(ue.kind==="update"){O.append(ue.update);let De=qn(ue.update);if(De&&De.kind==="usage-update"){let mr=!1;De.used!==void 0&&Q.used!==De.used&&(Q.used=De.used,mr=!0),De.size!==void 0&&Q.size!==De.size&&(Q.size=De.size,mr=!0),De.costAmount!==void 0&&Q.costAmount!==De.costAmount&&(Q.costAmount=De.costAmount,mr=!0),De.costCurrency!==void 0&&Q.costCurrency!==De.costCurrency&&(Q.costCurrency=De.costCurrency,mr=!0),mr&&k.setBtwOverlayMeta({usage:{...Q}})}}else ue.kind==="completed"?(k.setBtwOverlayStatus({label:"done",style:"done"}),F=null):ue.kind==="cancelled"?(k.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),F=null,j=null):ue.kind==="errored"&&(k.setBtwOverlayStatus({label:"errored",style:"errored"}),Ne(`btw errored: ${ue.error.message}`),j!==null&&Kn(n,j).catch(()=>{}),F=null,j=null)})}).catch(le=>{if(M!==H)return;let ue=le instanceof Error?le.message:String(le);k.setBtwOverlayStatus({label:"errored",style:"errored"}),Ne(`btw startup failed: ${ue}`),k.appendLines([{prefix:" ",body:`btw startup failed: ${ue}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(ke==="__new__")return k.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=I===-1?"":w.slice(I+1).trim(),M=ke;return(async()=>{try{let B=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!B.ok){let ue=await B.text().catch(()=>"");k.appendLines([{prefix:" ",body:`/export failed: HTTP ${B.status} ${ue}`.trim(),bodyStyle:"info"}]);return}let O=await B.text(),Q=new Date().toISOString().replace(/[:.]/g,"-"),Ne=`hydra-${rt(M)}-${Q}.md`,Pe=A.length>0?Ze(A):Ne,le=zr.resolve(Pe);await Uf.mkdir(zr.dirname(le),{recursive:!0}),await Uf.writeFile(le,O,{encoding:"utf8",mode:384}),k.appendLines([{prefix:" ",body:`Wrote ${le}`,bodyStyle:"system"}])}catch(B){k.appendLines([{prefix:" ",body:`/export failed: ${B.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},ko=async(g,w,I)=>{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});Le(1);let A={text:g,displayText:I??g,attachments:w,flushed:!1};ft.push(A),Et=!1;let M=!1,B=null,O=Pe=>{typeof Y<"u"&&Y!==null&&Y.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},Q=!1;zt={text:g,attachments:w,cancel:()=>{if(Et){Et=!1,Q=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:ke}).catch(le=>{O(`force-stop failed: ${le.message}`)});return}if(M)return;M=!0,m.notify("session/cancel",{sessionId:ke}).catch(()=>{});let Pe=Date.now();B=setTimeout(()=>{zt!==null&&(vs>=Pe||(Et=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},rn)}};let Ne;try{let Pe=await m.request("session/prompt",{sessionId:ke,prompt:C});Pe&&typeof Pe.stopReason=="string"&&(Ne=Pe.stopReason)}catch(Pe){let le=ft.indexOf(A);le>=0&&ft.splice(le,1),A.messageId!==void 0&&un.delete(A.messageId),Q?k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):k.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Pe.message,bodyStyle:"tool-status-fail"}])}finally{if(zt=null,B!==null&&(clearTimeout(B),B=null),Le(-1),A.flushed&&je===A){let Pe=A.messageId!==void 0&&wt.has(A.messageId);Pe&&A.messageId!==void 0&&wt.delete(A.messageId);let le={kind:"turn-complete"};Ne!==void 0&&(le.stopReason=Ne),Pe&&(le.amended=!0),x(le),je=null}if(cn!==null){let{text:Pe,attachments:le}=cn;cn=null,Ie.state().buffer.every(De=>De==="")&&(Ie.setBuffer(Pe,le),k.refreshPrompt())}}},pt=new Map,ss=new Map,rs=new Map,xn=new Map,at=[],ur=0,Cn=`tools:${ur}`,is=new Map,fr=new Map,ri=new Set,os=new Map,On=new Map,Es=new Map,E=null,U=null,re=null,W=null,te=null,se=e.tui.maxToolItems,ve=e.tui.maxPlanItems,qe=()=>({maxPlanItems:te??i.planExpanded?1/0:ve}),Ge=()=>{if(W===null)return;let g=zs(W,qe());g.length>0&&k.upsertLines("plan",[{body:""},...g])},dt="",xe=null,It=0,Ht=()=>{if(xe===null)return;let g=k.width(),w=Ks(dt,g>0?{maxWidth:g}:void 0);w.length!==0&&k.upsertLines(xe,w)},Jf=g=>{g.length!==0&&(xe===null&&(k.ensureSeparator(),xe=`agent:${It}`,It+=1,dt=""),dt+=g,Ht())},fn=()=>{xe=null,dt=""},Ps="",pn=null,pr=0,hr=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Dc=()=>{if(pn===null||Ps.length===0)return;let g=Vi(Ps);g.length!==0&&k.upsertLines(pn,g)},Hc=g=>{let w=On.get(g);if(w===void 0)return[];let I=Vi(w.text);return w.workerTaskId&&I.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),I},Ra=(g,w)=>{g.length!==0&&(pn===null&&(k.ensureSeparator("thought"),pn=`thought:${pr}`,pr+=1,Ps=""),Ps+=g,On.set(pn,{text:Ps,workerTaskId:w}),Dc())},Ee=()=>{pn=null,Ps=""},as=g=>aT({...g,collapsedLimit:se}),Ms=g=>fr.get(g)??i.toolsExpanded,Ut=()=>{if(E===null)return;let{lines:g,rowOwners:w}=as({order:at,states:pt,startedAt:E,endedAt:U,stopReason:re,expanded:Ms(Cn),perToolExpanded:ri});k.upsertLines(Cn,g),os.set(Cn,w)},Ta=g=>{let w=is.get(g);if(!w)return;let{lines:I,rowOwners:C}=as({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Ms(g),perToolExpanded:ri});k.upsertLines(g,I),os.set(g,C)},Jb=()=>{E!==null&&!is.has(Cn)&&Ut();for(let g of is.keys())Ta(g)},Uc=()=>{E!==null&&is.set(Cn,{order:[...at],states:new Map(pt),startedAt:E,endedAt:U??Date.now(),stopReason:re,rowOwners:os.get(Cn)??[]})},Yf=()=>{ur+=1,Cn=`tools:${ur}`,E=Date.now(),U=null,re=null,Ut()};function Yb(g){if(!g||typeof g!="object")return null;let w=g,I=Array.isArray(w.content)?w.content:void 0;if(!I)return null;let C=[],A=M=>{if(typeof M=="string"){C.push({text:ct(M)});return}if(M&&typeof M=="object"){let B=M;typeof B.__hydraBlob=="string"&&C.push({hash:B.__hydraBlob})}};for(let M of I){if(!M||typeof M!="object")continue;let B=M;if(B.type==="content"&&B.content&&typeof B.content=="object"){let O=B.content;if(O.text!==void 0){A(O.text);continue}}if(B.type==="text"&&B.text!==void 0){A(B.text);continue}B.text!==void 0&&A(B.text)}return C.length>0?C:null}let Vf=(g,w)=>{let I=w.map(M=>"text"in M?M.text:"").join(`
242
- `);if(I.length===0)return;let{text:C,truncated:A}=ry(I);g.resultText=C,g.resultTruncated=A},Ea=new Set,Vb=(g,w)=>{!w.some(C=>"hash"in C)||Ea.has(g)||(Ea.add(g),(async()=>{let C=await Promise.all(w.map(async M=>"text"in M?M:{text:await jc(M.hash)??""}));Ea.delete(g);let A=pt.get(g);if(!A)for(let M of is.values()){let B=M.states.get(g);if(B){A=B;break}}if(A){Vf(A,C),pt.has(g)&&Ut();for(let[M,B]of is)B.states.has(g)&&Ta(M);k.repaintNow()}})().catch(()=>{Ea.delete(g)}))},Qf=(g,w,I,C,A,M,B,O,Q,Ne)=>{let Pe=!pt.has(g),le=pt.get(g),ue=le??{initialTitle:w??"tool",latestTitle:w??"tool",status:I??"pending",startedAt:Date.now()};if(!le&&Q!==void 0&&(ue.workerTaskId=Q),le&&w!==void 0&&(ue.latestTitle=w),M!==void 0&&ue.detail===void 0&&(ue.detail=M),B!==void 0&&ue.detailFull===void 0&&(ue.detailFull=B),O!==void 0&&O.length>0&&(ue.locations=O),le&&I!==void 0&&(ue.status=I),le||(ue.status=I??"pending"),ue.endedAt===void 0&&Bu(ue.status)&&(ue.endedAt=Date.now()),C!==void 0&&(ue.errorText=C),A!==void 0&&(ue.editDiff=A),Ne!==void 0){let De=Yb(Ne);De!==null&&(Vf(ue,De),De.some(mr=>"hash"in mr)&&Vb(g,De))}pt.set(g,ue),Pe&&(E===null&&(ur+=1,Cn=`tools:${ur}`,E=Date.now(),U=null,re=null),at.push(g))},jc=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:ke,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},Pa=new Set,Qb=(g,w)=>{Pa.has(g)||w.oldRef===void 0&&w.newRef===void 0||(Pa.add(g),(async()=>{let[I,C]=await Promise.all([w.oldRef?jc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?jc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&I===null||w.newRef!==void 0&&C===null){Pa.delete(g);let Ne=Ou(w,"diff",{deferredStatus:"error"});Ne.length>0&&(k.upsertLines(`editdiff:${g}`,Ne),k.repaintNow());return}let M={...w.path!==void 0?{path:w.path}:{},oldText:I??"",newText:C??""};ss.set(g,M);let B=pt.get(g);B?.editDiff&&(B.editDiff=M),Pa.delete(g);let O=rs.get(g),Q=O===void 0?i.showFileUpdates:O?"diff":"edit";Q!=="none"&&(Ma(g,M,Q==="diff"?"diff":"edit"),k.repaintNow())})())},Ma=(g,w,I)=>{let C=`editdiff:${g}`,A=Ou(w,I);if(A.length===0){k.removeKey(C);return}k.upsertLines(C,A),I==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&k.notifyWhenVisible(C)},Gb=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),I=ss.get(w);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Qb(w,I)},Gf=g=>{let w=`editdiff:${g}`,I=i.showFileUpdates,C=pt.get(g),A;if(I==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let B=rs.get(g);A=B!==void 0?B?"diff":"edit":I==="diff"?"diff":"edit"}if(A===null){k.removeKey(w);return}let M=C.editDiff;ss.set(g,M),Ma(g,M,A)},Xb=()=>{let g=i.showFileUpdates;for(let[w,I]of ss){let C=`editdiff:${w}`,A=rs.get(w),M=A===void 0?g:A?"diff":"edit";if(M==="none"){k.removeKey(C);continue}Ma(w,I,M==="diff"?"diff":"edit")}},Zb=g=>{if(!g.path)return null;let w=ct(g.oldText).split(`
243
- `),I=ct(g.newText).split(`
244
- `),C=0,A=Math.min(w.length,I.length);for(;C<A&&w[C]===I[C];)C++;let M=I[C];if(!M)return null;let B=zr.isAbsolute(g.path)?g.path:zr.resolve(lt,g.path),O;try{O=J0(B,"utf8")}catch{return null}let Q=O.split(`
245
- `);for(let Ne=0;Ne<Q.length;Ne++)if(Q[Ne]===M)return Ne+1;return null},ev=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=ss.get(I),M=pt.get(I)?.locations?.[0],B=M?.path??C?.path;if(!B)return!1;let O=null;M?.line!==void 0?O=M.line:C&&(O=Zb(C));let Q=O===null?"":`:${O}`;return k.tryOpenPathString(B+Q)}if(g.startsWith("tools:")){if(w===0)return!1;let I=os.get(g),C=I?I[w]:void 0;if(!C)return!1;let A=pt.get(C),M=A?.locations?.[0];if(M){let O=M.line===void 0?"":`:${M.line}`;if(k.tryOpenPathString(M.path+O))return!0}let B=A?.detailFull??A?.detail;if(B)return k.tryOpenPathString(B)}return!1},tv=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=ss.get(I);if(!C)return;let A=rs.get(I)??i.showFileUpdates==="diff";rs.set(I,!A),Ma(I,C,A?"edit":"diff"),k.repaintNow();return}if(g==="plan"){if(W===null)return;te=!(te??i.planExpanded),Ge(),k.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=fr.get(g)??i.toolsExpanded;fr.set(g,!A),g===Cn&&E!==null?Ut():Ta(g),k.repaintNow();return}let I=os.get(g);if(!I)return;let C=I[w];if(!C)return;iT(C,ri),Ta(g),k.repaintNow();return}if(g.startsWith("thought:")){if(!On.has(g))return;let I=Es.get(g);if(I!==void 0){Es.delete(g),k.setRunCollapsed(I,!1,Hc(g)),k.repaintNow();return}let C=k.contiguousRun(g,new Set(On.keys()));if(C.length===0)return;let A=C[0];Es.set(A,C),k.setRunCollapsed(C,!0,[hr()]),k.repaintNow();return}};v=(g,w)=>{if(g.kind==="available-commands"){Ue=g.commands,yo();return}if(g.kind==="available-modes"){Gn=g.modes;return}if(g.kind==="config-options"){go=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==nt&&(nt=C.currentValue,k.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(Gn=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"){k.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&k.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==nt&&(nt=g.agentId,k.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Bt.used!==g.used&&(Bt.used=g.used,C=!0),g.size!==void 0&&Bt.size!==g.size&&(Bt.size=g.size,C=!0),g.costAmount!==void 0&&Bt.costAmount!==g.costAmount&&(Bt.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Bt.costCurrency!==g.costCurrency&&(Bt.costCurrency=g.costCurrency,C=!0),C&&k.setSessionbar({usage:{...Bt}});return}if(g.kind==="user-text"){nr&&Ft(g.text),fn(),Ee(),E!==null&&(U=Date.now(),Ut()),je=null,k.ensureSeparator();let C=zs(g);C.length>0&&k.appendLines(C),Uc(),k.clearKey("plan"),W=null,te=null,pt.clear(),xn.clear(),at.length=0,U=null,Yf(),k.redraw();return}if(g.kind==="agent-text"){Ee(),xe===null&&$(g.workerTaskId),Jf(g.text);return}if(g.kind==="agent-thought"){fn(),pn===null&&$(g.workerTaskId),Ra(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){fn(),Ee();let C=xn.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(xn.set(g.toolCallId,A),A.plan.length===0)return;let M=ly(A);M.length>0&&k.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){fn(),Ee(),pt.has(g.toolCallId)||$(g.workerTaskId),Qf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Ut(),Gf(g.toolCallId);return}if(g.kind==="plan"){fn(),Ee(),W=g;let C=zs(g,qe());C.length>0&&k.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(M=>(M.status??"pending")==="completed");k.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){fn(),Ee(),Qf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(ws=!0),Ut(),Gf(g.toolCallId);return}g.kind==="model-changed"&&k.setSessionbar({model:g.model});let I=zs(g);if(I.length>0&&k.appendLines(I),g.kind==="turn-complete"){G=void 0,fn(),Ee();let C=g.amended?"amended":g.stopReason;if(!g.amended&&ws&&(C===void 0||C==="end_turn")&&(C="error"),W!==null&&C!==void 0&&C!=="end_turn"){let A=zs({...W,stopped:!0,amended:g.amended===!0},qe());A.length>0&&k.upsertLines("plan",[{body:""},...A])}W=null,te=null,k.clearKey("plan"),k.setStickyBottomKey("plan"),E!==null?(U=Date.now(),re=C??null,Ut(),Uc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),pt.clear(),xn.clear(),at.length=0,E=null,U=null,re=null,ws=!1,k.ensureSeparator(),Ab({pendingTurns:L,queueSize:Je.size,ownTurnInFlight:zt!==null,hasInFlightHead:G!==void 0,replayDraining:S,amended:g.amended===!0})&&Le(-L)}};let Xf=y;y=[];let _a=[];for(let{event:g}of Xf)g.kind==="user-text"&&typeof g.text=="string"&&_a.push(g.text);k.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of Xf)v(g,w)}finally{S=!1,k.resumeRepaint()}if(_a.length>0){let g=eu(St,_a);g!==St&&(St=g,me=eu(me,_a),Ie.setHistory(cd(dn,me)),Ar(Is,St).catch(()=>{}))}nr=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(ke)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),I=w.compactionState?.status;if(I==="requested"||I==="running"?k.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&k.setCompactionIndicator("compaction queued (waiting for idle)"),!tr||w.shouldCompact!==!0)return;let C=w.approxTokens??0;D=!0,k.setCompactionPrompt({message:`This session has ~${Mm(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(ke)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(k.setSynthesisIndicator("synthesizing context\u2026"),Zs()):w.forkSynthesisState==="failed"&&(k.setSynthesisIndicator("\u26A0 synthesis failed"),k.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),vn!==void 0&&L>0?(be=vn,k.setBanner({status:"busy",elapsedMs:Date.now()-vn}),X===null&&(X=Xs()),E===null&&Yf(),E=vn,Ut()):vn===void 0&&L>0&&Le(-L);let nv=()=>{if(Te){let g=Te.resolve;Te=null,k.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}fn(),Ee()},Zf=()=>{E!==null&&(U=Date.now(),re="reconnect-recovery-failed",Ut(),Uc(),pt.clear(),xn.clear(),at.length=0,E=null,U=null,re=null)};return p=g=>{st({src:"reconnect",step:"disconnect",message:g?.message}),k.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{st({src:"reconnect",step:"begin",sessionId:ke}),nv();let g={jsonrpc:"2.0",id:`tui-reinit-${Eb()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}}};st({src:"reconnect",step:"initialize-send"});try{await h.request(g),st({src:"reconnect",step:"initialize-ok"})}catch(O){st({src:"reconnect",step:"initialize-fail",message:O.message})}let w=Qn!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Eb()}`,method:"session/attach",params:{sessionId:ke,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Qn}:{},clientInfo:{name:"hydra-acp-tui",version:pe},...(()=>{let O={};return $n!==void 0&&(O.resume={upstreamSessionId:$n,agentId:nt,cwd:lt}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[At]:O}}:{}})()}};ye=[];let C,A,M;st({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:Qn});try{let O=await h.request(I);if(st({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);M=Cb(O.result),C=M.appliedPolicy,M.clientId!==void 0&&(an=M.clientId)}catch(O){A=O,st({src:"reconnect",step:"attach-fail",message:A.message})}let B=ye??[];if(ye=null,A)Zf(),k.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")Zf(),k.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 B)it(O)}finally{S=!1}}if(M){let O=Rb({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&Le(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(be=O.busySince,k.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),X===null&&(X=Xs())):k.setBanner({status:"ready",elapsedMs:void 0})}else k.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});st({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
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.`)+`
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(`
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
248
  connection lost: ${g.message}
247
- `),R(g?1:0)}),process.on("SIGINT",Xn),s.initialPrompt&&a.sessionId==="__new__"&&In(s.initialPrompt,[]),await Lc}async function cT(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 $b(t,n,s,i)!=="ok"?null:_b(s,o,e);if(s.resume){let a=await zn(n,{cwd:o,all:!0}),c=Jd(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(t.yellow(`No sessions found for ${o}.
248
- `),null)}for(;;){let a=await zn(n,{includeNonInteractive:!0}),c=await Df(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 $b(t,n,s,i);if(u==="cancel")return null;if(u==="back")continue;return _b(s,o,e)}if(c.kind==="fork"){let u=await Bb(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 Ob(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 pa(d.cwd)).ok){let f=await Wr(t,d,{defaultCwd:Ze(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(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 Ob(t,e,n,s,r){for(;;){let i=await db(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 Lb(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await Wr(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 Lb(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 Hf(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 Bb(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await Lb(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 Wr(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 Kd(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
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
251
  fork failed: ${u.message}
250
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function _b(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function $b(t,e,n,s){if(n.agentId||await up())return"ok";let r;try{r=await zd(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await we(),o=s.lastChosenAgent??i.defaultAgent,a=await Hf(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 Oa(a.agentId)}catch{}return"ok"}function lT(t,e){st({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function uT(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(`
251
- `))}}}var qf,sT,rT,Mb,Nb=J(()=>{"use strict";Ir();Rt();of();Ye();uf();Sr();Mr();Yo();Ao();Pw();Hn();he();dl();Zt();mc();cf();ld();ta();_w();$w();mb();Lf();Of();gb();rf();wb();Ff();fu();mf();Ic();Sf();Pc();xb();Tb();Ds();Qi();qf="dismiss";sT=12e4;rT=[["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"]];Mb=!1});var Db={};qc(Db,{runTui:()=>Fb});var Hb=J(()=>{"use strict";Nb()});import{readFileSync as fT}from"fs";import{fileURLToPath as pT}from"url";import{dirname as hT,resolve as mT}from"path";var ep=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"]),rv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function tp(t){for(let e of Object.keys(t))if(!ep.has(e)&&!rv.has(e))return e}function Wc(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(ep.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 iv(t,e){let n=t[e];if(typeof n=="string")return n}function ii(t,e){return t[e]===!0||t[e]==="true"}var ov="HYDRA_ACP_";function av(t){return ov+t.toUpperCase().replace(/-/g,"_")}function ht(t,e){let n=iv(t,e);return n!==void 0?n:process.env[av(e)]}Ye();Sr();async function Tp(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=Qc(n);return{target:await Ap(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await we();return{target:await jt(s),sessionId:n,fromUrl:!1}}function al(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}dl();he();Ye();ds();import*as Mp from"fs/promises";async function _p(t){if(await Mp.mkdir(_.home(),{recursive:!0}),await Fa(),!await di()){let n=ai();await ci(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 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
254
  Service token: ${n}
253
- `);return}if(ii(t,"rotate-token")){let n=ai();await ci(n),process.stdout.write(`Rotated token in ${_.authToken()}
255
+ `);return}if(ci(t,"rotate-token")){let n=ui();await pi(n),process.stdout.write(`Rotated token in ${_.authToken()}
254
256
  New token: ${n}
255
257
  `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
256
258
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
257
- `)}he();ui();Ye();ds();import{setTimeout as tC}from"timers/promises";import Ag from"chalk";import*as vg from"fs";import*as Bi from"fs/promises";import*as Sg from"net";import*as kg from"tls";import Wx from"fastify";import zx from"@fastify/websocket";var $p="acp.v1";function Fp(t,e){return t.has($p)?$p:!1}Ye();import bg from"pino";import Kx from"pino-roll";he();import*as Ct from"fs/promises";import{createHash as Kv}from"crypto";import{gzip as Jv,gunzip as Yv}from"zlib";import{promisify as Op}from"util";var Lp=Op(Jv),Vv=Op(Yv),Bp=/^[A-Za-z0-9_-]+$/,Qv=/^[a-f0-9]{64}$/,cl=!0;function Np(t){cl=t}function Ha(t,e){return Bp.test(t)?e===void 0||Qv.test(e):!1}function Ua(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function ll(t,e){if(!Ha(t))return null;let n=Kv("sha256").update(e,"utf8").digest("hex"),s=Ua(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await Ct.access(a),n}catch{}await Ct.mkdir(_.toolsDir(t),{recursive:!0});let i=cl?s:r,o=cl?await Lp(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await Ct.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function ja(t,e){if(!Ha(t,e))return null;try{let n=await Ct.readFile(Ua(t,e));return(await Vv(n)).toString("utf8")}catch{}try{return await Ct.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Dp(t,e){if(!Ha(t,e))return null;try{return await Ct.readFile(Ua(t,e))}catch{}try{let n=await Ct.readFile(_.toolBlobFile(t,e));return await Lp(n)}catch{return null}}async function Hp(t,e,n){if(!Ha(t,e))return;let s=Ua(t,e);try{await Ct.access(s);return}catch{}await Ct.mkdir(_.toolsDir(t),{recursive:!0}),await Ct.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Up(t){Bp.test(t)&&await Ct.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();Ye();yr();import*as Xp from"fs/promises";import*as Wa from"path";import{z as ie}from"zod";he();import*as qp from"fs";import*as _t from"fs/promises";import*as $s from"path";import{spawn as Wp}from"child_process";import{Readable as Gv}from"stream";function Bn(){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 pl(t,e=Bn()){if(e)return t[e]}var fi=t=>{process.stderr.write(t+`
258
- `)};function hl(t){fi=t??(e=>process.stderr.write(e+`
259
- `))}async function zp(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Bn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Bn();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=$s.resolve(n,t.target.cmd);if(await fl(s))return s;if(await Xv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await fl(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await _t.chmod(s,493).catch(()=>{}),s}async function Xv(t){await _t.mkdir($s.dirname(t.installDir),{recursive:!0});let e=await _t.mkdtemp(`${t.installDir}.partial-`);try{fi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await Zv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});fi(`hydra-acp: extracting ${t.agentId}`),pi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await tS(n,e),await _t.unlink(n).catch(()=>{});try{await _t.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await fl(t.installDir)){await _t.rm(e,{recursive:!0,force:!0}).catch(()=>{}),pi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}fi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),pi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await _t.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function pi(t,e){if(t)try{t(e)}catch{}}async function Zv(t){let e=eS(t.url),n=$s.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=qp.createWriteStream(n),o=Gv.fromWeb(s.body);pi(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,pi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,fi(jp(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),fi(jp(t.agentId,a,r,!0)),pi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function jp(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 eS(t){let e=new URL(t);return $s.posix.basename(e.pathname)||"archive"}async function tS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await ul("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await nS("unzip")){await ul("unzip",["-q",t,"-d",e]);return}await ul("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function ul(t,e){return new Promise((n,s)=>{let r=Wp(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 nS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Wp(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function fl(t){try{return await _t.access(t),!0}catch{return!1}}he();import*as Gt from"fs/promises";import*as Nn from"path";import{spawn as sS}from"child_process";var gl=t=>{process.stderr.write(t+`
260
- `)};function yl(t){gl=t??(e=>process.stderr.write(e+`
261
- `))}async function Jp(t){let e=Bn();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=dS(t.packageSpec),r=cS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Nn.join(n,"node_modules",".bin",t.bin);if(await kr(o))return o;if(await kr(n)){let u=await Kp(i);if(u)return u.binPath}await rS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Kp(i);if(a)return a.binPath;let c=await Vp(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 rS(t){await Gt.mkdir(Nn.dirname(t.installDir),{recursive:!0});let e=await Gt.mkdtemp(`${t.installDir}.partial-`);try{gl(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),ml(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await aS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Gt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await kr(t.installDir)){await Gt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),ml(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}gl(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),ml(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Gt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function ml(t,e){if(t)try{t(e)}catch{}}var iS=5,oS=25;function aS(t){return Yp(t,0)}async function Yp(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=sS("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})
262
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<iS)return await new Promise(r=>setTimeout(r,oS*(e+1))),Yp(t,e+1);throw n}}function dS(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 cS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Vp(t,e){let n=Nn.join(t,"node_modules",e,"package.json");try{let s=await Gt.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 Kp(t){let e=Nn.join(t.installDir,"node_modules",".bin"),n=Nn.join(e,t.hint);if(await kr(n))return{binName:t.hint,binPath:n};let s=await Vp(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Nn.join(e,i);if(await kr(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=Nn.join(e,i);if(await kr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Nn.join(e,t.basename);if(await kr(r))return{binName:t.basename,binPath:r}}}async function kr(t){try{return await Gt.access(t),!0}catch{return!1}}var lS=ie.object({package:ie.string(),bin:ie.string().optional(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),hi=ie.object({archive:ie.string().url().optional(),cmd:ie.string().optional(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),uS=ie.object({"darwin-aarch64":hi.optional(),"darwin-x86_64":hi.optional(),"linux-aarch64":hi.optional(),"linux-x86_64":hi.optional(),"windows-x86_64":hi.optional(),"windows-aarch64":hi.optional()}),fS=ie.object({package:ie.string(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),pS=ie.object({command:ie.string(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),hS=ie.object({command:ie.string().optional(),url:ie.string().optional(),description:ie.string().optional()}),mS=ie.object({npx:lS.optional(),binary:uS.optional(),uvx:fS.optional(),exec:pS.optional()}),gS=ie.object({id:ie.string(),name:ie.string(),version:ie.string().optional(),description:ie.string().optional(),authors:ie.array(ie.string()).optional(),license:ie.string().optional(),icon:ie.string().optional(),repository:ie.string().optional(),website:ie.string().optional(),distribution:mS,onboarding:hS.optional(),requiredEnv:ie.array(ie.string().min(1)).optional()}),Qp=ie.object({version:ie.string(),agents:ie.array(gS),extensions:ie.array(ie.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=>wl(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:Ze(n.command??e),args:n.args?.map(Ze),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:yS(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=Qp.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 hn(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Qp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Qt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function yS(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 wl(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 mi(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 bl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function bl(t){let e=Bn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=pl(t.distribution.binary,e);if(s?.cmd){let r=Wa.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await Gp(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??wl(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=Wa.join(i,"node_modules",".bin",r);if(await Gp(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Gp(t){try{return await Xp.access(t),!0}catch{return!1}}async function mn(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??wl(t)??r.package,a=n.onInstallProgress;return{command:await Jp({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=pl(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Bn()??"this platform"}.`);let i=n.onInstallProgress,o=await zp({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 kS}from"child_process";import*as Ga from"fs";import*as hh from"path";Rt();function Qa(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();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(`
263
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(`
264
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)+`
265
- `;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()}}}Ir();he();var IS=4096,Os=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??IS,this.killEscalationMs=e.killEscalationMs??xS,this.logger=e.logger,this.fileLog=CS(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()} ---
266
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=Qa(n.stdout,n.stdin);this.connection=new qt(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 _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
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()} ---
268
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}
269
- stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=kS(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=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()} ---
270
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()} ---
271
- `),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)})}},xS=2e3;function CS(t){try{let e=_.agentLogFile(t);Ga.mkdirSync(hh.dirname(e),{recursive:!0});let n=Ga.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Tr from"fs/promises";import*as pd from"os";import*as Wo from"path";import{customAlphabet as Fk}from"nanoid";xl();Hn();Wl();he();yr();import*as us from"fs/promises";import{z as Un}from"zod";var wk=Un.object({version:Un.literal(1),agentId:Un.string(),upstreamSessionId:Un.string(),deletedAt:Un.string(),upstreamUpdatedAt:Un.string().optional(),cwd:Un.string().optional(),title:Un.string().optional(),reason:Un.enum(["user","expired"]).optional(),interactive:Un.boolean().optional()}),rd=class{async add(e){let n={version:1,...e};await Qt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await us.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await hn(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 wk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await us.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await us.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 us.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 us.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 jh(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as tm from"fs/promises";Rt();Zt();nd();td();var Sk=12e4;async function Wh(t,e,n){let s=t.timeoutMs??Sk,r,i,o=!1;try{let a=(async()=>{r=Os.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:pe}}),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=Ik(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=kk(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 od(t){let e=Si(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)})}},$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}
272
274
 
273
275
  ${e}
274
276
 
275
- ${Ll}`:`${n}
277
+ ${zl}`:`${n}
276
278
 
277
- ${Ll}`;return Wh(t,s,Dh)}async function zh(t){let e=Si(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
+ ${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}
278
280
 
279
281
  ${e}
280
282
 
281
- ${Bl}`:`${n}
283
+ ${Kl}`:`${n}
282
284
 
283
- ${Bl}`;return Wh(t,s,Hh)}function kk(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 Ik(t){let e=new Set;qh(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&qh(e,n.availableModels),e}function qh(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)}}}Jl();he();var xk=2,ad=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??xk}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]="title",this.drain())}scheduleCompaction(e){if(this.stopped||this.inflight.has(e))return;if(this.queued[e]==="title"){this.queued[e]="compaction";return}this.queued[e]="compaction",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){try{let s=await this.opts.store.read(e);if(!s){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let r=await this.opts.histories.load(e,{maxEntries:1/0}),i=s.summarizedThroughEntry;if(i!==void 0&&r.length<=i){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${r.length})`);return}let o=n==="compaction"?this.opts.compactionAgent??s.agentId:this.opts.synopsisAgent??s.agentId,a=await this.opts.registry.getAgent(o);if(!a){this.opts.logger?.warn(`synopsis: agent ${o} not in registry for session ${e}; skipping`);return}let c=await mn(a,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.compactionAgent===void 0,l=n==="compaction"?this.opts.compactionModel??(d?s.currentModel:void 0):this.opts.synopsisModel,u=_.sessionDir(e);if(await tm.mkdir(u,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${r.length} model=${JSON.stringify(l??"(default)")} cwd=${u}`),n==="compaction"){let f=this.opts.compactionMaxIterations??3,p=0,h=i??0,m,y=0,v,b=Date.now();await this.opts.onCompactionStateChange?.(e,{status:"requested",requestedAt:b}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{p++,this.opts.logger?.info(`synopsis: compaction iteration ${p} sessionId=${e} historyLen=${r.length} watermark=${h}`);let S=await this.opts.histories.load(e,{maxEntries:1/0});if(S.length<=h)break;let x=await zh({agentId:o,cwd:u,plan:c,history:S,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,F)=>{this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:b,iter:p,worker:{upstreamSessionId:$,pid:F??0}})},onFailure:$=>{v=$}});if(x){let $=Xh(x.synopsis,S);$&&Zh($)&&(await this.opts.persistSynopsis(e,$,S.length),m=$,y=S.length,v=void 0,await this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:b,iter:p}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"iteration",iter:p,historyLen:S.length}),await this.opts.onCompactionArtifact?.(e,$,y),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${p} fields=${em($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${p} returned no result`);if(h=S.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(p<f);if(m)p>=f&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${p}`);else{p>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${f} without producing artifact sessionId=${e}: ${v??"no reason captured"}`);let S=v??(p===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${p} iteration(s)`);await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:b,iter:p,lastError:S}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:S})}}catch(S){let x=S instanceof Error?S.message:String(S);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${x}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:b,iter:p,lastError:x}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:x})}}else{let f=await od({agentId:o,cwd:u,plan:c,history:r,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!f){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let p=Xh(f.synopsis,r);p&&Zh(p)?(await this.opts.persistSynopsis(e,p,r.length),f.title&&await this.opts.persistTitle(e,f.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${em(p)}`)):f.title&&(await this.opts.persistTitle(e,f.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function Xh(t,e){let n=Vh(e),s=Yh(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 Zh(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 em(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 $t from"fs/promises";function nm(t){return t==="summary"?"summary":"inline"}var Yl=256;function sm(t,e){return e!=="summary"?t:t.map(Ck)}function Ck(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(rm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Vl(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function Ak(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function rm(t){if(Ak(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=Vl(e.text)),typeof e.content=="string"?n.content=Vl(e.content):e.content&&typeof e.content=="object"&&(n.content=rm(e.content)),n}function Vl(t){if(typeof t=="string"&&t.length>Yl){let e=t.length-Yl;return`${t.slice(0,Yl)}\u2026[+${e} chars omitted from summary export]`}return t}var Rk=2048;function im(t){let e=new Set,n=s=>{if(om(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 om(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Tk(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 Xl(t,e){if(!Tk(t))return t;let n=t.params,s=n.update,r=await Ql(s,e);return{...t,params:{...n,update:r}}}async function Ql(t,e){if(typeof t=="string"){if(t.length<=Rk)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 Ql(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Ql(r,e);return n}return t}async function am(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await Gl(n,e);return s===n?t:{...t,params:s}}async function Gl(t,e){if(om(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await Gl(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 Gl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Bo=/^[A-Za-z0-9_-]+$/,Ek=1e3,dd=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Ek}async append(e,n){if(Bo.test(e))return this.enqueue(e,async()=>{await $t.mkdir(_.sessionDir(e),{recursive:!0});let s=await Xl(n,i=>ll(e,i)),r=JSON.stringify(s)+`
284
- `;await $t.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Bo.test(e))return this.enqueue(e,async()=>{await $t.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Xl(i,o=>ll(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
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
287
  `)+`
286
- `;await $t.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Bo.test(e))return this.enqueue(e,async()=>{let s;try{s=await $t.readFile(_.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
287
- `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await $t.writeFile(_.historyFile(e),i.join(`
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(`
289
+ `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await Lt.writeFile(_.historyFile(e),i.join(`
288
290
  `)+`
289
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Bo.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await $t.readFile(_.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
290
- `)){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 ja(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await am(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Bo.test(e))return this.enqueue(e,async()=>{try{await $t.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Up(e);try{await $t.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();Ye();ld();Rr();ed();Rt();Rt();Zt();Ml();var lm=900*1e3,um=5e3,fm=3,Ok="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ud=Fk(Ok,16),fd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>Os.spawn(a)),this.store=s??new sd,this.tombstones=r.tombstones??new rd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new dd({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 ad({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)=>{let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c)=>{this.broadcastHydraCompaction(a,c)},onCompactionArtifact:async(a,c,d)=>{let l=this.get(a);if(!l){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${a}`),await this.mutateRecord(a,{synopsis:c,summarizedThroughEntry:d});return}try{if(!await l.isQuiescedForSwap()){let f=this.compactionDeferrals.get(a)??0;if(f++,f>fm){this.logger?.warn(`compaction: deferral cap reached for sessionId=${a}, skipping swap until next trigger`),this.compactionDeferrals.delete(a),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"]),l.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached"});return}this.compactionDeferrals.set(a,f),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${f}`),l.broadcastCompactionPhase({phase:"deferred",attempts:f}),setTimeout(()=>{this.retrySwap(a)},um).unref();return}this.compactionDeferrals.delete(a),await l.swapUpstream({artifact:c,tailK:o,summarizedThroughEntry:d}),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"])}catch(u){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${u instanceof Error?u.message:String(u)}, leaving session as-is`)}}}),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;compactionDeferrals=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async retrySwap(e){let n=this.get(e);if(!n){this.compactionDeferrals.delete(e);return}let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let o=this.compactionDeferrals.get(e)??0;if(o++,o>fm){this.logger?.warn(`compaction: deferral cap reached on retry for sessionId=${e}, giving up`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]),n.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached on retry"});return}this.compactionDeferrals.set(e,o),this.logger?.info(`compaction: still not quiesced on retry, re-deferring sessionId=${e} attempt=${o}`),setTimeout(()=>{this.retrySwap(e)},um).unref();return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing on retry for sessionId=${e}, skipping swap`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}this.compactionDeferrals.delete(e),await n.swapUpstream({artifact:i.synopsis,tailK:s,summarizedThroughEntry:i.summarizedThroughEntry}),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"])}catch(r){this.logger?.warn(`compaction: retrySwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async refreshAgentCatalog(){try{let{agents:e}=await mi(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_${ud()}`,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 xi({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:()=>this.synopsisCoordinator.scheduleCompaction(r.sessionId),getCompactionState:()=>this.getCompactionState(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 mn(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:gi,clientInfo:{name:"hydra",version:pe}});o=m.agentCapabilities,i.authMethods=jo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ls(m,i)}let a;try{let m=pm(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(()=>{}),Ls(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
291
- `),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=iu(a??{}),d=e.agentModes??nu(ru(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 yi({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=tu(a??{}),f=nu(su(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 wi({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 xi({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:()=>this.synopsisCoordinator.scheduleCompaction(h.sessionId),getCompactionState:()=>this.getCompactionState(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 yi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await wi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new xi({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:()=>this.synopsisCoordinator.scheduleCompaction(c.sessionId),getCompactionState:()=>this.getCompactionState(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 Tr.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:Ze(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 mn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:pd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:gi,clientInfo:{name:"hydra",version:pe}})}catch(p){throw await r.kill().catch(()=>{}),Ls(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(Lk(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!jh(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=`${gn}${ud()}`,v=new Date().toISOString(),b=p.updatedAt??v,S={sessionId:y,lineageId:Oo(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:b,updatedAt:b};p.title!==void 0&&(S.title=p.title);let x=ql(S);await this.store.write(x),u.push({version:1,...x})}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 mn(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:gi,clientInfo:{name:"hydra",version:pe}}),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=tu(a),l=su(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=vi(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(v=>v.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=ru(a),p=iu(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(()=>{}),Ls(mm(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 mn(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:gi,clientInfo:{name:"hydra",version:pe}}),a=o.agentCapabilities;i.authMethods=jo(o.authMethods);let c=pm(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=tu(d),u=nu(su(d)),f=ru(d),p=iu(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(()=>{}),Ls(mm(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 mn(r,[],{npmRegistry:this.npmRegistry}),o=n??Ze(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:gi,clientInfo:{name:"hydra",version:pe}});a.authMethods=jo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ls(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 mn(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=Ti({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:ym(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=Bk(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 ja(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:Nk(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=ki(r.update.prompt),o=Ol(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(gn))return;let n=gn+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 qo(n.sessionId),c=Ti({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 qo(s.sessionId),i=Ti(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=>qo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Ti({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=>qo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Ti(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=Oo(),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 gm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of im(o)){let l=await Dp(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=`${gn}${ud()}`;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 x=new Error(`agent ${r} not found in registry`);throw x.code=z.AgentNotInstalled,x}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=Fl(o,n.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw x.code=z.InvalidParams,x}c=n.forkAt,a=o.slice(0,S+1)}else{let S=Hk(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 x=new Error(`agent ${r} not found in registry`);throw x.code=z.AgentNotInstalled,x}f=S,u=s.currentModel,l="running"}let h=await gm(e),m=d==="synthesis",y={...s,lineageId:Oo(),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}:{}},v=Uo({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:pe,machine:pd.hostname()}),b=`${gn}${ud()}`;return await this.writeImportedRecord({sessionId:b,bundle:v,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await mn(f,[],{npmRegistry:this.npmRegistry}),x=await od({agentId:r,cwd:n.cwd??_.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});x&&x.synopsis?await this.mutateRecord(b,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(b,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(b,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:b,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 Hp(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Tr.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Ar(_.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 qo(e),i=Ti(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){this.synopsisCoordinator.scheduleCompaction(e)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}broadcastHydraCompaction(e,n){let s=this.get(e);s&&s.broadcastCompactionPhase(n)}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 resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Ch(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<lm),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${lm/1e3}s)`),await _o(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 _o(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 Lk(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Wo.resolve(t),s=Wo.resolve(e);return n===s||n.startsWith(s+Wo.sep)}function Bk(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 ql({sessionId:t.sessionId,lineageId:e?.lineageId??Oo(),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:ym(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 ym(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 Nk(t){return t?{...t}:void 0}function pm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function hd(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=Dk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function tu(t){return hd(t,{nestedKey:"models",configId:"model",fromObject:e=>jn(e.currentModelId)??jn(e.currentModel)??jn(e.modelId)??jn(e.model),fromConfig:e=>jn(e.currentValue)})}function Ls(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 hm(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function mm(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 ${hm(s.cwd)} && ${[s.command,...s.args].map(hm).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(`
292
- `));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 jn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Dk(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 nu(t){return t.length>0?t:void 0}function su(t){return hd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Ii(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Ii(e.options);return n.length>0?n:void 0}})??[]}function ru(t){return hd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=$o(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=$o(e.options);return n.length>0?n:void 0}})??[]}function iu(t){return hd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>jn(e.currentModeId)??jn(e.currentMode)??jn(e.modeId)??jn(e.mode),fromConfig:e=>jn(e.currentValue)})}function Hk(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 gm(t){try{let e=await Tr.readFile(_.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
293
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function qo(t){try{let e=await Tr.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ti(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Cr?!1:e?!0:void 0}import{spawn as Uk}from"child_process";import*as Pi from"fs";import*as Bs from"fs/promises";import*as wm from"path";var md=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_}};Ye();var jk=1e3,qk=6e4,ou=3e3,Ei=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??jk,this.restartCapMs=r.restartCapMs??qk;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 Bs.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()},ou);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 zo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw zo(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 zo(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 zo(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 zo(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{}},ou);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 md(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Bs.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=wm.join(this.adapter.paths.dir(),n),r;try{let i=await Bs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&au(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+ou;for(;Date.now()<i&&au(r);)await new Promise(o=>setTimeout(o,50));if(au(r))try{process.kill(r,"SIGKILL")}catch{}}await Bs.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=Pi.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(!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})
294
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
295
- `),o.end();return}let u=Ze(d),f=[...l,...r.args].map(Ze),p;try{p=Uk(u,f,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){o.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
296
- `),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{Pi.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
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}
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}
297
299
  `,{encoding:"utf8",mode:384})}catch(h){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
298
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}
299
- `)}),p.on("exit",(h,m)=>{try{Pi.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${m??"null"}
300
- `),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 b of y)b();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let v=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof v=="object"){e.failureReason=v.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${v.tripped}
301
- `);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 au(t){try{return process.kill(t,0),!0}catch{return!1}}function zo(t,e){return t.code=e,t}he();var Wk={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},gd=class extends Ei{constructor(e,n,s={}){super(e,Wk,n,s)}};he();var zk={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},yd=class extends Ei{connected=new Map;constructor(e,n,s={}){super(e,zk,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 wd=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();ui();he();import*as Jo from"fs/promises";import*as bd from"path";var Ko=t=>{process.stderr.write(t+`
302
- `)};function du(t){Ko=t??(e=>process.stderr.write(e+`
303
- `))}async function bm(t,e){let n=Bn();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=bd.join(_.agentsDir(),n),a;try{a=await Jo.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;Ko(`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=bd.join(o,d),p;try{p=await Jo.readdir(f,{withFileTypes:!0})}catch(h){Ko(`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=bd.join(f,m);try{await Jo.rm(y,{recursive:!0,force:!0}),Ko(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(v){Ko(`hydra-acp: prune: failed to remove ${y}: ${v.message}`)}}}}function vm(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 bl(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 cu(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 ${Kk(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 Sm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await cu({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 Kk(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`}Zt();Yo();he();yr();import*as xm from"path";import{createHash as Yk,randomBytes as Vk,timingSafeEqual as Qk}from"crypto";var Cm="hydra_session_",Gk=3600*24*30,km=12,Xk=32,Zk=50;function eI(){return xm.join(_.home(),"session-tokens.json")}function Im(t){return Yk("sha256").update(t).digest("hex")}function Am(t){return Vk(t).toString("hex")}function tI(){return Am(km).slice(0,km*2)}function nI(){return`${Cm}${Am(Xk)}`}var vd=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=eI(),s=await hn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(sI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=nI(),s=Im(n),r=tI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Gk,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(Cm))return;let n=Im(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||!Qk(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(()=>{})},Zk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Qt(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 sI(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")}ds();var Rm="Bearer ",Sd=class{constructor(e){this.token=e}token;async validate(e){return rI(e,this.token)?"service":void 0}},kd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Id=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 Tm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Rm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Rm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Em(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 xd=class{tokens=new Map;mint(e,n){let s=ai();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 rI(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 Cd=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();Ye();fu();Rr();Td();import*as gu from"fs";import*as Go from"os";import*as Ym from"path";import*as yu from"readline";Ds();Hn();function Ed(t){let e=_I(t),n=$I(e),s=[];FI(s,t),OI(s,e,n);let r=s.join(`
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
+ `),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(`
304
306
  `);return r.endsWith(`
305
307
  `)||(r+=`
306
- `),r}function _I(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=qn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function $I(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 FI(t,e){let n=e.session,s=rt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Er(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?`${hu(a.size)}`:void 0;c.push(d?`${hu(a.used)} / ${d} tokens`:`${hu(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(`
307
- `)),t.push("")}function OI(t,e,n){if(!e.some(d=>LI(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
- `))t.push(`> ${Er(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(`
309
- `);for(let u of l)t.push(`> _${Er(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(`- ${NI(l.status)} ${BI(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} ${Er(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Er(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Er(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function LI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function BI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Er(t.title)}${n}`}function NI(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 Er(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function hu(t){return t.toLocaleString("en-US")}Rt();Zt();Co();Ds();function DI(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=>HI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function HI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Hm(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:Hm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Hm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function UI(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var jI=5,qI=200,Um=30;async function Wm(t,e,n={}){let s=DI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??jI,i=n.maxSessions??qI,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=WI(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 WI(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=zI(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 zI(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=KI(a).filter(d=>UI(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:GI(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 KI(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=Pd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ct(s.text):Pd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(VI(s))return[];let i=Pd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=QI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return JI(s);default:return[]}}function JI(t){let e=jm(t,"name"),n=jm(t,"title"),s=[];if(n!==void 0){let a=Ae(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=Ae(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=qm(r);if(a.length>0){let c={kind:"tool-input",text:Ae(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=qm(i);if(a.length>0){let c={kind:"tool-input",text:Ae(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=YI(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function YI(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=Ae(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=Ae(s);if(r.length>0)return r}}return null}function VI(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 Pd(t){if(typeof t=="string")return ct(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?ct(e.text):""}function QI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Pd(n);s.length>0&&e.push(s)}return e.join("")}function jm(t,e){let n=t[e];return typeof n=="string"?n:void 0}function qm(t){try{return JSON.stringify(t)}catch{return""}}function GI(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-Um),c=Math.min(s.length,o+i.length+Um),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Km}from"crypto";function zm(t){let e=Km(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 mu(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(zm({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(zm({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=$i(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function $i(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=Km(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 Md=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Jm(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!wr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Vm(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 Wm(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=Ze(u.cwd??n.cwd),p=u.agentId??n.agentId,h=$i(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 cu({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=>Ym.join(Go.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(v){return l.code(409).send({error:v.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),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":nm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=Uo({record:m.record,history:h==="summary"?sm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:pe,machine:Go.hostname(),hydraHost:Jm(n)}),v=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${v}.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(b=>b.trim()).filter(b=>b.length>0)):void 0,v=Mi(p.history);y&&(v=v.filter(b=>y.has(b.path))),m&&(v=v.map(b=>({...b,hunks:_i(b.hunks)}))),l.code(200).send(v)}),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=Uo({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:pe,machine:Go.hostname(),hydraHost:Jm(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Ed(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=Ze(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=En(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),v=!1,b,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&n.compaction){let T=h??0,$=x.length,j=x.slice(T).reduce((D,Z)=>D+JSON.stringify(Z.params).length,0);b=uu(j);let K=p?.currentModel,H=x.at(-1).recordedAt,L=p?.currentUsage;v=Pm({summarizedThroughEntry:T,totalEntries:$,unsummarizedChars:j,compactionInFlight:e.getCompactionInFlight(),currentModel:K,lastActivityMs:H,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:v,...b!=null?{approxTokens:b}:{},...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,v,b=!1,S=1e4,x=[];if(m){p&&(v=m.onBroadcast($=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify($)+`
310
- `):(x.push($),x.length>S&&x.shift()))})),d.raw.on("close",()=>{v?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch($){throw v?.(),$}}else{let $=await e.getHistory(h);if($===void 0)return l.code(404).send({error:"session not found"}),l;y=$}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 $ of y??[]){l.raw.write(JSON.stringify($)+`
311
- `);let F=$;typeof F.recordedAt=="number"&&T.add(String(F.recordedAt))}for(;x.length>0;){let $=x.splice(0,x.length);for(let F of $){let j=F,K=typeof j.recordedAt=="number"?String(j.recordedAt):"";K&&T.has(K)||l.raw.write(JSON.stringify(F)+`
312
- `)}}return b=!0,v||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 v=m.update.sessionUpdate;return typeof v!="string"||!l.has(v)?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=yu.createInterface({input:gu.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(!Md.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...Md].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}),v=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 b=[];for(let S of v)try{let x=_.historyFile(S.sessionId),T=await a(S.sessionId,x,h,m);T.exhausted||b.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of b)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;b.length>0;){let S=-1,x=1/0;for(let $=0;$<b.length;$++){let F=b[$];F.current!==null&&F.current.ts<x&&(x=F.current.ts,S=$)}if(S===-1)break;let T=b[S];if(l.raw.write(JSON.stringify(T.current.row)+`
313
- `),await c(T),T.exhausted){try{T.rl.close()}catch{}b.splice(S,1)}}}catch(S){for(let x of b)try{x.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($=>$.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let $ of y)if(!Md.has($))return l.code(400).send({error:`kind "${$}" is not queryable; allowed kinds: ${[...Md].join(", ")}`}),l;let v=new Set(y),b;if(f.since!==void 0&&f.since.trim().length>0){let $=new Date(f.since);if(isNaN($.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;b=$.getTime()}let S=_.historyFile(p),x=gu.createReadStream(S),T=yu.createInterface({input:x,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let $ of T){let F=typeof $=="string"?$.trim():"";if(F.length===0)continue;let j;try{j=JSON.parse(F)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!j||typeof j!="object"||Array.isArray(j)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let K=j;if(typeof K.recordedAt!="number"||typeof K.params!="object"||K.params===null||Array.isArray(K.params))continue;let H=K.params;if(typeof H.update!="object"||H.update===null||Array.isArray(H.update))continue;let L=H.update,D=L.sessionUpdate;if(typeof D!="string"||!v.has(D)||b!==void 0&&K.recordedAt<b)continue;let Z={ts:new Date(K.recordedAt).toISOString(),kind:D,update:L};L.messageId!==void 0&&L.messageId!==null&&(Z.messageId=L.messageId),l.raw.write(JSON.stringify(Z)+`
314
- `)}}catch($){if($.code==="ENOENT")return l.raw.end(),l;throw $}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 v of y)v.source===u.source&&p.push({...v,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 v=e.get(f);if(v){if(m.length>0&&y.length>0)v.clearAttentionFlag(m,y);else{let $=Array.from(v.listAttentionFlags()).map(F=>`${F.source}::${F.reason}`);for(let F of $)v.clearAttentionFlag(F.split("::")[0],F.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let b=e.store,S=await b.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let $=`${m}::${y}`;T=x.filter(F=>`${F.source}::${F.reason}`!==$)}else T=[];if(T.length===x.length&&T.every(($,F)=>$.source===x[F].source&&$.reason===x[F].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:T}),l.code(204).send()})}Rt();function Qm(t,e,n,s={}){t.get("/v1/agents",async()=>mi(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 mn(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 Gm(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var XI=/^[A-Za-z0-9._-]+$/;function _d(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=ZI(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){Xo(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){Xo(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){Xo(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){Xo(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){Xo(o,c)}})}function Xo(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 ZI(t){let e=t.name;if(typeof e!="string"||!XI.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 Xm(t,e){_d(t,"extension",e)}function Zm(t,e){_d(t,"transformer",e)}function eg(t,e){t.get("/v1/config",async()=>e)}import{z as Fi}from"zod";he();import*as Hs from"fs/promises";import*as rg from"path";import{randomBytes as ex,scrypt as tx,timingSafeEqual as nx}from"crypto";import{promisify as sx}from"util";var ig=sx(tx);function wu(){return rg.join(_.home(),"password-hash")}var tg=32768,ng=8,sg=1,rx=64,ix=16,og=128*1024*1024;async function ag(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=ex(ix),n=await ig(t,e,rx,{N:tg,r:ng,p:sg,maxmem:og}),s=`scrypt$${tg}$${ng}$${sg}$${e.toString("hex")}$${n.toString("hex")}
315
- `;await Hs.mkdir(_.home(),{recursive:!0}),await Hs.writeFile(wu(),s,{encoding:"utf8",mode:384})}async function $d(){try{return(await Hs.readFile(wu(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Fd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Hs.readFile(wu(),"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 ig(t,o,a.length,{N:s,r,p:i,maxmem:og});return c.length!==a.length?!1:nx(c,a)}var ox=Fi.object({password:Fi.string().min(1),label:Fi.string().min(1).max(256).optional(),ttlSec:Fi.number().int().positive().optional()}),ax=Fi.object({id:Fi.string().optional()}).optional();function dg(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=dx(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=ox.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await $d())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Fd(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=ax.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 dx(t){return t.ip||"unknown"}Ir();Oi();import{nanoid as Iu}from"nanoid";ed();Rt();Zt();import{randomBytes as lg}from"crypto";import*as ug from"os";import*as fg from"path";function ce(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function px(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 en(t,e,n){let s=t.get(e);if(!s)throw ce(z.SessionNotFound,n??`session ${e} not found`);return s}async function bu(t,e){let n=$i(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=lg(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=mu({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 Sx(d,t),d}function pg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Em({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=Wn(n),a=new qt(o),c={clientId:`hydra_client_${Iu(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 ce(z.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Zp.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)),vx()}),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 v={verb:y.verb};return typeof y.argsHint=="string"&&(v.argsHint=y.argsHint),typeof y.description=="string"&&(v.description=y.description),v}).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 v=y;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let b={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(b.outputSchema=v.outputSchema),b}).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 ce(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw ce(-32602,"emit_message requires method");let v=en(e.manager,p),b=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(b)return v.dischargeClaim(b,m),{ok:!0};if(y==="chain")return{ok:!0,response:await v.emitToChain(i.name,h,m)};if(y==="daemon")return{ok:!0,response:await v.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw ce(-32602,"client_broadcast requires an envelope object");return v.broadcastClientUpdate(m),{ok:!0}}throw ce(-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 ce(-32602,"hydra-acp/session/request_permission requires sessionId");return en(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>gx(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,v=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,b=v&&typeof v.title=="string"?v.title:void 0,S=v&&typeof v.model=="string"?v.model:void 0;if(!h&&m){let $=e.manager.get(m);$&&(h=$.cwd)}if(!h)throw ce(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:h,parentSessionId:m,interactive:x,transformChain:[],title:b,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw ce(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 ce(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}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw ce(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 ce(-32602,"await_child requires childSessionId");let y=en(e.manager,p,`child session ${p} not found`);return new Promise(v=>{let x=[],T=[],$=0,F=!1,j,K,H=!1,L=()=>{H||(H=!0,clearTimeout(D),j?.(),K?.(),v(F?{entries:x,truncated:!0}:{entries:x}))};j=y.onBroadcast(Z=>{let G=px(Z);for(x.push(Z),T.push(G),$+=G;x.length>0&&(x.length>1e3||$>1048576);)x.shift(),$-=T.shift()??0,F=!0;h==="turn_complete"&&Z.params?.update?.sessionUpdate==="turn_complete"&&L()});let D=setTimeout(L,m);typeof D.unref=="function"&&D.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 ce(-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=>yx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>wx(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 ce(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 ce(z.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>hx(u,e)),a.onRequest("session/new",async u=>{let f=eh.parse(u),p=Xt(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(D=>typeof D=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,v,b=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=lg(32).toString("hex"),v=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}`}]};b=[...f.mcpServers??[],Z]}let S,x,T=$i(e);T!==void 0&&(b=[...b??[],...T.descriptors]);let $=mu({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),F;try{F=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:b,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:cg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...$?{mintMcpServersForSwap:$}:{}})}catch(D){throw v!==void 0&&v.abandon(D instanceof Error?D:void 0),x!==void 0&&x.abandon(D instanceof Error?D:void 0),T!==void 0&&T.abandon(D instanceof Error?D:void 0),D}if(y!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let D=y,Z=e.mcpTokenRegistry;v.complete(F),F.onClose(()=>{Z.unbind(D)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let D=S,Z=e.mcpTokenRegistry;x.complete(F),F.onClose(()=>{Z.unbind(D)})}T!==void 0&&T.bindToSession(F);let j,K;try{j=Od(a,F,c),{entries:K}=await F.attach(j,"full")}catch(D){throw await F.close({deleteRecord:!1}).catch(()=>{}),D}c.attached.set(F.sessionId,{sessionId:F.sessionId,clientId:j.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let D of K){if(a.isClosed())break;await a.notify(D.method,D.params).catch(()=>{})}})()});let H=vu(F),L=Su(F);return{sessionId:F.sessionId,...H?{modes:H}:{},...L?{models:L}:{},configOptions:F.buildConfigOptions(),_meta:ku(e.manager,F,{clientId:j.clientId})}}),a.onRequest("session/attach",async u=>{let f=nh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=Xt(f._meta),m=h.resume,y=h.readonly===!0,v=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let b=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(b);if(!S&&y){let L=await e.manager.loadFromDisk(b);if(!L)throw ce(z.SessionNotFound,`session ${f.sessionId} not found`);let D=await e.manager.loadHistory(b),Z=f.clientId??`cli_${Iu(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=${D.length}`);for(let G of D)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:Z,connectedClients:[Z],historyPolicy:"full",replayed:D.length,_meta:bx(L)}}let x=!S;if(!S){let L=await e.manager.loadFromDisk(b),D=L;if(m&&(D={...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}:{}}),!D)throw ce(z.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(D.agentId,D.upstreamSessionId))throw ce(z.SessionNotFound,`session ${f.sessionId} was deleted`);let Z=D.originatingClient?D:{...D,originatingClient:c.clientInfo},G=v!==void 0?{...Z,forwardedEnv:v}:Z;S=await bu(e,{...G,onInstallProgress:cg(a)})}let T=Od(a,S,c,f.clientInfo,f.clientId),$=h.replayMode==="drip",{entries:F,appliedPolicy:j}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:$,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),v!==void 0&&await e.manager.setForwardedEnv(S.sessionId,v).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${j} replayed=${F.length} readonly=${y}${$?" replayMode=drip":""}`),$){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,D=750;(async()=>{let Z=null;for(let G of F){let be=typeof G.recordedAt=="number"?G.recordedAt:null;if(Z!==null&&be!==null){let X=Math.min(D,Math.max(0,(be-Z)/L));X>0&&await new Promise(de=>setTimeout(de,X))}be!==null&&(Z=be);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let L=0;L<F.length&&!a.isClosed();L++){let D=F[L],Z=a.notify(D.method,D.params).catch(()=>{});(L+1)%200===0&&await Z}S.replayPendingPermissions(T);let K=vu(S),H=Su(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:j,replayed:F.length,...K?{modes:K}:{},...H?{models:H}:{},configOptions:S.buildConfigOptions(),_meta:ku(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=sh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw ce(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:{[At]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=rh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Cr).map(ih)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw ce(z.InternalError,"agent registry unavailable");return mi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw ce(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=oh.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(",")}]`),ce(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 ce(z.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await bu(e,m);let y=Od(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=Ya.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=Ya.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=dh.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),en(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Ya.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),en(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=ch.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),en(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=lh.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw ce(z.SessionNotFound,"not attached to session");return en(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 ce(z.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let x=await e.manager.loadFromDisk(h);if(!x)throw ce(z.SessionNotFound,`session ${p} not found in memory or on disk`);m=await bu(e,x)}let y=Od(a,m,c),{entries:v}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of v){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let b=vu(m),S=Su(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:ku(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=mx(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),ce(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 ce(z.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw ce(z.InvalidParams,"session/set_mode requires string modeId");let h=en(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=v=>ce(z.InvalidParams,v),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=en(e.manager,f.sessionId),y=m.buildConfigOptions().find(v=>v.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(v=>v.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 ce(z.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw ce(z.MethodNotFound,`Method not found: ${f}`);return d(y,f),en(e.manager,y).forwardRequest(f,u)})})}async function hx(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw ce(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 ce(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,x)=>{if(!Array.isArray(S))throw ce(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw ce(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} 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&&fg.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,x=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...x]}let v={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(v[S]=x);Object.assign(v,h.env);let b=ug.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:v,cwd:b}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Ls(p,a)}}function cg(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(Va,n).catch(()=>{})}}function vu(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 Su(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 mx(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=vi(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 gx(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw ce(z.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw ce(z.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw ce(z.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return en(n.manager,r).addTransformer(i),{ok:!0}}async function yx(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 ce(z.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw ce(z.InvalidParams,"hydra-acp/attention/set requires string reason");return en(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function wx(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 ce(z.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw ce(z.InvalidParams,"hydra-acp/attention/clear requires string reason");return en(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function bx(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{[At]:Ka(e,n)}}function ku(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 Po(e.agentMeta,Ka(s,r))}function vx(){return{protocolVersion:1,agentInfo:{name:"hydra",version:pe},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:Po(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Sx(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 Od(t,e,n,s,r){return{clientId:r??`cli_${Iu(8)}`,connection:t,clientInfo:s}}var Ld=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 kx}from"crypto";import{McpServer as Ix}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as xx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Tt}from"zod";function*xu(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 tn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var hg="Bearer ";function Li(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(hg))return;let n=e.slice(hg.length).trim();return n.length>0?n:void 0}function Cx(t){let e=new Ix({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:Tt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return tn(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:Tt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return tn(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:Tt.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:Tt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Tt.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 tn(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:Tt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Tt.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 tn({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:Tt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Tt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Tt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Tt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Tt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Tt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Tt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Tt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Tt.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 tn(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 tn(n)}),e}var Ax=1e4;function mg(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=Cx(a),l=new xx({sessionIdGenerator:()=>kx()});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=Li(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),Ax)}),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)})}td();import{randomUUID as Rx}from"crypto";import{McpServer as Tx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ex}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Us}from"zod";function Px(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Mx(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 _x(t){let e=new Tx({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:Us.string().min(1).describe("Case-insensitive substring to search for."),limit:Us.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Us.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 tn({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 xu(o)){if(u==="tool_call"&&!r)continue;let f=Si([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=Px(u),m=Mx(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 tn({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:Us.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Us.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 tn({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=Si(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:Us.string().optional(),file_path:Us.string().optional(),limit:Us.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 tn({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 xu(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let v=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,b=l.get(v);b||(b={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(v,b),d.push(v)),typeof y.name=="string"&&y.name.length>0?b.toolName=y.name:(b.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(b.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))b.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!b.locations.includes(T)&&b.locations.push(T)}typeof y.status=="string"&&(b.status=y.status),h.recordedAt!==void 0&&b.timestamp===void 0&&(b.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(),v=["file_path","filePath","path"],b=!1;for(let S of v){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){b=!0;break}}if(!b){for(let S of h.locations)if(S.toLowerCase().includes(y)){b=!0;break}}if(!b)continue}let m={};for(let[y,v]of Object.entries(h.rawInput))typeof v=="string"?m[y]=v.length>500?v.slice(0,497)+"\u2026":v:(typeof v=="number"||typeof v=="boolean")&&(m[y]=v);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 tn({calls:u,truncated:f})}),e}var $x=1e4;function gg(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=_x(a),l=new Ex({sessionIdGenerator:()=>Rx()});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=Li(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),$x)}),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 Bd=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 Ux}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as jx}from"crypto";import{Server as Fx}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Ox,ListToolsRequestSchema as Lx}from"@modelcontextprotocol/sdk/types.js";function yg(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new Fx({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(Lx,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(Ox,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Nd(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=Nx(d,a.sendNotification);try{let u=await s(),f=await Dx(e.connection,t,c,o.params.arguments??{},u);return Hx(f,c)}catch(u){return Nd(u instanceof Error?u.message:String(u))}finally{l()}}),r}var Bx=15e3;function Nx(t,e,n=Bx){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 Dx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function Hx(t,e){if(t===null||typeof t!="object")return Nd(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Nd(`extension ${e} omitted content array`)}function Nd(t){return{content:[{type:"text",text:t}],isError:!0}}var qx=1e4;function wg(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 v=s.get(d);if(v!==void 0){s.delete(d);for(let b of v.values())await r(b)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=yg(l,p,async()=>{let v=e.lookup(d);if(v===void 0)throw new Error("mcp token no longer bound");if(v.session!==void 0)return v.session.sessionId;let b,S=new Promise(T=>{b=setTimeout(()=>T(void 0),qx)}),x=await Promise.race([v.sessionReady.catch(()=>{}),S]);if(b!==void 0&&clearTimeout(b),x===void 0)throw new Error("session not ready");return x.sessionId}),y=new Ux({sessionIdGenerator:()=>jx()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Li(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 Ig(t,e){Vx(t);let n=t.daemon.tls?await Bi.readFile(Ze(t.daemon.tls.key)):void 0,s=t.daemon.tls?await Bi.readFile(Ze(t.daemon.tls.cert)):void 0;await Bi.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await Jx(t.daemon.logLevel),o=Wx({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(zx,{options:{handleProtocols:Fp}}),hl(Y=>{o.log.info(Y)}),yl(Y=>{o.log.info(Y)});let a=await vd.load(),c=new Cd,d=new xd,l=new Id([new Sd(e),new kd(a),d]),u=Tm({validator:l});o.addHook("onRequest",async(Y,Se)=>{Y.routeOptions.config?.skipAuth||Y.url==="/acp"||Y.url?.startsWith("/acp?")||await u(Y,Se)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new qa(t,{onFetched:()=>{bm(h,b)}});du(Y=>o.log.info(Y));let m={info:Y=>o.log.info(Y),warn:Y=>o.log.warn(Y)},y=Y=>Os.spawn({...Y,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Np(t.compressToolContent);let v=new wd,b=new fd(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:v,defaultCwd:t.defaultCwd}),S=new gd(op(t),void 0,{tokenRegistry:d}),x=new yd(ap(t),void 0,{tokenRegistry:d});Gm(o,pe,Ns(t));let T=new Ld,$=new Bd,F,j=()=>{if(F!==void 0)return F;let Y=o.server.address();return F=`http://127.0.0.1:${Y&&typeof Y=="object"?Y.port:t.daemon.port}`,F};Vm(o,b,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:$,mcpTokenRegistry:T,getDaemonOrigin:j}),Qm(o,h,b,{npmRegistry:t.npmRegistry}),Xm(o,S),Zm(o,x),eg(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]}),dg(o,{store:a,rateLimiter:c}),mg(o,T),gg(o,T),wg(o,T,$),pg(o,{validator:l,manager:b,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Y,Se)=>S.reportVersion(Y,Se),onTransformerVersion:(Y,Se)=>x.reportVersion(Y,Se),transformers:x,extensionCommands:v,mcpTokenRegistry:T,extensionMcp:$,getDaemonOrigin:j,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 H=o.server.address(),L=H&&typeof H=="object"?H.port:t.daemon.port,D,Z=t.daemon.host,G=L;if(K&&n&&s){D=Yx({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=D.address();Y&&typeof Y=="object"&&(G=Y.port)}await Bi.mkdir(_.home(),{recursive:!0}),await mp({pid:process.pid,host:Z,port:G,loopbackPort:L,startedAt:new Date().toISOString()});let be={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(be),x.setContext(be),await S.start(),await x.start();try{await b.reconcilePermissionFlags()}catch(Y){o.log.warn(`permission flag reconcile failed: ${Y.message}`)}b.resurrectPendingQueues().catch(Y=>{o.log.warn(`queue replay scan failed: ${Y.message}`)}),b.resumePendingCompactions().catch(Y=>{o.log.warn(`compaction resume scan failed: ${Y.message}`)});let X=t.daemon.agentSyncIntervalMinutes*60*1e3,de=X>0?vm({registry:h,manager:b,intervalMs:X,logger:m}):void 0,Ke=t.daemon.sessionGcIntervalMinutes*60*1e3,Xs=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,ws=Ke>0?Sm({manager:b,intervalMs:Ke,maxAgeMs:Xs,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:$,processRegistry:d,shutdown:async()=>{ws&&ws(),de&&de(),clearInterval(f),clearInterval(p);let Y=async(Se,Qn)=>{try{await Qn()}catch(ye){o.log.warn(`shutdown step ${Se} failed: ${ye instanceof Error?ye.message:String(ye)}`)}};await Y("sessionTokenStore.flush",()=>a.flush()),await Y("extensions.stop",()=>S.stop()),await Y("transformers.stop",()=>x.stop()),await Y("manager.closeAll",()=>b.closeAll()),await Y("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await Y("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await Y("manager.flushMetaWrites",()=>b.flushMetaWrites()),await Y("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),hl(null),yl(null),du(null),D&&await Y("tlsTerminator.close",()=>new Promise(Se=>D.close(()=>Se()))),await Y("app.close",()=>o.close());try{vg.unlinkSync(_.pidFile())}catch{}await Y("fileStream.flushSync",()=>i.flushSync())}}}async function Jx(t){let e=await Kx({file:_.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=bg.destination(2);return{stream:bg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function Yx(t){let e=kg.createServer(t.tlsOptions,n=>{let s=Sg.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 Vx(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.`)}Mr();Zt();Yo();Zo();async function Rg(t={}){let e=await we(),n=await Io();if(await Dd(e)){let r=await Hi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
316
- `);return}if(ii(t,"foreground")){process.title="hydra-daemon";let r=await Ig(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
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(`
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}
317
319
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
318
320
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
319
321
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
320
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)}
321
- `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Hd(),await Ud(e);let s=await Hi();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
322
- `)}async function Tg(){let t=await Hi();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}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
325
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
324
326
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
325
- `)}}async function Eg(){let t=await we();await Io();let e=await Hi();if(e&&Tn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
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}...
326
328
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
327
- `),process.exit(1)}await nC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
329
+ `),process.exit(1)}await uA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
328
330
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
329
- `);if(Hd(),await Ud(t),await Dd(t)){let n=await Hi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
330
- `)}}async function nC(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Tn(t))return!0;await tC(50)}return!1}async function Pg(t){await Di(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Mg(){let t=await Hi();if(!t){process.stdout.write(`Daemon: not running
331
- `),process.stdout.write(`CLI version: ${pe}
332
- `);return}let e=Tn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
333
- `);let n,s;if(e)try{let o=await we();n=await Pr(o),s=Ns(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${pe}
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
333
+ `),process.stdout.write(`CLI version: ${fe}
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}
334
336
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
335
- `);return}let r=n.version===pe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${pe}
336
- `);return}process.stdout.write(`CLI version: ${pe}
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
+ `);return}process.stdout.write(`CLI version: ${fe}
337
339
  `),process.stdout.write(`Daemon version: ${n.version}
338
- `),r||process.stdout.write(Ag.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Ag.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function Hi(){return ls()}Ye();ds();qs();Sr();Co();Hn();ta();Rr();import*as yn from"fs/promises";import*as Wg from"os";import*as wn from"path";Qd();async function zg(t={}){let e=await we(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Me(`/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(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)+`
339
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.
340
342
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
341
343
  `);return}process.stdout.write(`No active sessions.
342
- `);return}let c=a.slice().sort((y,v)=>{let b=(v.status==="warm"?1:0)-(y.status==="warm"?1:0);return b!==0?b:String(v.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(x=>x.status!=="cold").length,v=e.sessionListColdLimit,b=c.slice(y,y+v),S=c.length-y-b.length;d=[...c.slice(0,y),...b],l=S}let u=Date.now(),f=d.map(y=>Ki(y,u)),p={columns:t.columns??e.tui.sessionColumns??Wi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Ji(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ws(zi,h,m,p)+`
343
- `);for(let y of f)process.stdout.write(Ws(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=>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
346
  `);l>0&&process.stdout.write(`
345
347
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
346
- `)}async function Kg(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
347
- `),process.exit(2));let e=await Me(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
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
350
  `),process.exit(1)),process.stdout.write(`Killed ${t}
349
- `)}async function Jg(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
350
- `),process.exit(2));let e=await Me(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
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
353
  `),process.exit(1)),process.stdout.write(`Removed ${t}
352
- `)}async function Yg(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 Me("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
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)}
353
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.
354
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${ji(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
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}.
355
357
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
356
358
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
357
- `)}async function Vg(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
358
- `),process.exit(2));let s=await gr(),r=await Ui(),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 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
361
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
360
362
  `)||process.stdout.write(`
361
- `);return}let c=e==="."?vC(o,t):e;await yn.mkdir(wn.dirname(wn.resolve(c)),{recursive:!0}),await yn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
362
- `)}async function Qg(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
363
- `),process.exit(2));let n,s,r=await mC(t);if(r!==null){let o=gC(r.raw);n=Ed(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${wn.basename(t,wn.extname(t))}-${a}.md`}else{let o=await gr(),a=await Ui(),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==="."?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}
364
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(`
365
367
  `)||process.stdout.write(`
366
- `);return}let i=e==="."?s:e;await yn.mkdir(wn.dirname(wn.resolve(i)),{recursive:!0}),await yn.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
367
- `)}async function mC(t){try{if(!(await yn.stat(t)).isFile())return null}catch{return null}let e=await yn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
368
- `),process.exit(1)}}function gC(t){try{return En(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
369
- `),process.exit(1)}}async function Gg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
370
- `),process.exit(2));let n;if(e.cwd!==void 0){let a=wn.resolve(e.cwd);try{(await yn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
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]
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
371
373
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
372
- `),process.exit(1)}n=a}let s;t==="-"?s=await bC():s=await yn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
373
- `),process.exit(1)}if(e.info===!0){let a=await we();wC(r,a.tui.cwdColumnMaxWidth);return}let i=await Me("/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 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
376
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
375
377
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
376
378
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
377
- `)}function yC(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 wC(t,e){let n;try{n=En(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
378
- `),process.exit(1)}let s=yC(n),r=Ki(s),i={columns:Vd,cwdMaxWidth:e},o=Ji([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ws(zi,o,a,i)+`
379
- `),process.stdout.write(Ws(r,o,a,i)+`
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)+`
380
382
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
381
383
  lineage: ${n.session.lineageId}
382
384
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -384,75 +386,75 @@ origin session: ${n.session.sessionId}
384
386
  origin upstream: ${c}
385
387
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
386
388
  `:`
387
- `))}async function bC(){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 vC(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 Xg(t,e={}){let n=await we(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await jt(n),l=e.cwd?wn.resolve(e.cwd):process.cwd(),u=await zn(d,{cwd:l,all:!0}),f=Jd(u,l);f||(process.stderr.write(`No sessions found for ${l}.
388
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=SC(e.host,n),a=rt(s),c=fp({host:r,port:i,sessionId:a});process.stdout.write(c+`
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
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.
390
- `)}function SC(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=qg(t,Rn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=qg(e.daemon.publicHost,Rn);return{host:n,port:s,isFallback:!1}}return kC(e.daemon.host)?{host:IC(),port:e.daemon.port,isFallback:!1}:wr(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 kC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function IC(){let t=Wg.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function qg(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}}qu();Qd();Du();Ye();he();Zo();qs();var iA={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function nc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Gi(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function sc(t){let e=iA[t],n=`/v1/${e.plural}`;async function s(){let u=(await Me(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
391
- `);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:Gi(p.name,f.map(y=>y.name)),status:Gi(p.status,f.map(y=>y.status)),version:Gi(p.version,f.map(y=>y.version)),pid:Gi(p.pid,f.map(y=>y.pid)),restarts:Gi(p.restarts,f.map(y=>y.restarts)),started:Gi(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 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
394
  `);for(let y of f)process.stdout.write(m(y)+`
393
395
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
394
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]
395
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._-]+
396
- `),process.exit(2);return}await we();let u=await qi(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${hy(e.singular)} '${d}' already exists in config.
397
- `),process.exit(1);return}let h=Wd(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 Au(u),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
398
- `);let v={name:d,...y};try{let b=await Me(n,{method:"POST",body:v,rethrowNetworkError:!0});if(b.ok){let S=b.body,x=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${x}
399
- `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${b.status}${nc(b.body)}). Restart the daemon to apply.
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}
401
+ `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${lc(v.body)}). Restart the daemon to apply.
400
402
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
401
- `),process.exit(2);return}await we();let l=await qi(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${hy(e.singular)} '${d}' not found in config.
402
- `),process.exit(1);return}delete f[d],u[e.plural]=f,await Au(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
403
- `);try{let p=await Me(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
404
- `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${nc(p.body)}).
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
406
+ `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${lc(p.body)}).
405
407
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
406
408
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
407
- `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Me(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${nc(u.body)}
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)}
408
410
  `),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${d}: ${f.status}${p}
409
- `)}async function a(d){let p=((await Me(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}.
410
- `);return}let h=0;for(let m of p)try{let y=await Me(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${nc(y.body)}
411
- `),h+=1;continue}let v=y.body,b=v.pid!=null?` pid=${v.pid}`:"";process.stdout.write(`${m.name}: ${v.status}${b}
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)}
413
+ `),h+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${m.name}: ${b.status}${v}
412
414
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
413
- `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=jd(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
414
- `),process.exit(2);return}let f=e.logFile(l);await Di(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 hy(t){return t.charAt(0).toUpperCase()+t.slice(1)}var $r=sc("extension"),my=$r.list,gy=$r.add,yy=$r.remove,wy=$r.start,by=$r.stop,vy=$r.restart,Sy=$r.logs;var Fr=sc("transformer"),ky=Fr.list,Iy=Fr.add,xy=Fr.remove,Cy=Fr.start,Ay=Fr.stop,Ry=Fr.restart,Ty=Fr.logs;ef();ea();Oi();Ir();Ye();Sr();Mr();Rt();Zt();za();rf();import kA from"os";import{spawn as IA}from"child_process";async function xA({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 CA(c,s),u=await sf(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
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
415
417
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
416
418
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
417
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:kA.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
418
- `),{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 CA(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: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
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:
420
422
  ${s.join(`
421
423
  `)}
422
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}
423
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})
424
- `),process.exit(2)}async function Qy(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
425
- `),process.exit(2));let{resolveAgentIdOrExit:n}=await Promise.resolve().then(()=>(ef(),_y)),s=await n(t,"hydra agent auth"),r=await we(),i=await jt(r);await js(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await _r(i.wsUrl,o),c=Wn(a),d=new qt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:pe}})}catch{}let l;try{l=await xA({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:IA})}finally{a.close()}process.exit(l.exitCode)}Zo();Zc();qs();async function Gy(t){let e=ii(t,"force");if(await $d()&&!e){let r=await li("Current password: ");await Fd(r)||(process.stderr.write(`Wrong password.
426
- `),process.exit(1))}let n=await li("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
427
- `),process.exit(2));let s=await li("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
428
- `),process.exit(1)),await ag(n),process.stdout.write(`Password set.
429
- `)}async function Xy(){let e=(await Me("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
430
- `);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:fc(n.id,s.map(o=>o.id)),label:fc(n.label,s.map(o=>o.label)),createdAt:fc(n.createdAt,s.map(o=>o.createdAt)),expiresAt:fc(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)+`
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.
428
+ `),process.exit(1))}let n=await hi("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
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.
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)+`
431
433
  `);for(let o of s)process.stdout.write(i(o)+`
432
- `)}async function Zy(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
433
- `),process.exit(2));let e=await Me(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
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
436
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
435
437
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
436
- `),process.exit(1)}function fc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Js from"fs";Ye();Sr();Mr();of();Rt();var pc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(df(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(af(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(!af(e)&&!df(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(af(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(!df(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=Xt(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 af(t){return"method"in t&&"id"in t&&t.id!==void 0}function df(t){return!("method"in t)&&"id"in t}mc();Zt();he();Ao();import{writeFileSync as MA}from"fs";var _A=t=>{MA("/proc/self/comm",t)};function ro(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??_A;try{s(e.commName??Ln())}catch{}}function io(t,e=Ln()){return t.length===0?e:`${e} ${t.join(" ")}`}async function yc(t){ro(io(process.argv.slice(2)),{commName:"hydra-shim"});let e=await we(),n=t.target??await jt(e);n.isLocal&&!t.target&&await js(e);let s=new pc,r=Qa(process.stdin,process.stdout),i=n.isLocal?async()=>(await jt(await we())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new so({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await NA(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
437
- `);for(let l of d)await DA(a,l,s.lastMessageId(l.sessionId))}}});$A({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
438
- `),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 $A({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(ow("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&qA(i)){e.send({jsonrpc:"2.0",id:i.id,result:Hr(i.params)});return}FA(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(ow("client\u2192daemon",i),s.observeFromClient(i),UA(i)){e.send(jA(i));return}if(HA(i)){if(t.sessionId){e.send(WA(i,t.sessionId));return}let o=i;t.agentId&&(o=gc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=gc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=gc(o,{title:r.name}),r.used=!0),t.model&&(o=gc(o,{model:t.model})),e.send(o);return}e.send(i)})}function FA(t,e,n){let s=OA(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=BA(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function OA(t){if(!LA(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function LA(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function BA(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function NA(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
439
- `);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 DA(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";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}
440
442
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
441
- `)}}function HA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function UA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function jA(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:pe}}}}function qA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function WA(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var zA=25*1024*1024,iw=!1,Ur=null;function ow(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!iw){iw=!0;try{Ur=_.shimWireLogFile(),Js.mkdirSync(_.home(),{recursive:!0});let n=Js.statSync(Ur,{throwIfNoEntry:!1});n&&n.size>zA&&Js.renameSync(Ur,`${Ur}.1`)}catch{Ur=null}}if(Ur)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
442
- `;Js.appendFile(Ur,n,()=>{})}catch{}}}function gc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Ir();Oi();ea();Ye();Sr();Mr();Ds();Rt();Zt();mc();import{mkdtempSync as nR,rmSync as sR}from"fs";import{tmpdir as rR}from"os";import{join as iR}from"path";function aw(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())}}}Qi();import KA from"chalk";import JA from"strip-ansi";var wc=new KA.Instance({level:3});function dw(t,e){if(t.length===0)return"";let n=Ks(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(YA(i,e));let r=s.join(`
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
445
  `);return r.endsWith(`
444
446
  `)||(r+=`
445
- `),r}function YA(t,e){let n=eR(t.body,e);return e==="ansi"?n=tR(n,t.bodyStyle):n=JA(n),n}var VA="\x1B[1m",QA="\x1B[96m",GA="\x1B[93m",XA="\x1B[0m",ZA="\0";function eR(t,e){let n=t.replace(/\^\^/g,ZA);return e==="ansi"&&(n=n.replace(/\^\+/g,VA).replace(/\^C/g,QA).replace(/\^Y/g,GA).replace(/\^:/g,XA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function tR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return wc.bold.yellowBright(t);case"heading-2":return wc.bold.cyanBright(t);case"heading-3":return wc.bold(t);case"dim":return wc.dim(t);default:return t}}var oR=1*1024*1024,cw="mcp__hydra-acp-stdin__";function lw(t,e){return{sessionId:t,prompt:e,_meta:{[At]:{ancillary:!0}}}}function aR(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 dR(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(cw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(cw))}async function uw(t){if(ro(io(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.
446
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=nR(iR(rR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{sR(c,{recursive:!0,force:!0})}catch{}})}let e=await we(),n=t.target??await jt(e);n.isLocal&&!t.target&&await js(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await _r(n.wsUrl,s),i=Wn(r),o=new qt(i),a=await lR({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:cR(n.baseUrl,n.token)});process.exit(a.exitCode)}function cR(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 lR(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?Hr(X):dR(X)?Hr(X):nw(X));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Cr,version:pe}})}catch{}let u=await pR(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)},v=()=>{if(d||h.length===0)return;let X=dw(h,c);if(h="",X.length===0)return;let de=m>0?`
447
- `:"";y(de+X),m+=1},b=()=>{v(),f&&!p&&y(`
448
- `),f=!1};e.onNotification("session/update",X=>{let de=X?.update,Ke=qn(de,{cwd:n.cwd});if(Ke){if(Ke.kind==="agent-text"){d?y(Ke.text):h+=Ke.text;return}if(Ke.kind==="turn-complete"){b();return}switch(Ke.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":v();return;default:return}}});let S=!1,x=async X=>{let de=[];if(n.prompt&&!S&&de.push({type:"text",text:n.prompt}),X.length>0&&de.push({type:"text",text:X}),de.length!==0){try{await e.request("session/prompt",lw(u,de)),S=!0}catch(Ke){a(`hydra-acp cat: prompt failed: ${Ke.message}
449
- `);return}b()}},T=0,$,F=new Promise(X=>{$=X}),j=!1,K=async X=>{j||(j=!0,b(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Ke=>setTimeout(Ke,500))]),await e.close().catch(()=>{}),$({exitCode:X}))};e.onClose(X=>{X&&(a(`hydra-acp cat: ${X.message}
450
- `),T=1),j||(j=!0,b(),$({exitCode:T}))});let H=[],L=!1,D=!1,Z=async()=>{if(!L){L=!0;try{for(;H.length>0;){let X=H.shift();if(X===void 0)break;await x(X)}}finally{L=!1,D&&H.length===0&&await K(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await K(0),F;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),uR({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{D=!0,!L&&H.length===0&&K(T)},onError:X=>{a(`hydra-acp cat: stdin error: ${X.message}
451
- `),T=1,D=!0,!L&&H.length===0&&K(T)},onPromptFailed:X=>{a(`hydra-acp cat: ${X.message}
452
- `),T=1,D=!0,!L&&H.length===0&&K(T)}}),F;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=aw({scheduleFlushCheck:de=>{let Ke=setImmediate(de);return()=>clearImmediate(Ke)},onChunk:de=>{H.push(de),Z()}});return s.on("data",de=>{X.feed(typeof de=="string"?de:de.toString("utf8"))}),s.on("end",()=>{X.eof(),D=!0,!L&&H.length===0&&K(T)}),s.on("error",de=>{a(`hydra-acp cat: stdin error: ${de.message}
453
- `),T=1,D=!0,!L&&H.length===0&&K(T)}),F}let be="";return s.on("data",X=>{be+=typeof X=="string"?X:X.toString("utf8")}),s.on("end",()=>{D=!0,be.length>0&&H.push(be),Z()}),s.on("error",X=>{a(`hydra-acp cat: stdin error: ${X.message}
454
- `),T=1,D=!0,!L&&H.length===0&&K(T)}),F}function uR(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??oR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let x=b.toString("base64");h=h.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
455
- `)})},y=async()=>{d="inline";let b=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(b)}catch(S){t.onPromptFailed(S);return}t.onEof()},v=async()=>{d="pivoting";let b;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),b=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=fR(r.prompt,b.capacityBytes);e.request("session/prompt",lw(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",b=>{let S=typeof b=="string"?Buffer.from(b,"utf8"):b;if(d==="undecided"){u.push(S),f+=S.length,f>c&&v();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 fR(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:
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?`
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}
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}
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
458
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
457
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.
458
460
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -467,49 +469,50 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
467
469
  User's question:
468
470
  ${t}`:`${s}
469
471
 
470
- 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 pR(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Cr,version:pe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=aR(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={[At]:s});let o=await t.request("session/new",i);return Xt(o._meta),o.sessionId}Ye();he();function bc(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 fw(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 hR(t){try{return JSON.parse(t)}catch{return t}}function pw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function hw(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
471
- `),process.exit(2));let e=bc(t),n=await we(),s=fw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
472
- `),process.exit(1)),process.stdout.write(`${pw(s)}
473
- `)}async function mw(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
474
- `),process.exit(2));let n=bc(t),s=hR(e);try{await cs(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}
475
- `),process.exit(1)}process.stdout.write(`set ${t} = ${pw(s)}
476
- `)}async function gw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
477
- `),process.exit(2));let e=bc(t);try{await cs(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 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}
478
480
  `),process.exit(1)}process.stdout.write(`unset ${t}
479
- `)}async function yw(t){let e=await we(),n=t?fw(e,bc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
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
480
482
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
481
- `)}function ww(){process.stdout.write(`${_.config()}
482
- `)}Ye();ds();Mr();Zt();qs();async function Sw(t={}){let{report:e,configLoaded:n}=await mR();if(t.json){process.stdout.write(JSON.stringify(e,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
485
  `);return}process.stdout.write(`CLI: ${e.cli}
484
486
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
485
- `),e.daemonReachable&&(bw("Extensions",e.extensions),bw("Transformers",e.transformers)))}function bw(t,e){if(process.stdout.write(`
487
+ `),e.daemonReachable&&(Tw("Extensions",e.extensions),Tw("Transformers",e.transformers)))}function Tw(t,e){if(process.stdout.write(`
486
488
  ${t}:
487
489
  `),e.length===0){process.stdout.write(` (none)
488
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}
489
- `)}}async function mR(){let t={cli:pe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await we()}catch{return{report:t,configLoaded:!1}}let n=await Pr(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 gr()}catch{return{report:t,configLoaded:!0}}let r=await Ui(),i={Authorization:`Bearer ${s}`};return t.extensions=await vw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await vw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function vw(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 gR}from"child_process";import{accessSync as yR,constants as wR,statSync as bR}from"fs";import{delimiter as vR,join as SR}from"path";var kR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function IR(t){return kR.has(t)}function xR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function CR(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 AR(t){try{if(!bR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return yR(t,wR.X_OK),!0}catch{return!1}}function RR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(vR).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=SR(o,r+a);if(AR(c))return c}}function TR(t,e){let n=gR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
490
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function kw(t){let e=xR(t);if(e===void 0||IR(e))return!1;let n=RR(e);if(n===void 0)return!1;TR(n,CR(t))}cf();var Gs=!1,Ub=!1;function jb(t){!t||Ub||(Ub=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
491
- `))}async function gT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Eo(),Sp));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let v=e.slice(0,n),b=e.slice(n+1),S=b[0],x=b.slice(1),{flags:T}=Wc(v);if(Wb(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.
492
- `),process.exit(2);return}let $=S??ht(T,"agent");if(!$){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
493
- `),process.exit(2);return}let F=await zb(al(T),{allowPrompt:!1}),j=ht(T,"name"),K=ht(T,"model");Gs=!0;let H=T["dangerously-skip-permissions"]===!0;jb(H);let L={agentId:$,agentArgs:x,name:j,model:K,dangerouslySkipPermissions:H};F?.sessionId!==void 0&&(L.sessionId=F.sessionId),F?.target!==void 0&&F.fromUrl&&(L.target=F.target),await yc(L);return}Wf(e)===void 0&&!e.some(v=>v==="--prompt"||v.startsWith("--prompt="))&&kw(e);let{positional:s,flags:r}=Wc(e);if(Wb(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${yT()}
494
- `);return}if(r.help===!0){Kf();return}let i=Wf(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=ht(r,"name"),d=ht(r,"agent"),l=ht(r,"model"),u=r["dangerously-skip-permissions"]===!0;jb(u);let f=al(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await zb(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.
495
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){Gs=!0,await qb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}Gs=!0;let v={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(v.sessionId=m),y!==void 0&&(v.target=y),await yc(v);return}switch(a){case"shim":{Gs=!0;let v={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(v.sessionId=m),y!==void 0&&(v.target=y),await yc(v);return}case"cat":{let v=Wf(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=v??b,x=ht(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};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let $=zf(r,"stream-threshold");$!==void 0&&(T.streamThreshold=$);let F=zf(r,"stream-bytes");F!==void 0&&(T.streamBufferBytes=F),d!==void 0&&await rc(d),Gs=!0,await uw(T);return}case"version":{Gs=!0,await Sw({json:r.json===!0});return}case"init":await _p(r);return;case"daemon":{let v=e.indexOf("daemon"),b=e.slice(v+1),S=b[0];if(S===void 0||S==="status"){await Mg();return}if(S==="start"){await Rg(r);return}if(S==="stop"){await Tg();return}if(S==="restart"){await Eg();return}if(S==="log"||S==="logs"){await Pg(b.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
496
- `),process.exit(2);return}case"session":case"sessions":{let v=s[1];if(v===void 0||v==="list"){let b=ht(r,"columns"),S;if(b!==void 0)try{S=jg(b)}catch(x){process.stderr.write(`${x.message}
497
- `),process.exit(2);return}await zg({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(v==="info"){await py(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(v==="diff"){await fy(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(v==="kill"){await Kg(s[2]);return}if(v==="remove"){await Jg(s[2]);return}if(v==="collect"){let b=ht(r,"max-age-days"),S=ht(r,"limit"),x={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(b!==void 0){let T=Number(b);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
498
- `),process.exit(2);return}x.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
499
- `),process.exit(2);return}x.limit=T}await Yg(x);return}if(v==="export"){let b=ht(r,"out"),S=ht(r,"tools");await Vg(s[2],b,S);return}if(v==="transcript"){let b=ht(r,"out");await Qg(s[2],b);return}if(v==="import"){let b=ht(r,"cwd");await Gg(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(v==="share"){let b=ht(r,"host"),S=ht(r,"cwd");await Xg(s[2],{...b!==void 0?{host:b}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${v}
500
- `),process.exit(2);return}case"extension":case"extensions":{let v=e.indexOf(a),b=e.slice(v+1),S=b[0],x=b[1],T=b.slice(2);if(S===void 0||S==="list"){await my();return}if(S==="add"){await gy(x,T);return}if(S==="remove"){await yy(x);return}if(S==="start"){await wy(x);return}if(S==="stop"){await by(x);return}if(S==="restart"){await vy(x);return}if(S==="log"||S==="logs"){await Sy(b.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
501
- `),process.exit(2);return}case"transformer":case"transformers":{let v=e.indexOf(a),b=e.slice(v+1),S=b[0],x=b[1],T=b.slice(2);if(S===void 0||S==="list"){await ky();return}if(S==="add"){await Iy(x,T);return}if(S==="remove"){await xy(x);return}if(S==="start"){await Cy(x);return}if(S==="stop"){await Ay(x);return}if(S==="restart"){await Ry(x);return}if(S==="log"||S==="logs"){await Ty(b.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
502
- `),process.exit(2);return}case"agent":case"agents":{let v=s[1];if(v===void 0||v==="list"){await zu();return}if(v==="refresh"){await ic();return}if(v==="install"){await Ju(s[2]);return}if(v==="sync"){await Yu(s[2]);return}if(v==="set"){await Qu(s[2],s[3]);return}if(v==="pin"){await Gu(s[2],s[3]);return}if(v==="add"){let b=e.indexOf(a),S=e.slice(b+1);await Xu(S[1],S.slice(2));return}if(v==="remove"){await Zu(s[2]);return}if(v==="log"||v==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:x,rest:T}=jd(S);await Vu(x,T);return}if(v==="auth"){await Qy(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${v}
503
- `),process.exit(2);return}case"registry":{let v=s[1];if(v==="refresh"){await ic();return}if(v==="pin"){await oc(!0);return}if(v==="unpin"){await oc(!1);return}process.stderr.write(`Unknown registry subcommand: ${v}
504
- `),process.exit(2);return}case"auth":{let v=s[1];if(v==="password"){let b=s[2];if(b===void 0||b==="set"){await Gy(r);return}process.stderr.write(`Unknown auth password action: ${b}
505
- `),process.exit(2);return}if(v===void 0||v==="list"){await Xy();return}if(v==="revoke"){await Zy(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${v}
506
- `),process.exit(2);return}case"config":{let v=s[1];if(v===void 0||v==="list"){await yw(s[2]);return}if(v==="get"){await hw(s[2]);return}if(v==="set"){await mw(s[2],s[3]);return}if(v==="unset"){await gw(s[2]);return}if(v==="path"){ww();return}process.stderr.write(`Unknown config subcommand: ${v}
507
- `),process.exit(2);return}case"tui":Gs=!0,await qb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
508
- `),Kf(),process.exit(2)}}async function qb(t,e){let n=ht(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 rc(e.agentId),ro(io(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Hb(),Db)),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.
509
- `),process.exit(2)),a.drip=!0;let c=zf(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function zf(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 Wb(t){let e=tp(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
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
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}
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}
510
512
 
511
- `),Kf(),process.exit(2))}function Wf(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 zb(t,e){try{return await Tp(t,e)}catch(n){st({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
512
- `),process.exit(1)}}function yT(){try{let t=hT(pT(import.meta.url));return JSON.parse(fT(mT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Kf(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --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."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --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."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," 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)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," 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."," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," 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."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," 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"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," 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"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," 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)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," 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>])."," 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."," 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)."," hydra-acp agent remove <id> Remove a local agent."," 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."," 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`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp agent auth <id> Run the auth flow for <id>"," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"," 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."," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"," hydra-acp config path Print the config file path"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
513
- `))}async function Kb(){if(!Gs)try{let t=await la();t&&process.stderr.write(`\u2728 ${ua(t)}
514
- `)}catch{}}gT().then(Kb).catch(async t=>{st({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
515
- `),await Kb(),process.exit(1)});
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(`
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)});