@hydra-acp/cli 0.1.94 → 0.1.95

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,32 @@
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?`
2
+ var nv=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var zc=(t,e)=>{for(var n in e)nv(t,n,{get:e[n],enumerable:!0})};import*as we from"path";import*as Jc from"os";function Ze(t){let e=Jc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function dv(){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[av];if(t&&t.length>0)return we.resolve(t);let e=dv();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(Jc.homedir(),".hydra-acp")}var av,_,he=J(()=>{"use strict";av="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 ai from"fs/promises";function di(){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 ci(){try{let e=(await ai.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function yr(){let t=await ci();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function li(t){await ai.mkdir(_.home(),{recursive:!0}),await ai.writeFile(_.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function xo(){let t=await ci();if(t)return t;let e=di();return await li(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
+ `),e}var cs=J(()=>{"use strict";he()});import*as xt from"fs/promises";import*as sp from"fs";import*as Rn from"path";import{randomBytes as cv}from"crypto";async function Gt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await lv(t,r,n)}async function lv(t,e,n={}){let s=await uv(t),r=fv(s);await xt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${pv()}`;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{sp.chmodSync(s,n.mode)}catch{}}async function uv(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=Rn.isAbsolute(n)?n:Rn.resolve(Rn.dirname(t),n);try{let r=await xt.realpath(Rn.dirname(s));return Rn.join(r,Rn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function mn(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 fv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function pv(){return cv(4).toString("hex")}var wr=J(()=>{"use strict"});import*as $s from"fs/promises";import{homedir as Yc}from"os";import{z as q}from"zod";function op(t){return t.tui.inAppSelection??t.tui.mouse}function ap(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function dp(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Fa(){return await kv(),await mn(_.config())??{}}async function kv(){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 Oa(){let t=await Fa(),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 li(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Gt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
+ `)}async function be(){return await Oa(),Vc.parse(await Fa())}async function ls(t){await Oa();let e=await Fa();t(e),Vc.parse(e),await Gt(_.config(),e,{mode:384})}async function Co(t,e){await ls(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function La(t){await ls(e=>{e.defaultAgent=t})}async function cp(t,e){await ls(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function lp(t,e){await ls(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 Qc(t,e){await ls(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 up(t){await ls(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function fp(){let t=await Fa();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function et(t){return t==="~"||t==="$HOME"?Yc():t.startsWith("~/")?Yc()+t.slice(1):t.startsWith("$HOME/")?Yc()+t.slice(5):t}var ip,hv,Tn,mv,gv,yv,wv,bv,rp,vv,Sv,Vc,Ve=J(()=>{"use strict";he();cs();wr();ip="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",hv=q.object({cert:q.string(),key:q.string()}),Tn=55514,mv=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Tn),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:hv.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)}),gv=q.object({url:q.string().url().default(ip),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),yv=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()}),wv=q.object({packageSpec:q.string().optional()}),bv=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()}),rp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),vv=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)}),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)}),Vc=q.object({daemon:mv.default({}),registry:gv.default({url:ip,ttlHours:24,pinned:!1}),agents:q.record(q.string(),yv).default({}),agentOverrides:q.record(q.string(),wv).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(rp,vv).default({}),transformers:q.record(rp,Sv).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:bv.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 br(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Gc(t){return{httpScheme:"https",wsScheme:"wss"}}function Xc(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 ${Ba(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Ba(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=Iv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Ba(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Ba(t)}`);let i=br(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=Tn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function pp(t){let e=t.port!==void 0&&t.port!==Tn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Iv(t){try{return new URL(t)}catch{return null}}function Ba(t){return t.length>80?`${t.slice(0,77)}...`:t}var Ao=J(()=>{"use strict";Ve()});function vr(t,e){return`${t}:${e}`}function hp(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function xv(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 Cv(){let t=await mn(_.remotes());return t===void 0?{version:1,entries:{}}:Av(t)}function Av(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 Zc(t){await Gt(_.remotes(),t,{mode:384})}var Na,el=J(()=>{"use strict";he();wr();Na=class t{data;constructor(e){this.data=e}static async load(){let e=await Cv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(hp(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Zc(i),new t(i)}get(e,n){let s=this.data.entries[vr(e,n)];if(s&&!hp(s,Date.now()))return s}async set(e,n,s){this.data.entries[vr(e,n)]=s,await Zc(this.data)}async delete(e,n){let s=vr(e,n);return s in this.data.entries?(delete this.data.entries[s],await Zc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=xv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function ui(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)}):Rv()}function Rv(){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 tl=J(()=>{"use strict"});import*as mp from"path";function Bn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=mp.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Ro=J(()=>{"use strict"});import*as Da from"fs/promises";async function us(){try{let t=await Da.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 gp(t){await Da.writeFile(_.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function En(t){try{return process.kill(t,0),!0}catch{return!1}}var fi=J(()=>{"use strict";he()});var kp={};zc(kp,{_resetForTests:()=>Lv,clearPin:()=>Fv,fetchPeerFingerprint:()=>il,formatFingerprint:()=>Ha,getPin:()=>sl,installGlobalTlsTrust:()=>al,loadPinsFromStore:()=>rl,setPin:()=>To,sha256Hex:()=>ol,wsTlsOptions:()=>Eo});import{createHash as Tv}from"crypto";import*as yp from"tls";import{Agent as Ev,Dispatcher as Pv,buildConnector as Mv,getGlobalDispatcher as _v,setGlobalDispatcher as $v}from"undici";function To(t,e,n){Sr.set(vr(t,e),wp(n))}function Fv(t,e){Sr.delete(vr(t,e))}function sl(t,e){return Sr.get(vr(t,e))}function rl(t){Sr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&To(e.host,e.port,e.entry.pinnedFingerprint)}async function il(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=yp.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,ol(l.raw))}),o.once("error",l=>c(l))})}function ol(t){return Tv("sha256").update(t).digest("hex")}function Ha(t){let e=wp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function wp(t){return t.replace(/:/g,"").toLowerCase()}function al(){if(nl)return;nl=!0;let t=_v(),e=new Ev({connect:Mv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>vp(s,r)})}),n=new Pv;n.dispatch=(s,r)=>{let i=Ov(s.origin);return(i&&bp(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(()=>{})),$v(n)}function Ov(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function bp(t){for(let e of Sr.keys())if(Sp(e)?.host===t)return!0;return!1}function vp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=ol(e.raw);for(let[s,r]of Sr.entries()){let i=Sp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Ha(n)})`)}function Sp(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 Eo(t){return bp(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>vp(e,n)}:{autoSelectFamily:!0}}function Lv(){Sr.clear(),nl=!1}var Sr,nl,Po=J(()=>{"use strict";el();Sr=new Map,nl=!1});import*as Ap from"os";async function _t(t){let e=await xo(),n=await us();if(n&&En(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:br(r)}}function Ip(t,e){let{httpScheme:n,wsScheme:s}=Gc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Tp(t),isLocal:t.isLoopback}}async function Rp(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??ui,r=e.confirmImpl??Hv,i=e.tlsHandshakeImpl??Bv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let v=await ci();if(v)return Dv(t,v)}let c=e.store??await Na.load();rl(c),al();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&To(t.host,t.port,d.pinnedFingerprint),Ip(t,d.token);if(!a)throw new dl(t.host,t.port);let l=Tp(t),{httpScheme:u}=Gc(t.host),f;if(u==="https"&&sl(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
10
  subject: ${v.subject??"(unknown)"}
11
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(`
12
+ sha256: ${Ha(v.fingerprint)}${b}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);To(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:Cp()})});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:Cp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),Ip(t,y.session_token)}async function Bv(t,e){let n=await Nv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await il(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Nv(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?xp(p.subject):void 0,issuer:p?.issuer?xp(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 xp(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 Dv(t,e){let n=await us(),r=n&&En(n.pid)?n.loopbackPort:t.port,i=t.port===Tn?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 Hv(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 Cp(){try{let t=Ap.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Tp(t){return t.port===Tn?t.host:`${t.host}:${t.port}`}var dl,kr=J(()=>{"use strict";Ve();cs();Ao();el();tl();Ro();fi();Po();Ao();dl=class extends Error{host;port;constructor(e,n){let s=n===Tn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Bn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as Uv,renameSync as jv,statSync as qv}from"fs";function Mp(t){Pp=t}function se(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{Wv(n);let s=JSON.stringify({t:new Date().toISOString(),...t});Uv(n,`${s}
15
+ `)}catch{}}function Wv(t){try{if(qv(t).size<Pp)return;jv(t,`${t}.0`)}catch{}}var Pp,Ir=J(()=>{"use strict";he();Pp=5*1024*1024});var z,Ka=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 eh,yS,th,nh,sh,Sl=J(()=>{"use strict";eh=Oe.object({protocolVersion:Oe.number().optional(),clientCapabilities:Oe.record(Oe.unknown()).optional(),clientInfo:Oe.object({name:Oe.string(),version:Oe.string().optional()}).optional()}),yS=Oe.enum(["full","pending_only","none","after_message"]),th=Oe.object({cwd:Oe.string(),mcpServers:Oe.array(Oe.unknown()).optional(),_meta:Oe.record(Oe.unknown()).optional()}),nh=Oe.object({upstreamSessionId:Oe.string(),agentId:Oe.string(),cwd:Oe.string(),title:Oe.string().optional(),agentArgs:Oe.array(Oe.string()).optional()}),sh=Oe.object({sessionId:Oe.string(),historyPolicy:yS.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 Ja(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 oh(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Mo(t._meta,Ja(t))};return t.title!==void 0&&(e.title=t.title),e}var rh,ih,kl,OE,wS,LE,Il=J(()=>{"use strict";Ya();rh=de.object({sessionId:de.string()}),ih=de.object({cwd:de.string().optional(),cursor:de.string().optional()}),kl=de.object({used:de.number().optional(),size:de.number().optional(),costAmount:de.number().optional(),costCurrency:de.string().optional()}),OE=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:kl.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()}),wS=de.object({sessionId:de.string(),cwd:de.string(),title:de.string().optional(),updatedAt:de.string().optional(),_meta:de.record(de.unknown()).optional()}),LE=de.object({sessions:de.array(wS),nextCursor:de.string().optional()})});function bS(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 Zt(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=nh.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=kl.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=bS(n.env);r!==void 0&&(s.env=r)}return s}function Mo(t,e){return{...t??{},[At]:e}}var At,Ya=J(()=>{"use strict";Sl();Il();At="hydra-acp"});import{z as ee}from"zod";var ah,Va,dh,jE,qE,WE,ch,zE,lh,KE,uh,JE,YE,fh=J(()=>{"use strict";ah=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),Va=ee.object({sessionId:ee.string()}),dh=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),jE=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:dh,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),qE=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),WE=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),ch=ee.object({sessionId:ee.string(),messageId:ee.string()}),zE=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),lh=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),KE=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),uh=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),JE=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),YE=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:dh,amendedAt:ee.number()})});import{z as Os}from"zod";var ph,Qa,yi,hh=J(()=>{"use strict";ph=Os.object({agentId:Os.string(),version:Os.string(),source:Os.enum(["binary","npm"]),phase:Os.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Os.number().optional(),totalBytes:Os.number().optional(),packageSpec:Os.string().optional()}),Qa="hydra-acp/agents/install_progress",yi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Rt=J(()=>{"use strict";Ka();Sl();Ya();Il();fh();hh()});import{nanoid as vS}from"nanoid";var xl,qt,Cr=J(()=>{"use strict";Rt();xl=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 xl;let s=vS(),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 wi(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 bi(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 Cl=J(()=>{"use strict"});import*as yh from"fs/promises";function _S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var CS,AS,vi,RS,TS,ES,PS,MS,gh,Za,wh=J(()=>{"use strict";CS=64*1024*1024,AS=1*1024*1024,vi=64*1024,RS=6e4,TS=100,ES=1e3,PS=64*1024,MS=256*1024,gh=20;Za=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??CS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(AS,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,vi));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,vi)),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,vi)),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,RS));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??TS,ES)),f=Math.max(1,Math.min(e.maxBytes??PS,MS)),p=Math.max(0,Math.min(e.contextBefore??0,gh)),h=Math.max(0,Math.min(e.contextAfter??0,gh)),m=[],y=[],v=[],b=0,S=!1,k=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 Se of G.before)b+=Se.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 N=m.length>=u&&v.length===0,Z=b>=f;return N||Z};for(let K=0;K<o.length;K++){if(o[K]!==10)continue;let H=o.subarray(k,K).toString("utf8"),L=r+k;if(k=K+1,T=k,$(L,H)){S=!0;break}}if(!S&&k<o.length&&this.closed){let K=o.subarray(k).toString("utf8"),H=r+k;$(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(()=>yh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var ed,yP,bh=J(()=>{"use strict";ed=[{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."}],yP=new Map(ed.map(t=>[t.verb,t]))});function vh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Si(t,e){return Al(t,e.map(n=>n.modelId))}function Al(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=vh(t),s=e.filter(i=>vh(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 td=J(()=>{"use strict"});function Sh(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=Rl(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=Rl(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?FS(r,i.outIndex,$S(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)?OS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!LS(f)&&(f=BS(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 Rl(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function $S(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function FS(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 OS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function LS(t){let n=Rl(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function BS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var kh=J(()=>{"use strict"});function ki(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=El(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Pl(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Tl(c))):d==="turn_complete"&&i()}return i(),jS(s.join(`
16
+ `),n)}function Tl(t){let e=DS(t),n=HS(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function DS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function HS(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of NS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${US(r,200)}`)}return n}function El(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 Pl(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function US(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function jS(t,e){if(t.length<=e)return t;let n=t.split(`
17
+ `);for(;n.length>0;){let s=Ih+n.join(`
18
+ `);if(s.length<=e)return s;n.shift()}return Ih}var Ih,NS,nd=J(()=>{"use strict";Ih=`[older history truncated]
19
+ `,NS=["file_path","filePath","path","command","pattern","query"]});function Ml(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??qS}`),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=_o("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=_o("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=_o("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=_o("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=_o("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=xh(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=xh(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=WS(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 _o(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 xh(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 WS(t,e){if(t.length===0||e<=0)return"";let n=zS(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 zS(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:El(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=Pl(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Tl(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var qS,Ch=J(()=>{"use strict";nd();qS="(untitled)"});import*as Hn from"fs/promises";async function $o(t,e){let n=_.queueFile(t);if(e.length===0){await Hn.unlink(n).catch(()=>{});return}await Hn.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 Hn.writeFile(n,s,"utf8")}async function Ah(t){let e=_.queueFile(t),n;try{n=await Hn.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 Rh(t){let e=_.queueFile(t);await Hn.unlink(e).catch(()=>{})}var _l=J(()=>{"use strict";he()});import{customAlphabet as _h}from"nanoid";import*as Oh from"fs/promises";function Bs(){return`m_${Fh()}`}function rt(t){return t.startsWith(yn)?t.slice(yn.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"&&VS.has(s)}function QS(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 GS(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 XS(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 xi(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 Fo(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 ZS(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 ek(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 tk(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 nk(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:Bs()}}}function Ol(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 Ph(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 sk(t){let e=rk(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=ik(t.resolver),n}function rk(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 ik(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 Ii(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Fl(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function ok(t){return t==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Mh(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 Ll(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,Fh,$l,KS,Th,yn,JS,sd,YS,Ci,VS,Un=J(()=>{"use strict";Cl();wh();bh();td();kh();Ch();_l();Rt();$h="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Fh=_h($h,16),$l=_h($h,16),KS=20,Th=20,yn="hydra_session_";JS=1e3,sd=300*1e3,YS=64,Ci=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;_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??`${yn}${Fh()}`,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.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??JS,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){ek(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=Ph(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_${$l()}`,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,v=new Set(n),b=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([...v,u.name]),m+1,b).then(()=>S()).catch(()=>S()))},sd);typeof k.unref=="function"&&k.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:k,transformerName:u.name,method:b,envelope:y,chainIdx:m,originatedBy:v,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),n.add(u.name)}if(r!=="session/update")return;let c=tk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=ZS(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=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 bi({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedModel:a,agentReportedModel:u.initialModel,logger:this.logger}),await wi({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=Ml({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.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),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:`
28
28
  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:`
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 bi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await wi({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=KS){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 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:Sh(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?Ol(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=Bs();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Zt((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=Ii(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:Bs()};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>YS;){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=Bs(),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=Bs(),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_${$l()}`,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??Fl(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:Fl(e))))},sd);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)}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_${$l()}`,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??ok(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 v=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})))},sd);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(d,{resolve:b=>y({shortCircuit:!0,payload:b}),timer:v,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):sd,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:Fl(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=Bs(),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=Ii((e??{}).prompt),r=Ll(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=xi(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=xi(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=Fo(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=xi(o.options);if(c.length>0){let d=Fo(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(QS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(GS(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(",")}]`),XS(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(ed.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=ed.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
30
  ${e}
31
31
  `},_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
32
  ${s.join(`
@@ -39,7 +39,7 @@ ${s}
39
39
  `},_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
40
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
41
41
  ${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:`
42
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Si(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
43
  ${d}.
44
44
  ${l}:
45
45
  ${c.join(`
@@ -49,7 +49,7 @@ ${l}:
49
49
  ${o}
50
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:`
51
51
  _(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:`
52
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>Mh(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
53
53
  ${u.join(`
54
54
 
55
55
  `)}
@@ -59,16 +59,16 @@ ${u.join(`
59
59
  Available options:
60
60
  ${l}
61
61
  `},_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:`
62
+ ${Mh(o)}
63
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=Al(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
64
  ${p}.
65
65
  ${h}:
66
66
  ${f.join(`
67
67
  `)}
68
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:
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=Ii(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=Ml({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 Za(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??vi,vi)),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(()=>Rh(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(()=>Oh.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=!Eh(e,r),o=i?nk(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 Wt(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=Ph(s),i=Bs(),{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(k=>{f--,m(()=>{let T=sk({toolCallId:r,result:k,resolver:b});for(let $ of u)$.client.clientId!==b.clientId&&$.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??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:Bs(),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,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=Ii(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"||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)}};VS=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 Ai}from"zod";var ak,Lh,Bh=J(()=>{"use strict";ak=Ai.object({source:Ai.string(),reason:Ai.string(),raisedAt:Ai.number(),payload:Ai.unknown()}),Lh=Ai.array(ak)});import{z as Le}from"zod";function Hh(t){let e=t.trim();if(e.length===0)return;let n=Ri(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Ri(e.slice(i,o+1)))}if(n===void 0){let i=jh(e);i!==void 0&&(n=Ri(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,Dh))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Oo.safeParse(s.synopsis);i.success&&dk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Uh(t){let e=t.trim();if(e.length===0)return;let n=Ri(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Ri(e.slice(d,l+1)))}if(n===void 0){let d=jh(e);d!==void 0&&(n=Ri(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,Dh))}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 Ri(t){try{return JSON.parse(t)}catch{return}}function jh(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 dk(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 Nh,Oo,Dh,Bl,Nl,rd=J(()=>{"use strict";Nh=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()}),Oo=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()}),Dh=200,Bl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
72
72
  {
73
73
  "title": "short summary, max 80 chars",
74
74
  "synopsis": {
@@ -78,7 +78,7 @@ ${h}:
78
78
  "open_threads": ["work started but not finished"]
79
79
  }
80
80
  }
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:
81
+ Use empty arrays/strings where a field doesn't apply.`;Nl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
82
82
  {
83
83
  "title": "short summary, max 80 chars",
84
84
  "goal": "the user's original ask",
@@ -90,293 +90,293 @@ Use empty arrays/strings where a field doesn't apply.`;Bl=`Reply with ONLY a JSO
90
90
  "unresolved_errors": ["errors left open at session end"],
91
91
  "tool_state": ["runtime state relevant for recall"]
92
92
  }
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(`
93
+ Use empty arrays/strings where a field doesn't apply.`});import*as Ti from"fs/promises";import*as HP from"path";import{customAlphabet as ck}from"nanoid";import{z as ne}from"zod";function Lo(){return`${fk}${uk()}`}function gk(t){if(!Dl.test(t))throw new Error(`unsafe session id: ${t}`)}function Wl(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 lk,uk,fk,Hl,Ul,pk,jl,ql,hk,mk,Dl,id,zl=J(()=>{"use strict";he();wr();Bh();rd();lk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",uk=ck(lk,16),fk="hydra_lineage_";Hl=ne.object({name:ne.string(),description:ne.string().optional()}),Ul=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),pk=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),jl=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),ql=ne.object({name:ne.string(),version:ne.string().optional()}),hk=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),mk=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:Oo.optional(),compactionState:Nh.optional(),rollbackBreadcrumb:hk.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:jl.optional(),agentCommands:ne.array(Hl).optional(),agentModes:ne.array(Ul).optional(),agentModels:ne.array(pk).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:ql.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Lh.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Dl=/^[A-Za-z0-9_-]+$/;id=class{async write(e){gk(e.sessionId);let n={version:1,...e};await Gt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Dl.test(e))return;let n=await mn(_.sessionFile(e));if(n!==void 0)try{return mk.parse(n)}catch{return}}async delete(e){if(Dl.test(e)){try{await Ti.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Ti.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 Ti.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 wk}from"url";import*as Bo from"path";import*as ad from"fs";function bk(){try{let t=Bo.dirname(wk(import.meta.url));for(let e=0;e<8;e+=1){let n=Bo.join(t,"package.json");if(ad.existsSync(n)){let r=JSON.parse(ad.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=Bo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,Ar,en=J(()=>{"use strict";fe=bk(),Ar="hydra-acp-cat"});function Kl(t){let e=new Map;for(let n of Xh(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 Vh(t){return Kl(t).map(e=>e.name)}function Jl(t){let e=new Map;for(let n of Xh(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 Qh(t){return Jl(t).map(e=>e.path)}function Gh(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Xh(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:Jh(i),paths:new Set},e.set(c,d)):d.toolName=Jh(i);for(let l of Yh(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 Yh(i.rawInput,i.locations))a.paths.add(c)}return e}function Jh(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Yh(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 Yl=J(()=>{"use strict"});import{promises as Do}from"fs";import*as eu from"path";async function Ho(t){let e;try{e=await Do.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return Ek(e)}function Ek(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 Uo(t,e,n=cm){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 Rr(t,e){await Do.mkdir(eu.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Do.writeFile(t,n.length>0?n.join(`
95
95
  `)+`
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(`
96
+ `:"")}async function lm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Do.mkdir(eu.dirname(t),{recursive:!0}),await Do.appendFile(t,JSON.stringify(n)+`
97
+ `,{encoding:"utf8"}))}function ud(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function tu(t,e,n=cm){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=Uo(r,o,n)))}return r}var cm,fd=J(()=>{"use strict";cm=500});import{z as Me}from"zod";function jo(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 Pn(t){return _k.parse(t)}var Pk,Mk,_k,Tr=J(()=>{"use strict";zl();rd();Pk=Me.object({method:Me.string(),params:Me.unknown(),recordedAt:Me.number()}),Mk=Me.object({sessionId:Me.string(),lineageId:Me.string(),upstreamSessionId:Me.string().optional(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),synopsis:Oo.optional(),summarizedThroughEntry:Me.number().int().nonnegative().optional(),currentModel:Me.string().optional(),currentMode:Me.string().optional(),currentUsage:jl.optional(),agentCommands:Me.array(Hl).optional(),agentModes:Me.array(Ul).optional(),interactive:Me.boolean().optional(),originatingClient:ql.optional(),priority:Me.number().int().nonnegative().optional(),createdAt:Me.string(),updatedAt:Me.string()}),_k=Me.object({version:Me.literal(1),exportedAt:Me.string(),exportedFrom:Me.object({hydraVersion:Me.string(),machine:Me.string(),hydraHost:Me.string().optional()}),session:Mk,history:Me.array(Pk),promptHistory:Me.array(Me.string()).optional(),toolBlobs:Me.record(Me.string()).optional()})});import{createHash as Kk}from"crypto";function uu(t){if(Array.isArray(t))return t.map(uu);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=uu(t[n]);return e}return t}function Hs(t){let{tui:e,...n}=t,s=JSON.stringify(uu(n));return Kk("sha256").update(s).digest("hex").slice(0,16)}var Vo=J(()=>{"use strict";Ve()});function fu(t){return Math.floor(t/4)}function Em(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=fu(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 Pm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var pu=J(()=>{"use strict"});function Qo(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Mm=J(()=>{"use strict"});import{posix as rI}from"path";import iI from"strip-ansi";function ct(t){return iI(t).replace(oI,"")}function Ee(t){return ct(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Wn(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 fI(n);case"agent_thought_chunk":case"agent_thought":return pI(n);case"user_message_chunk":return hI(n);case"prompt_received":return mI(n);case"tool_call":return gI(n,e);case"tool_call_update":return SI(n,e);case"plan":return xI(n);case"current_mode_update":return CI(n);case"current_model_update":return AI(n);case"turn_complete":return RI(n);case"usage_update":return uI(n);case"available_commands_update":return cI(n);case"available_modes_update":return lI(n);case"session_info_update":return dI(n);case"config_option_update":return aI(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function aI(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 dI(t){let e=tt(t,"title"),n=e!==void 0?Ee(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 Td(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 cI(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Td(e)}:null}function lI(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 uI(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 fI(t){let e=Go(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Qo(t)}}function pI(t){let e=typeof t.text=="string"?ct(t.text):Go(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Qo(t)}}function hI(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=Go(t.content);return n===null?null:{kind:"user-text",text:n}}function mI(t){let e=TI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Fm(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 Ed(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 Om(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 gI(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(Fm(r)){let h=Om(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=Nm(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=Ed(t);d!==null&&(c.editDiff=d);let l=Bm(t);l!==void 0&&(c.detail=l);let u=hu(t);u!==void 0&&(c.detailFull=u);let f=Lm(t);f!==void 0&&(c.locations=f);let p=Qo(t);return p!==void 0&&(c.workerTaskId=p),c}function Lm(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 Bm(t){let e=hu(t);if(e===void 0)return;let n=Ee(e),s=t.rawInput;return s&&typeof s.command=="string"?bI(n,$m):vI(n,$m)}function hu(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 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 wI(t){for(let e of yI)if(t.startsWith(e))return!0;return!1}function Nm(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 wI(t)?Ze(`/${t}`):n.cwd&&n.cwd.length>0?Ze(rI.resolve(n.cwd,t)):t}function bI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function vI(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 SI(t,e={}){let n=tt(t,"toolCallId")??tt(t,"id");if(!n)return null;let s=tt(t,"title"),r=s!==void 0?Nm(Ee(s),t,e):void 0,i=tt(t,"status"),o=Ed(t),a=Bm(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(Fm(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=Om(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=hu(t);u!==void 0&&(l.detailFull=u);let f=Lm(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=kI(t);h!==null&&(l.errorText=h),II(t,h)&&(l.upstreamInterrupted=!0)}let p=Qo(t);return p!==void 0&&(l.workerTaskId=p),l}function kI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Go(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 II(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 xI(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 CI(t){let e=tt(t,"currentModeId")??tt(t,"currentMode")??tt(t,"mode");return e?{kind:"mode-changed",mode:Ee(e)}:null}function AI(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 RI(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 Go(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 TI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Go(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 oI,$m,yI,Us=J(()=>{"use strict";he();Mm();oI=/[\x00-\x08\x0b-\x1f\x7f]/g;$m=64;yI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function _i(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=PI(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)EI(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 EI(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 PI(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=Ed(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Pd=J(()=>{"use strict";Us()});function zn(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 Li=J(()=>{"use strict";Rt()});import{spawn as Vx}from"child_process";import{setTimeout as Qx}from"timers/promises";async function Ig(){let t=await us();if(t&&En(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function Gx(t){let e=await Mr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===Hs(t)?"match":"mismatch":"missing"}async function Ws(t){let e=await Gx(t);if(e!=="match"){if(e==="mismatch"){let n=Bn();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
+ `),jd(),await qd(t)}}async function Ud(t){let e=await Ig();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Mr(t,e=1e3){let n=await Ig();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 jd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Vx(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function qd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Ud(t))return;await Qx(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var _r=J(()=>{"use strict";Ro();Vo();fi()});import*as xg from"fs";import*as Di from"fs/promises";async function Hi(t,e,n){let s=Zx(e),r;try{r=await Di.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
99
+ `),process.exit(1);return}throw c}let i=await Xx(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
100
+ `);let o=!1,a=xg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Di.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Di.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 Xx(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Di.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
101
  `).slice(-n-1);process.stdout.write(d.join(`
102
102
  `)),o.endsWith(`
103
103
  `)||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}
104
+ `)}finally{await r.close()}return e}function Wd(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 Zx(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
105
  `),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}
106
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}var ea=J(()=>{"use strict"});import{WebSocket as nC}from"ws";async function $r(t,e,n=sC){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=Eo(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 nC(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 Au(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 sC,Au,ta=J(()=>{"use strict";Po();sC=1e4,Au=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 zd from"fs/promises";function rC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function ji(){let t=await us();if(t&&En(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await be();return Mg(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Mg(t,e,n){return`${n?"https":"http"}://${rC(t)}:${e}`}async function Fe(t,e={}){let n=await yr(),s=await ji(),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
107
  `),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
108
+ `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function qi(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 Kd(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?iC(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
110
110
  `),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
111
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
112
112
  `),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(`
113
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function iC(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Wi(){let t=await zd.readFile(_.config(),"utf8");return JSON.parse(t)}async function Ru(t){await zd.writeFile(_.config(),JSON.stringify(t,null,2)+`
114
+ `,{encoding:"utf8",mode:384})}var zs=J(()=>{"use strict";Ve();cs();he();fi();ta()});async function sn(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 Tu(t,n):c}finally{clearTimeout(a)}}async function Kn(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 sn(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 sn(`${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 sn(`${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 Jd(t,e=fetch){let n=await sn(`${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 Yd(t,e,n={},s=fetch){let r=await sn(`${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 Jn(t,e,n=fetch){let s=await sn(`${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 $g(t,e,n,s=fetch){let r=await sn(`${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 Fg(t,e,n,s=fetch){let r=await sn(`${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 Og(t,e,n=fetch){let s=await sn(`${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 Lg(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await sn(`${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 Bg(t,e,n=fetch){let s=await sn(`${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 Vd(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 Tu,na=J(()=>{"use strict";Tu=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 Eu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Ng(t,e){let n=t??"?",s=Eu(e);return s?`${n}${oC}${s}`:n}function Dg(t){return t??"?"}function Hg(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Pu(e,n)}function Pu(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var oC,Mu=J(()=>{"use strict";oC="\u2022"});function Ug(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(!Gd.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Gd.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Ji(t,e=Date.now()){return{session:rt(t.sessionId),upstream:cC(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:lC(t.status,t.busy,t.awaitingInput,dC(t.compactionState),t.forkSynthesisState),agent:Dg(t.agentId),model:Eu(t.currentModel)??"-",age:uC(t.updatedAt,e),title:t.title??"-",cwd:Ze(t.cwd),cost:Hg(t.currentUsage)}}function dC(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 cC(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function lC(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 Yi(t,e={}){let n=e.columns??zi,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]=fC(Ki[r],t.map(i=>i[r]));return s}function uC(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 fC(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ks(t,e,n,s={}){let r=s.columns??zi,i=s.cwdMaxWidth??aC,o=b=>b==="age"?t[b].padStart(e[b]):t[b].padEnd(e[b]);if(n===void 0)return r.map((S,k)=>k===r.length-1?t[S]:o(S)).join(Qd);let a=r.map((b,S)=>({col:b,i:S})).filter(({col:b})=>_u.has(b)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let b=r.map(o).join(Qd);return b.length>n?b.slice(0,n):b}let d=r.filter(b=>!_u.has(b)).reduce((b,S)=>b+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*Qd.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:b,i:S}of a){if(S===c)continue;let k=b==="cwd"?Math.min(e[b],i):e[b],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=(b,S,k)=>{if(b==="cwd")return sa(t[b],S).padEnd(S);let T=pC(t[b],S);return k?T:T.padEnd(S)},v=r.map((b,S)=>_u.has(b)?m(b,f.get(S)??0,S===h):o(b)).join(Qd);return v.length>n?v.slice(0,n):v}function pC(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function sa(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 Gd,zi,_u,Ki,Qd,aC,Xd=J(()=>{"use strict";Mu();he();Un();Gd=["session","upstream","host","state","agent","model","age","cwd","title","cost"],zi=["session","state","age","cwd","title","agent","cost"],_u=new Set(["cwd","title"]),Ki={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Qd=" ",aC=32});import{spawn as IC}from"child_process";import{Writable as xC}from"stream";function Zd(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=CC(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??IC,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 xC({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 CC(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 AC from"chalk";import{highlight as RC,supportsLanguage as ec}from"cli-highlight";import nc from"string-width";function Js(t,e={}){switch(t.kind){case"user-text":{let n=Fu(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 Fu(t.text," ","agent");case"agent-thought":return Fu(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return VC(t,e.maxPlanItems??JC);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 Ou(t,e){return Vi(t,e).styled}function Vi(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=Vi(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=Vi(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 k of v.links)l.push({start:b+k.start,end:b+k.end,url:k.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 TC(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 Zg(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 ey(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=" ",k,T)=>{let $={prefix:S,body:v,bodyStyle:b};r!==void 0&&($.prefixStyle=r),k&&k.length>0&&($.links=k),T&&($.ansi=!0),c.push($)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let v=ny(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 k=b.match(/^(#{1,6})\s+(.*)$/);if(k){let H=k[1].length,L=k[2]??"",N=s?H===1?"heading-1":H===2?"heading-2":"heading-3":n,Z=s?Zg(N):o;h(Ou(L,Z),N,m());continue}let T=d[v+1];if(b.includes("|")&&T!==void 0&&EC(T)&&ra(b).length===ra(T).length){let H=ra(b),L=[],N=v+2;for(;N<d.length&&d[N].includes("|");)L.push(ra(d[N])),N++;let Z=LC(H,L,a);for(let G of Z)r!==void 0&&(G.prefixStyle=r),c.push(G);v=N-1;continue}let $=b.match(/^(\s*)[-*+]\s+(.*)$/);if($){let H=$[1]??"",L=$[2]??"",N=Vi(L,o),Z=H.length+2,G=N.links.map(Se=>({start:Se.start+Z,end:Se.end+Z,url:Se.url}));h(`${H}\u2022 ${N.styled}`,n,m(),G,N.ansi);continue}let F=b.match(/^(\s*)(\d+)\.\s+(.*)$/);if(F){let H=F[1]??"",L=F[2]??"",N=F[3]??"",Z=Vi(N,o),G=H.length+L.length+2,Se=Z.links.map(X=>({start:X.start+G,end:X.end+G,url:X.url}));h(`${H}${L}. ${Z.styled}`,n,m(),Se,Z.ansi);continue}let j=b.trim()==="",K=Vi(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 Ys(t,e){return ey(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Qi(t){return ey(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function ra(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 EC(t){if(!t.includes("|"))return!1;let e=ra(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function tc(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return nc(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:nc(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:tc(r)}),n=i}return e}function $C(t,e){let n=[],s="",r=0;for(let i of t){let o=nc(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 FC(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=$C(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=nc(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 OC(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,ty)),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 LC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=tc(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=tc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*ty,n-PC-(s-1)*MC);i=OC(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=FC(_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],k=tc(b),T=Ou(b,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",Zg("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 ny(t,e){if(t.length===0||!ec(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=RC(e.join(`
118
+ `),{language:t,theme:BC,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 DC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return ec("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return ec("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=NC[s];return r&&ec(r)?r:""}function Fu(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 HC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Yn(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 sy(t){if(t.length<=4096&&t.split(`
121
121
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
122
122
  `);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(`
123
+ `),r=!0),{text:s,truncated:r}}function ia(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 ${Yn(l-t.startedAt)}`}let c={prefix:` ${WC(t.status)} `,prefixStyle:zC(t.status),body:o,bodyStyle:QC(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 ry(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: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(`
125
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=DC(r);if(i.length>0){let o=ny(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 oy(t){iy=t>=0?t:0}function Lu(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=` (~${HC(d)})`}else{let d=jC(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=Bu(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(...Ys(c)),s.length>0&&s.unshift({body:""}),s}function ay(t){let e=ct(t.oldText).split(`
126
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}
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 jC(t){let{oldLines:e,newLines:n}=ay(t),s=0,r=0;for(let i of dy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Xg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Bu(t,e={}){let n=e.maxLines??UC,s=e.contextLines??iy,{oldLines:r,newLines:i}=ay(t),o=dy(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(Xg(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(Xg(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 dy(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(...qC(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 qC(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 Nu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function WC(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 zC(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 cy(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ys(t.plan));let n=t.status;if(n!==void 0){let s=KC(n);s!==null&&e.push(s)}return e}function KC(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 YC(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 VC(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}=YC(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=Ou(b,TC(v));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:v})}return f}function QC(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 ty,PC,MC,nt,BC,NC,UC,iy,JC,Gi=J(()=>{"use strict";he();Us();ty=6,PC=2,MC=3;nt=new AC.Instance({level:3}),BC={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};NC={".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"};UC=40,iy=Number.POSITIVE_INFINITY;JC=5});import{highlight as GC,supportsLanguage as XC}from"cli-highlight";async function uy(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 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=Pn(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
130
+ `),process.exit(1)}let u=_i(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:$i(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
131
131
  `),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(`
132
+ `);return}let i=Zd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Du(r,a)),await i.flush()}function Du(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=tA(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
134
+ `:n.join("")}function ZC(t){let e=[];for(let n of t.hunks){let s=Bu(n,{maxLines:1/0});eA(s)&&e.push({body:s,oldCount:ly(n.oldText),newCount:ly(n.newText)})}return e}function eA(t){if(t.length===0)return!1;for(let e of t.split(`
135
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function tA(t,e){let n=ZC(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
136
  `)+`
137
137
 
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(`
138
+ `;return!e||!XC("diff")?i:GC(i,{language:"diff"})}function ly(t){if(t.length===0)return 0;let e=t.split(`
139
+ `);return e[e.length-1]===""&&e.pop(),e.length}var Hu=J(()=>{"use strict";zs();Tr();Pd();Gi();$u()});async function fy(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 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=Pn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
141
+ `),process.exit(1)}let a=qu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=_i(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=Zd({disabled:e.noPager===!0});f.stream.write(sc(a,e.verbose===!0)),f.stream.write(`
143
+ `),f.stream.write(Du(d??[],u)),await f.flush();return}process.stdout.write(sc(a,e.verbose===!0))}function qu(t,e){let n=t.session,s=t.history,r=Gh(s),i=Kl(s),o=Jl(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 sc(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:")}${sA(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,Uu),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>Uu&&n.push(` ... ${t.tools.length-Uu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>nA.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,ju),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>ju&&n.push(` ... ${o.length-ju} more (use --verbose to see all)`)}return n.join(`
144
144
  `)+`
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)+`
145
+ `}function sA(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 Uu,ju,nA,Wu=J(()=>{"use strict";zs();Tr();Yl();Pd();$u();Hu();Uu=10,ju=15,nA=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var My={};zc(My,{assertKnownAgent:()=>oc,resolveAgentIdOrExit:()=>Ju,runAgentsAdd:()=>Zu,runAgentsInstall:()=>Yu,runAgentsList:()=>Ku,runAgentsLogs:()=>Qu,runAgentsPin:()=>Xu,runAgentsRefresh:()=>ac,runAgentsRemove:()=>ef,runAgentsSet:()=>Gu,runAgentsSync:()=>Vu,runRegistryPin:()=>dc});async function Ku(){let e=(await Fe("/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:ps(s.id,n.map(a=>a.id)),name:ps(s.name,n.map(a=>a.name)),version:ps(s.version,n.map(a=>a.version)),source:ps(s.source,n.map(a=>a.source)),distributions:ps(s.distributions,n.map(a=>a.distributions)),installed:ps(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
147
  `);for(let a of n)process.stdout.write(i(a)+`
148
- `);let o=e.fetchedAt!==void 0?` (synced ${ji(e.fetchedAt)})`:"";process.stdout.write(`
148
+ `);let o=e.fetchedAt!==void 0?` (synced ${qi(e.fetchedAt)})`:"";process.stdout.write(`
149
149
  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(", ")}).
150
+ `)}async function oc(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.
151
+ `),process.exit(2))}async function Ju(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
152
  `),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"}
153
+ `),process.exit(2)}async function Yu(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
154
+ `),process.exit(2);return}let e=await Ju(t,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
155
+ `);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
156
  `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
157
157
  `),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)+`
158
+ `)}async function Vu(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
159
+ `),process.exit(2);return}let e=await Ju(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).
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:ps(i.id,r.map(c=>c.id)),upstream:ps(i.upstream,r.map(c=>c.upstream)),cwd:ps(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
161
  `);for(let c of r)process.stdout.write(a(c)+`
162
162
  `);process.stdout.write(`
163
163
  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(", ")}).
164
+ `)}async function Qu(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 Hi(n,e,"No log file (agent never ran?)")}async function Gu(t,e){let n=await be();if(!t){let c=await Ey()??zu(await Wi());process.stdout.write(`${Ty(c)}
166
+ `);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
167
  `),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}.
168
+ `),process.exit(1);return}}e!==void 0?await cp(t,e):await La(t);let i=zu(await Wi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
169
+ `),process.stdout.write(`${Ty(i)}
170
+ `);let o=await Ey();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Py(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
171
+ `))}function Ty(t){return`Default agent is ${Py(t)}`}function Py(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 Ey(){try{let t=await Fe("/v1/config",{rethrowNetworkError:!0});return t.ok?zu(t.body):void 0}catch{return}}async function ac(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
172
+ `)}async function Xu(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
173
+ `),process.exit(2);return}await lp(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
174
174
  `):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]...
175
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Zu(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
176
176
  `),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(`
177
+ `),process.exit(2);return}let n=Kd(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 Qc(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 ef(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
179
+ `),process.exit(2);return}await Qc(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 dc(t){await up(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 ps(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}var tf=J(()=>{"use strict";Ve();he();ea();zs()});var cc,hs,Zi,oa,_y,aa,nf,lc,Lr,$y,Br,Fy,Nr,Oy,Dr,eo,to,Ly,no,By,Ny,Dy,sf,Hy,uc,fc,da,Uy,jy,ca=J(()=>{"use strict";cc="\x1B[?2004h",hs="\x1B[?2004l",Zi="\x1B[200~",oa="\x1B[201~",_y="\x1B[?1049l",aa="\x1B[?7h",nf="\x1B[?7l",lc="\x1B[?25h",Lr="\x1B[?1l",$y="\x1B[>1u",Br="\x1B[<u",Fy="\x1B[>4;2m",Nr="\x1B[>4;0m",Oy="\x1B[>5;1m",Dr="\x1B[>5;0m",eo="\x1B[?1000l",to="\x1B[?1002l",Ly="\x1B[?1003l",no="\x1B[?1006l",By="\x1B[?1015l",Ny="\x1B[?w",Dy="\x1B[=24;1w",sf="\x1B[=0;0w",Hy="\x1B]22;pointer\x07",uc="\x1B]22;default\x07",fc="\x1B[?1004h",da="\x1B[?1004l",Uy="\x1B[?2026h",jy="\x1B[?2026l"});function Mn(){process.stdout.write(Br),process.stdout.write(hs),process.stdout.write(Nr),process.stdout.write(Dr),process.stdout.write(eo),process.stdout.write(to),process.stdout.write(no),process.stdout.write(Lr),process.stdout.write("\x1B>")}function rn(t){return t.width??80}function ms(t){return t.height??24}function _n(t,e){let n=rn(t),s=ms(t),r=e.contentWidth??iA,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=qy.repeat(a-2),p=lA(f,e.title);t.moveTo(l,u),t.dim.noFormat(oA),uA(t,p),t.dim.noFormat(aA);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(Wy),t.moveTo(l+a-1,u+h),t.dim.noFormat(Wy);return t.moveTo(l,u+d-1),t.dim.noFormat(dA+qy.repeat(a-2)+cA),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function lA(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 uA(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 pc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Vn(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 iA,qy,Wy,oA,aA,dA,cA,Hr=J(()=>{"use strict";Ir();ca();iA=64,qy="\u2500",Wy="\u2502",oA="\u250C",aA="\u2510",dA="\u2514",cA="\u2518"});function zy(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 hA(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??fA,footer:pA};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}] ${zy(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 mA(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 gA(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function Ky(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 yA(t){let e=Ky(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function wA(t){let e=Ky(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 Jy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!gA(e))throw e;let n=yA(e)??t.fallbackAgentId??"",s=wA(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 bA(t,e,n){t.grabInput(!1),se({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Mn(),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({}),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
183
  failed to spawn ${e.command}: ${c.message}
184
184
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
185
185
  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(`
186
+ `),i({exitCode:-1})}})}function vA(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 rf(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(vA(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 Yy(t,e,n,s,r){Mn();let i=hA(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=_n(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 Vn({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=mA(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 ${zy(y)}\u2026`,d();let v=r.runTerminalAuth??(b=>bA(t,b));(async()=>{let b=await rf(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 fA,pA,of=J(()=>{"use strict";Ir();Ka();Ya();Hr();fA="This agent requires authentication before use.",pA="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Zy}from"timers/promises";function EA(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var CA,AA,RA,TA,ro,af=J(()=>{"use strict";ta();Li();CA=200,AA=5e3,RA=2,TA=60,ro=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(()=>{}),Zy(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=CA;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(zn(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>=TA)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 Zy(n),this.destroyed)return;n=Math.min(n*RA,AA)}}bindStream(e){this.current=e,e.onMessage(n=>{if(EA(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 ew(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 Ur(t){return{outcome:{outcome:"selected",optionId:ew(t,["allow_once","allow_always"])}}}function tw(t){return{outcome:{outcome:"selected",optionId:ew(t,["reject_once","reject_always"])}}}function gc(t){return t&&typeof t=="object"?t:void 0}function la(t){return typeof t=="string"&&t.length>0?t:void 0}function nw(t){let e=gc(t),n=gc(e?.toolCall),s={paths:[]};if(!n)return s;let r=la(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=la(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(gc(d)?.path);let c=gc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=la(c.command);d&&(s.command=d);let l=la(c.url);l&&(s.url=l);let u=la(c.description);u&&(s.description=u)}return s}function sw(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 yc=J(()=>{"use strict"});function TR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function kw(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 ER(t,e){let n=kw(t),s=kw(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 ua(){if(Qs!==void 0)return Qs;if(TR())return Qs=null,Qs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Iw,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&ER(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Qs={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{}Qs=null}}catch{Qs=null}return Qs}function fa(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Iw}`}var Iw,Qs,lf=J(()=>{"use strict";en();Iw="@hydra-acp/cli"});import*as pa from"fs/promises";import*as uf from"path";async function ha(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=uf.resolve(et(e)),s;try{s=await pa.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 xw(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 pa.stat(r)).isDirectory())return r}catch{}return null}async function Cw(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=uf.resolve(et(r)),o;try{o=(await pa.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 ff=J(()=>{"use strict";Ve()});var Aw,Rw,Tw,Ew=J(()=>{"use strict";Aw="hydra-acp/question/list",Rw="hydra-acp/question/answer",Tw="hydra-acp/question/dismiss"});import{EventEmitter as PR}from"events";import{WebSocket as MR}from"ws";function _R(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=Eo(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 MR(t,e,n),o=()=>{i.off("error",a),s(zn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Pw(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 Yd(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 pf(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(()=>{}),Jn(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 pf,Mw=J(()=>{"use strict";Po();na();Cr();Li();Rt();pf=class extends PR{_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(()=>{}),Jn(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 hf,kc,_w=J(()=>{"use strict";Gi();Us();hf=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())}},kc=class extends hf{_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=Wn(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=Qi(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Qi(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=ia(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=ia(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=Js(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Ys(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 FR(t,e){return`[pasted #${t} +${e} lines]`}var $R,Ic,mf,OR,gs,gf=J(()=>{"use strict";$R=/\[pasted #(\d+) \+\d+ lines\]/g,Ic=/\[pasted #(\d+) \+\d+ lines\]$/,mf=/^\[pasted #(\d+) \+\d+ lines\]/;OR=500,gs=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>OR&&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(`
188
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(FR(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(`
189
+ `)}expandPastes(e){return e.replace($R,(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
190
  `)){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=`
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(Ic);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(mf);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
192
  `,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
193
  `,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
194
  `,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(`
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(Ic);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(Ic);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(mf);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(Ic);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(mf);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 ao,xc,yf=J(()=>{"use strict";ao=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())}},xc=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 LR from"path";function ma(t){return $w[LR.extname(t).toLowerCase()]??null}function BR(t){return ma(t)!==null}function wf(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(!NR.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 DR(t){return wf(t)!==null}function vn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Fw(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(!DR(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!BR(o))return null;n.push(o)}return n.length>0?n:null}var Qn,$w,NR,Cc=J(()=>{"use strict";Qn=10*1024*1024,$w={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};NR=new Set(Object.values($w))});import HR from"string-width";function Ow(t,e){if(!t||e<=0)return 0;let n=0;for(let s of UR.segment(t)){let r=HR(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Lw(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 UR,Bw=J(()=>{"use strict";UR=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as jR}from"child_process";import bf from"fs/promises";import qR from"os";import WR from"path";async function Hw(t={}){let e={...vf,...t};return e.platform==="darwin"?YR(e):e.platform==="linux"?VR(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Uw(t={}){let e={...vf,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await co(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await co(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 ga(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Sf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function jw(t,e={}){let{target:n="both",...s}=e,r={...vf,...s},i=await zR(r,t,n);if(i.ok)return i;let o=KR(r,t,n);return o.ok||o.reason!==qw?o:i}async function zR(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await Ac(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 co(t,"wl-copy")?Dw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await co(t,"xclip")?Dw(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 Dw(t,e,n,s,r,i,o){let a=n;if(i){try{await Ac(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await Ac(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await Ac(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function KR(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Nw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Nw} 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??JR)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:qw}}function JR(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 YR(t){let e=WR.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 Ww(t.spawn,"osascript",s);let r=await e0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await bf.unlink(e).catch(()=>{})}try{let r=await ga(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Sf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function VR(t){let e=await QR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await ZR(t,e),s=XR(n);if(s)try{let r=await ga(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Qn?{ok:!1,reason:`clipboard image is ${vn(r.length)}, max ${vn(Qn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await ga(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Sf(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function QR(t){return t.env.WAYLAND_DISPLAY&&await co(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await co(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function XR(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of GR)if(e.has(n))return n;return null}async function ZR(t,e){try{return(await ga(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
197
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Sf(t){return t.replace(/\r\n?/g,`
198
+ `)}async function co(t,e){try{return await Ww(t.spawn,"which",[e]),!0}catch{return!1}}async function e0(t,e){try{let n=await bf.readFile(t);return e&&await bf.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Qn?{ok:!1,reason:`clipboard image is ${vn(n.length)}, max ${vn(Qn)}`}:{ok:!0,kind:"image",attachment:{mimeType:ma(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Ww(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 Ac(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 ga(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 vf,Nw,qw,GR,kf=J(()=>{"use strict";Cc();vf={platform:process.platform,env:process.env,spawn:jR,tmpdir:qR.tmpdir};Nw=74994;qw="no TTY available for OSC 52 clipboard write";GR=["image/png","image/jpeg","image/gif","image/webp"]});function t0(){ya===0&&process.stdout.write(Uy),ya++}function n0(){ya!==0&&(ya--,ya===0&&process.stdout.write(jy))}function Ne(t){t0();try{t()}finally{n0()}}var ya,If=J(()=>{"use strict";ca();ya=0});import{spawn as s0}from"child_process";import{statSync as r0}from"fs";import{homedir as zw}from"os";import{isAbsolute as Kw,resolve as i0}from"path";import Ke from"string-width";import o0 from"wrap-ansi";function m0(t){let e=t.replace(/\r\n?$|\n$/,"");return h0.test(e)?e:null}function g0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function Jw(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 ws(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 Xs(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 Yw(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){ys(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){ys(t,e.slice(c),n,o);return}d>c&&ys(t,e.slice(c,d),n,o);let l=r!==null&&d===r;ys(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function wa(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function ys(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 y0(t,e){return e<=0?[t]:t.length===0?[""]:o0(t,e,{hard:!0,trim:!1}).split(`
199
+ `)}function sb(t){nb=t}function rb(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 Gs(t){return Ke(t,{ambiguousIsNarrow:!nb})}function lo(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 w0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Vw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=lo(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 Qw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=lo(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function b0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=lo(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function ib(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(lo(t,e))return!0;return!1}function*Ff(t){let e=0;for(;e<t.length;){let n=lo(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(lo(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:Gs(i)};e=s}}function v0(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 S0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&ib(t);return!s&&!tb.test(t)?k0(t,e):I0(t,e,s)}function k0(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 I0(t,e,n){let s=[],r=n?[...Ff(t)]:x0(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 x0(t){let e=[];for(let{segment:n}of $f.segment(t))e.push({text:n,width:Gs(n)});return e}function vt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&ib(t);if(!s&&t.length<=e&&!tb.test(t))return t;if(!s)return Gs(t)<=e?t:e<=1?Gw(t,e):Gw(t,e-1)+"\u2026";let r=[...Ff(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?Xw(r,e):Xw(r,e-1)+"\u2026"}function Gw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of $f.segment(t)){let i=Gs(r);if(s+i>e)break;n+=r,s+=i}return n}function Xw(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 C0(t){let e=t.indexOf(`
200
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Zw(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Tc(t.used)}/${Tc(t.size)}`):e.push(Tc(t.used)):typeof t.size=="number"&&e.push(`/${Tc(t.size)}`),typeof t.costAmount=="number"&&e.push(Pu(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Tc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Pc(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 qr(){let t=[eo,to,Ly,no,By,sf,hs,Nr,Dr,Br,Lr,"\x1B>",aa,lc,uc,"\x1B]9;4;0\x07",_y].join("");try{process.stdout.write(t)}catch{}}function ob(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 eb(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 xf,Rc,Cf,Af,a0,Ue,Qe,d0,Ge,Rf,Tf,c0,l0,u0,Ef,Pf,Mf,f0,p0,h0,Ec,tb,$f,nb,w0,_f,Of=J(()=>{"use strict";yf();Mu();he();Un();Cc();Gi();Bw();kf();If();Ir();ca();xf=500,Rc=1,Cf=/[A-Za-z0-9_]/,Af=/[A-Za-z0-9_./\-~+@]/,a0=/\x1b\[[0-9;]*[A-Za-z]/g,Ue=1,Qe=0,d0=1,Ge=1,Rf=8,Tf=5,c0=12,l0=12,u0=30,Ef=6,Pf=4,Mf=2,f0=1e3,p0=1e4,h0=/^(https?|ftp):\/\/\S+$/;Ec=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??f0,this.painter=new ao(this.term),this.scheduler=new xc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??p0,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(nf),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(uc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(aa),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(qr(),this.term.fullscreen(!1),this.term(`
201
+ `)))}installBracketedPaste(){process.stdout.write(cc),process.stdout.write(Fy),process.stdout.write(Oy),process.stdout.write($y),process.stdout.write(fc);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(hs),process.stdout.write(Nr),process.stdout.write(Dr),process.stdout.write(Br),process.stdout.write(da),process.stdout.write(Lr),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(Ny),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(sf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>qr(),this.onProcessSignal=e=>{qr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{qr(),process.stderr.write(`
202
202
  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(`
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(Dy),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(Zi)){this.handleRawStdinSegment(n);return}if(n.includes(`
204
204
  `)){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")(`
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=eb(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=eb(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=Zi,s=oa;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=Fw(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=m0(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=_f(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(a0,""):(c=a.slice(o.start,o.end),wa(r.bodyStyle)&&(c=Qw(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(nf),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=Pc(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=g0(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)<=Rc&&Math.abs(o.y-d.y)<=Rc&&Date.now()-d.t<=xf||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<=xf&&Math.abs(e.x-r.x)<=Rc&&Math.abs(e.y-r.y)<=Rc){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}=Vw(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),!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=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}=Vw(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),!Af.test(r[a]))return null;let c=a;for(;c>0&&Af.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Af.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==="~"?zw():`${zw()}/${n.slice(2)}`);let s=Kw(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=Kw(n)?n:i0(this.sessionbar.cwd,n);if(s)return i;try{if(r0(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=s0(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)},xf);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&&jw(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"?Hy:uc))}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=Gs(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let v=wa(p.bodyStyle)?Lw(Ff(p.body),y):Ow(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()-Ue-Ge-Qe-d0-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=Ng(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 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=vt(i,f),m=s?vt(s,p):"",y=Ke(h)+(s?u+Ke(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=_f(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?Yn(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=Zw(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 v=Ke(h)+Ke(d)+Ke(m),b=Math.max(0,n-y-v),S="\u2500".repeat(b),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 v=0;v<m.length;v++){v>0&&this.term.dim(" \xB7 ");let b=m[v];if(b===void 0)continue;let 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+Ke(i)+1,y=r.split(" \xB7 ");for(let v of y){let b=Ke(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+Ke(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?_f(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Zw(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),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),k=Jw("sb",e,m,this.scrollbackHighlight,y,v)+(S?"|H":"");this.paintRow(p,k,()=>{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(Tf,this.queuedTexts.length)}chipRows(){return Math.min(Pf,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(Ef,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>Ef,h=this.completions.length-Ef+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?vt(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-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>Pf,u=this.attachments.length-Pf,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${vn(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(v0(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>Tf,p=this.queuedTexts.length-Tf,h=u===void 0?"":f?`+ ${p+1} more queued`:vt(C0(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=ws(s.buffer,n),i=Xs(r,s,Rf),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-Mf-Qe-Ge-Ue+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${vt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${vt(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(` ${vt(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}. ${vt(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 ${vt(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(` ${vt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${vt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(u0,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} ${vt(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(` ${vt(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}. ${vt(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-Mf-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=ws(s.buffer,n),i=Xs(r,s,Rf),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 Mf;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=ws(s.buffer,n);return Math.min(Rf,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(c0,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(l0,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 ${vt(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}${vt(`${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=Jw(`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=Gs(r),o=Math.max(1,n-i-1),a=wa(e.bodyStyle),c=e.ansi?y0(e.body,o):S0(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&&ys(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-Gs(e.prefix??"")),c=wa(e.bodyStyle),d=e.ansi?e.body:vt(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;Yw(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else ys(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=wa(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Qw(m)),ys(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=b0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Yw(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):ys(this.term,d,e.bodyStyle,o);if(e.fillRow){let u=e.ansi?Ke(d):Gs(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;ys(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)}};tb=/[^\x20-\x7e]/,$f=new Intl.Segmenter(void 0,{granularity:"grapheme"}),nb=!1;w0=/[a-zA-Z+\-:_!#/]/;_f=rt});function A0(t,e,n=Mc){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 ab(t,e){Mn();let n=rt(e.sessionId),s=e.importedFromMachine??"another machine",r=Ze(e.cwd),i=Mc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Mc.length*2+2,d=_n(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++,db(t,d,f,{intro:"What do you want to do?",choices:Mc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Vn({term:t,render:o,onKey:(a,c,d,l)=>{let u=R0(a,d);if(!u)return;let f=A0(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 db(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(pc(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 R0(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 cb(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=_n(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++,db(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 Mc,Lf=J(()=>{"use strict";he();Un();Hr();Mc=[{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 va(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 lb(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=va(e);return o.length<=r.length?null:o+i}var _c=J(()=>{"use strict"});import*as ub from"os";async function zr(t,e,n={}){let s=n.defaultCwd??(e?await xw(e.cwd):void 0)??ub.homedir();Mn();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=_n(t,{contentHeight:k,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(ze(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(` ${ze(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=k=>{if(!l)return;let T=k??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(T0(a,$)),d||t.bgWhite(" ")},S=()=>{if(b(),!l)return;let k=v()+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 Vn({term:t,render:y,hideCursor:!1,onKey:(k,T,$,F)=>{if(!d){if(k==="ENTER"||k==="KP_ENTER"){let j=a;d=!0,c=null,S(),ha(j).then(K=>{if(d=!1,K.ok){F({kind:"ok",path:K.path});return}c=K.reason,S()});return}if(k==="ESCAPE"){F({kind:"back"});return}if(k==="CTRL_C"||k==="CTRL_D"){F({kind:"cancel"});return}if(k==="TAB"){d=!0,Cw(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=va(j.matches);if(H.length<=j.basePrefix.length)return;K=j.prefix+H}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 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(k===""){h(),c=null,S();return}if(k==="\x1B_"||k==="\x1B"){m(),c=null,S();return}if($?.isCharacter){p(),a+=k,c=null,S();return}}}})}function T0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Bf=J(()=>{"use strict";he();Un();ff();_c();Hr()});function Df(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Hf(t,e){let n=()=>{process.stdout.write(Br),process.stdout.write(hs),process.stdout.write(Nr),process.stdout.write(Dr),process.stdout.write(eo),process.stdout.write(to),process.stdout.write(no),process.stdout.write(Lr),process.stdout.write("\x1B>")};n();let s=e.prefs??Df();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=Fc(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(B=>B.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(B=>B.interactive===!0)),P=$0(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??zi,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Ji(R,Date.now())),l=Yi(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",k=null,T=!1,$="input",F=new gs({history:[],collapsePastes:!1}),j=[],K=!1,H=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)},er=()=>{let R=X.pop();R!==void 0&&(Se.push(G),G=R)},bs=()=>{Se=[],X=[]},De=null,V=!1,xe=new gs({history:[]});e.initialPrompt&&xe.setBuffer(e.initialPrompt);let Gn=e.config.tui.promptHistoryMaxEntries;Ho(_.globalTuiHistoryFile()).then(R=>{let P=R.length>Gn?R.slice(R.length-Gn):R;xe.setHistory(P)}).catch(()=>{});let ve=new ao(t),vs=ms(t),it=rn(t),He=0,uo="",Ss=0,Et=[],on=1,ks=0,tr=0,fo=0,Jr="",_e=[],$n=1,Sa=0,nr=[],St=1,Fn=0,po=0,Yr=0,ho=()=>{vs=ms(t),it=rn(t);let R=Math.max(10,it-Nf-1);Ss=Math.max(10,it-fb);let P=Math.max(10,it-8);uo=_0(r,P);let B=xe.state();Et=ws(B.buffer,Ss);let Q=Xs(Et,B,$c);on=Q.rendered,ks=Q.windowStart,tr=Q.cursorVisualRow,fo=Q.cursorVisualCol;let ae=6+on,ue=Math.max(3,vs-ae);He=Math.min(a.length,ue),Jr=Ks(Ki,l,R,c).padEnd(R),_e=d.map(Be=>Ks(Be,l,R,c).padEnd(R))},Ce=()=>{d=a.map(R=>Ji(R,Date.now())),l=Yi(d,c),u=1+a.length,ho()},st=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>F0(P,m)):a=R,Ce(),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)),an()},lt=R=>{if(R!==void 0){let P=a.findIndex(B=>B.sessionId===R);if(P>=0){f=P+1,an();return}}f=a.length>0?1:0,p=0,an()},an=()=>{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))},dn=()=>Math.max(2,it-3),ut=!1,wt=!0,ft=!1,Vr=[],Qr=()=>{let R=dn(),P=`\u2500 ${uo} `,B=Math.max(1,R-P.length),Q="\u2500".repeat(B);(f===0||ut)&&wt?t.brightBlue.noFormat(`\u256D${P}${Q}\u256E`):t.dim.noFormat(`\u256D${P}${Q}\u256E`)},Is=()=>{let R=dn(),P="\u2500".repeat(R);(f===0||ut)&&wt?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},Gr=R=>{let P=Et[R];return P?(xe.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},Sn=R=>{let P=dn(),B=Gr(R),Q=Math.max(0,P-1-B.length),ae=" ".repeat(Q);(f===0||ut)&&wt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${B}${ae}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${B}${ae}`),t.dim.noFormat("\u2502"))},sr=R=>{let P=_e[R]??"",B=a[R],Q=B&&B.priority&&B.priority>0?"* ":" ";f===R+1&&!ut&&wt?t.brightWhite.bgBlue.noFormat(`${Q}${P}`):t.noFormat(`${Q}${P}`)},xs=()=>{let R=p,P=Math.max(0,a.length-p-He),B=[];if(s.filters.cwdOnly&&B.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Q=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;B.push({kind:"host",text:Q})}return s.filters.includeNonInteractive&&B.push({kind:"plain",text:"+non-interactive"}),R>0&&B.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&B.push({kind:"plain",text:`\u2193 ${P} below`}),B},mo=()=>{let R=xs();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},kt=R=>rt(R),cn=()=>{let R=k?`${k.sessionId}|${k.status}`:"";return["ind",S,R,G,De??"",h?`1|${m}|${a.length}`:"0",mo(),Ts?"h1":"h0",ur?"ho1":"ho0"].join("")},me=()=>{Ne(()=>{ve.paintRow(ln(),cn(),()=>{let R=()=>{Yt=null,kn=null};if(S==="confirm-kill"&&k)R(),t.brightYellow.noFormat(` kill ${kt(k.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&k)R(),k.status==="warm"?t.brightRed.noFormat(` kill + delete ${kt(k.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${kt(k.sessionId)}? [y/N]`);else if(S==="busy"&&k)R(),t.dim.noFormat(` working on ${kt(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=xs(),B=mo(),Q="Esc \xB7 Go Back",ae=Q.length,ue=5,Be=B.length,Ht=Math.max(1,it-Be-ae-ue);if(kn=null,P.length>0){t.dim.noFormat(" ");let Mt=3;for(let Ye=0;Ye<P.length;Ye++){let ht=P[Ye];Ye>0&&(t.dim.noFormat(" \xB7 "),Mt+=3),ht.kind==="host"?(kn={start:Mt,end:Mt+ht.text.length-1},ur?t.noFormat(ht.text):t.dim.noFormat(ht.text)):t.dim.noFormat(ht.text),Mt+=ht.text.length}}t.dim(" ".repeat(Ht)),Ts?t.noFormat(Q):t.dim.noFormat(Q),Yt={start:it-ue-ae+1,end:it-ue}}})})},Ae=R=>$n+1+R,rr=()=>$n+on+1,Ot=()=>$n+on+3,zt=R=>Ot()+1+(R-p),ln=()=>Ot()+1+He,Lt=()=>{let R=tr-ks;if(R<0||R>=on)return;let P=3+fo;t.moveTo(P,Ae(R))},x=()=>wt?f===0?"f":ut?"h":"u":"x",go=()=>`ct|${x()}|${dn()}|${uo}`,ka=()=>`cb|${x()}|${dn()}`,Cs=R=>`cbb|${x()}|${dn()}|${Gr(R)}`,Xr=()=>`h|${Jr}`,ir=R=>{let P=a[R],B=P&&P.priority&&P.priority>0?"* ":" ",Q=_e[R]??"";return`sr|${f===R+1&&!ut&&wt?"1":"0"}|${B}${Q}`},je=()=>{Ne(()=>{t.hideCursor(),ho(),an(),$n=1,ve.ensureSize(it,vs),ve.paintRow($n,go(),()=>{Qr()});for(let R=0;R<on;R++){let P=ks+R;ve.paintRow(Ae(R),Cs(P),()=>{Sn(P)})}ve.paintRow(rr(),ka(),()=>{Is()}),ve.paintRow(rr()+1,"blank",()=>{}),ve.paintRow(Ot(),Xr(),()=>{t.dim.noFormat(` ${Jr}`)});for(let R=0;R<He;R++){let P=p+R,B=Ot()+1+R;P<a.length?ve.paintRow(B,ir(P),()=>{sr(P)}):ve.paintRow(B,"blank",()=>{})}me();for(let R=ln()+1;R<=vs;R++)ve.paintRow(R,"blank",()=>{});f===0&&(Lt(),t.hideCursor(!1))})},Xn=()=>{ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),je()},yo=()=>{Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
209
209
 
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)(`
210
+ `);for(let R of M0){if(R===null){t(`
211
+ `);continue}let[P,B]=R;t.brightCyan.noFormat(` ${P.padEnd(P0)}`),t.noFormat(B)(`
212
212
  `)}t(`
213
213
  `),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)}`)(`
214
+ `)})},Kt=()=>St+4,Bc=2,ot=0,Bt=()=>{vs=ms(t);let R=Math.max(2,vs-(St+3)-Bc);return Math.max(1,Math.floor(R/2))},wo=()=>{let R=Bt();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)},Ia=R=>{it=rn(t);let P=Math.max(2,it-3),B="\u2500 Find sessions ",Q="\u2500".repeat(Math.max(1,P-B.length));R?t.brightBlue.noFormat(`\u256D${B}${Q}\u256E`):t.dim.noFormat(`\u256D${B}${Q}\u256E`),t.styleReset()},or=()=>{it=rn(t),Sa=Math.max(10,it-fb);let R=F.state();nr=ws(R.buffer,Sa);let P=Xs(nr,R,E0);St=P.rendered,Fn=P.windowStart,po=P.cursorVisualRow,Yr=P.cursorVisualCol},bo=(R,P)=>{it=rn(t);let B=Math.max(2,it-3),Q=nr[R],ae="";Q&&(ae=(F.state().buffer[Q.bufferIdx]??"").slice(Q.startCol,Q.endCol));let ue=Math.max(0,B-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()},xa=R=>{it=rn(t);let P=Math.max(2,it-3),B="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${B}\u256F`):t.dim.noFormat(`\u2570${B}\u256F`),t.styleReset()},ar=()=>3+Yr,dr=()=>2+(po-Fn),Nt=()=>{let R=$==="input";Ne(()=>{R&&t.hideCursor(),t.moveTo(1,1),Ia(R);for(let P=0;P<St;P++)t.moveTo(1,2+P),bo(Fn+P,R);t.moveTo(1,2+St),xa(R),R&&(t.moveTo(ar(),dr()),t.hideCursor(!1))})},pt=()=>{Ne(()=>{t.hideCursor();for(let R=0;R<St;R++)t.moveTo(1,2+R),bo(Fn+R,!0);t.moveTo(ar(),dr()),t.hideCursor(!1)})},Nc={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},vo=(R,P)=>{let B=j[R];if(!B)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Q=rn(t),ae=Math.max(20,Q-Nf),ue=rt(B.sessionId),Be=B.title??Ze(B.cwd),Ht=P&&B.snippets.length>1?` [${L+1}/${B.snippets.length}]`:P&&B.totalMatches>B.snippets.length?` [${B.snippets.length} of ${B.totalMatches}]`:"",Mt=`${ue} ${B.status==="warm"?"warm":"cold"}`,Ye=Math.max(5,ae-Mt.length-Ht.length-2),ht=sa(Be,Ye),fn=`${Mt} ${ht}${Ht}`.padEnd(ae),bt=B.snippets[P?L:0],qe=bt?Nc[bt.kind]??bt.kind:"",In=bt?.toolName?`${qe} \xB7 ${bt.toolName}`:qe,ri=Math.max(10,ae-In.length-6),xn=bt?sa(bt.text,ri):"",fr=bt?` ${In} ${xn}`:" (no snippet)";return{rowBudget:ae,line1:fn,line2:fr.padEnd(ae+Nf),focusedRow:P}},cr=(R,P)=>{let{line1:B,focusedRow:Q}=vo(R,P);Q?t.brightWhite.bgBlue.noFormat(`\u276F ${B}`):t.noFormat(` ${B}`),t.styleReset()},Zn=(R,P)=>{let{line2:B}=vo(R,P);t.dim.noFormat(B),t.styleReset()},As=()=>{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($==="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":"",B=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${B}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},es=()=>{or();let R=$==="input",P=F.state().buffer.join(`
215
+ `);Ne(()=>{t.hideCursor(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ia(R);for(let Q=0;Q<St;Q++)t.moveTo(1,2+Q),bo(Fn+Q,R);t.moveTo(1,2+St),xa(R);let B=j.length;if(B===0)t.moveTo(1,Kt()),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,Kt()+1),As();else{wo();let Q=Bt(),ae=$!=="input";for(let ue=0;ue<Q;ue++){let Be=ot+ue;t.moveTo(1,Kt()+ue*2),Be<B?cr(Be,ae&&Be===H):t.eraseLineAfter(),t.moveTo(1,Kt()+ue*2+1),Be<B?Zn(Be,ae&&Be===H):t.eraseLineAfter()}t.moveTo(1,Kt()+Q*2),As()}R&&(t.moveTo(ar(),dr()),t.hideCursor(!1))})},Rs=(R,P)=>{let B=R-ot;B<0||B>=Bt()||Ne(()=>{t.moveTo(1,Kt()+B*2),cr(R,P),t.moveTo(1,Kt()+B*2+1),Zn(R,P)})},lr=()=>{Ne(()=>{t.moveTo(1,Kt()+Bt()*2),As()})},Zr=()=>{Ne(()=>{let R=Bt(),P=j.length,B=$!=="input";for(let Q=0;Q<R;Q++){let ae=ot+Q;t.moveTo(1,Kt()+Q*2),ae<P?cr(ae,B&&ae===H):t.eraseLineAfter(),t.moveTo(1,Kt()+Q*2+1),ae<P?Zn(ae,B&&ae===H):t.eraseLineAfter()}t.moveTo(1,Kt()+R*2),As()})},So=()=>F.state().buffer.join(`
216
+ `),Dc=R=>{let P=St;F.feed({type:"paste",text:R}),or(),St!==P?es():pt()},Hc=async()=>{let R=So().trim();if(R.length!==0){if(a.length===0){N="no sessions in view to search",es();return}Z=!0,N=null,es();try{let P=await Lg(e.target,R,{sessionIds:a.map(B=>B.sessionId)});j=P.results,K=P.truncated,H=0,L=0,ot=0,$=P.results.length>0?"results":"input",or()}catch(P){N=`search failed: ${P.message}`}finally{Z=!1,es()}}},ts=()=>{},Dt=()=>{Ne(()=>{let R=f===0;R&&t.hideCursor(),ve.paintRow($n,go(),()=>{Qr()}),ve.paintRow(rr(),ka(),()=>{Is()});for(let P=0;P<on;P++){let B=ks+P;ve.paintRow(Ae(P),Cs(B),()=>{Sn(B)})}R&&(Lt(),t.hideCursor(!1))})},un=()=>{Ne(()=>{let R=xe.state();Et=ws(R.buffer,Ss);let P=Xs(Et,R,$c);ks=P.windowStart,tr=P.cursorVisualRow,fo=P.cursorVisualCol;let B=f===0;B&&t.hideCursor();for(let Q=0;Q<on;Q++){let ae=ks+Q;ve.paintRow(Ae(Q),Cs(ae),()=>{Sn(ae)})}B&&(Lt(),t.hideCursor(!1))})},ei=R=>{R<p||R>=p+He||Ne(()=>{ve.paintRow(zt(R),ir(R),()=>{sr(R)})})},Pt=()=>{Ne(()=>{for(let R=0;R<He;R++){let P=Ot()+1+R,B=p+R;B<a.length?ve.paintRow(P,ir(B),()=>{sr(B)}):ve.paintRow(P,"blank",()=>{})}me()})},On=()=>{Ne(()=>{ve.paintRow(Ot(),Xr(),()=>{t.dim.noFormat(` ${Jr}`)});for(let R=0;R<He;R++){let P=Ot()+1+R,B=p+R;B<a.length?ve.paintRow(P,ir(B),()=>{sr(B)}):ve.paintRow(P,"blank",()=>{})}me(),f===0&&(Lt(),t.hideCursor(!1))})},Jt=!1,ns="",ti=0,Ca=200,ss=null,ni=!1,Yt=null,Ts=!1,kn=null,ur=!1,Vt=null,ko=null,Aa=null,si=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=wt;wt=ue===Q,wt&&(ti=Date.now()),Be!==wt&&!ft&&Vr.length<=1&&Ne(()=>{Dt(),Pt()}),P=P.slice(0,ue)+P.slice(ue+"\x1B[I".length)}if(P.length===0)return}if(!Jt&&P===""&&ko){ko();return}if(!Jt&&(P===""||P==="\x1B_"||P==="\x1B")){Aa?.(P);return}if(Jt){let Q=P.indexOf(oa);if(Q===-1){ns+=P;return}ns+=P.slice(0,Q),Jt=!1;let ae=Buffer.from(ns,"binary").toString("utf-8").replace(/\r\n?/g,`
217
+ `);ns="";let ue=P.slice(Q+oa.length);if(T)$==="input"&&!Z&&Dc(ae);else if(f===0&&!h){xe.feed({type:"paste",text:ae});let Be=xe.state(),Ht=ws(Be.buffer,Ss);Xs(Ht,Be,$c).rendered!==on?je():un()}ue.length>0&&Vt&&Vt(Buffer.from(ue,"binary"));return}let B=P.indexOf(Zi);if(B===-1){Vt?.(R);return}B>0&&Vt?.(Buffer.from(P.slice(0,B),"binary")),P=P.slice(B+Zi.length),Jt=!0,P.length>0&&si(Buffer.from(P,"binary"))};return je(),await new Promise(R=>{let P=null,B=!1,Q=null,ae=!1,ue=Vr,Be=E=>{ue.push(E)},Ht=()=>{ue.pop(),ft||ue[ue.length-1]?.onResize()},Mt={push:Be,pop:Ht},Ye=()=>({kind:"new",cwd:r}),ht=async()=>{Ps(),ve.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Be({onKey:()=>{},onResize:()=>{}});let U;try{U=await zr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Ht(),Ln()}U.kind==="ok"&&U.path!==r&&(r=U.path,i=Fc(i,r),st()),ft||je()};ts=()=>{F=new gs({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,ot=0,N=null,Z=!1,$="input",T=!1,Ht()};let fn=(E,U,ie)=>{ri(),ue[ue.length-1]?.onKey(E,U,ie)},bt=()=>{ft||ue[ue.length-1]?.onResize()};Aa=E=>{ft||ue[ue.length-1]?.onKey(E,null,{})};let qe=()=>{if(ft)return;ft=!0,ue.length=0,P&&(clearInterval(P),P=null),Q&&(Q.abort(),Q=null,B=!1),t.off("key",fn),t.off("mouse",as),t.off("resize",bt),process.stdout.write(hs),process.stdout.write(da);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",si),E.stdin.on("data",Vt),Vt=null),Jt=!1,ns="",t.grabInput(!1),se({src:"grab",site:"picker.cleanup",on:!1}),t.hideCursor(!1),t.moveTo(1,ln()+1),t(`
218
+ `)},In=()=>{if(ft||ue.length>1||S!=="normal"||h||ae)return;B&&Q&&(Q.abort(),Q=null,B=!1);let E=f>0?a[f-1]?.sessionId:void 0;B=!0;let U=new AbortController;Q=U,Es(E,{silent:!0,signal:U.signal}).finally(()=>{Q===U&&(Q=null),B=!1})},ri=()=>{ft||(P&&clearInterval(P),P=setInterval(In,3e3))},xn=()=>(qe(),R({kind:V?"exit":"abort"}),!0),fr=()=>{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}:${De??""}
220
+ ${E}`},Es=async(E,U={})=>{try{let ie=U.silent?fr():"",W=u,te=await Kn(e.target,{includeNonInteractive:!0,signal:U.signal}),re=E??(f>0?a[f-1]?.sessionId:void 0);if(i=Fc(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)),an(),U.silent&&fr()===ie)return;u===W?On():je()}catch(ie){if(U.silent)return;De=`refresh failed: ${ie.message}`,je()}},Ra=async E=>{if(!k)return;let U=k;S="busy",me();try{await $g(e.target,U.sessionId,E),S="normal",k=null,G="",await Es(U.sessionId)}catch(ie){S="normal",k=null,G="",De=`rename failed: ${ie.message}`,me()}},Io=async E=>{try{await Og(e.target,E.sessionId),De="title regen queued (press r to refresh)",me()}catch(U){De=`regen failed: ${U.message}`,me()}},mt=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=Fc(i,r),st(),lt(te),je(),De=W>0?"priority: high":"priority: normal",me();try{await Fg(e.target,E.sessionId,ie)}catch(re){De=`priority failed: ${re.message}`,me()}},rs=async()=>{if(ae)return;ae=!0;let E=f>0?a[f-1]?.sessionId:void 0;De="syncing agents\u2026",me();try{let{synced:U,skipped:ie,agents:W}=await _g(e.target);await Es(E),De=`synced ${U} new (${ie} known) from ${W} agent${W===1?"":"s"}`,me()}catch(U){De=`sync failed: ${U.message}`,me()}finally{ae=!1}},is=async E=>{if(!k)return;let U=k;S="busy",me();try{E==="kill"?await Jn(e.target,U.sessionId):await Bg(e.target,U.sessionId),S="normal",k=null,U.sessionId===e.currentSessionId&&(V=!0);let ie;if(E==="kill")ie=U.sessionId;else{let W=a.findIndex(te=>te.sessionId===U.sessionId);W>=0&&(ie=a[W+1]?.sessionId??a[W-1]?.sessionId)}await Es(ie)}catch(ie){S="normal",k=null,De=`${E} failed: ${ie.message}`,me()}},Cn=(E,U)=>{E===0!=(U===0)&&(Dt(),U===0?(t.hideCursor(!1),Lt()):t.hideCursor())},at=E=>{let U=Math.min(u-1,Math.max(0,f+E));if(U===f)return;let ie=f;f=U,an(),Ne(()=>{Pt(),Cn(ie,f)})},pr=()=>De===null?!1:(De=null,me(),!0),An=()=>{yo(),Be({onKey:E=>{if(E==="CTRL_C"){qe(),R({kind:"abort"});return}Ht()},onResize:()=>yo()})},os=E=>{let U=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
221
 
222
222
  `),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}`)(`
223
+ `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
224
+ `);else if(U!==null)for(let We of U)t.noFormat(` ${We}`)(`
225
225
  `);t(`
226
226
  `),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(`
227
+ `)})};te();let re=new AbortController,ke={onKey:We=>{if(We==="ESCAPE"||We==="CTRL_C"){re.abort(),Ht();return}},onResize:()=>te()};Be(ke),(async()=>{try{let We=await sn(`${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(),dt=Pn(Xe),Re=qu(dt,E.status);U=sc(Re,!1).replace(/\n$/,"").split(`
228
+ `)}catch(We){if(re.signal.aborted)return;ie=`failed to load info: ${We.message}`}finally{W=!1,!ft&&ue[ue.length-1]===ke&&te()}})()},hr=()=>{if(a.length===0){De="no sessions to search",me();return}F=new gs({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,ot=0,N=null,Z=!1,$="input",T=!0,or(),es(),Be({onKey:(U,ie,W)=>{if($==="input"){if(Z)return;if(U==="ESCAPE"||U==="CTRL_C"){ts();return}if(U==="ENTER"||U==="KP_ENTER"){if(So().trim().length===0)return;Hc();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&j.length>0){$="results",H=0,L=0,Ne(()=>{Nt(),Rs(0,!0),lr(),t.hideCursor()});return}let te=F.state(),re=null;if(U==="")re={type:"key",name:"ctrl-underscore"};else if(U==="\x1B_"||U==="\x1B")re={type:"key",name:"alt-underscore"};else if(W?.isCharacter)re={type:"char",ch:U};else{let dt=Pc(U);dt!==null&&(re={type:"key",name:dt})}if(re===null){t.moveTo(ar(),dr());return}F.feed(re);let ke=F.state();if(te.buffer.length===ke.buffer.length&&te.buffer.every((dt,Re)=>dt===ke.buffer[Re])&&te.row===ke.row&&te.col===ke.col){t.moveTo(ar(),dr());return}let Xe=St;or(),St!==Xe?es():pt();return}if($==="results"){if(U==="ESCAPE"||U==="CTRL_C"){ts();return}if(U==="CTRL_F"){$="input",Zr(),lr(),Nt();return}if(U==="ENTER"||U==="KP_ENTER"){let re=j[H];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 cb(t,{sessionId:re.sessionId,title:re.title,cwd:re.cwd},Mt);if(Xe==="cancel"){qe(),R({kind:"abort"});return}if(Xe==="back")return;qe();let dt={kind:"attach",sessionId:re.sessionId,readonly:Xe==="view"};ke?.agentId!==void 0&&(dt.agentId=ke.agentId),R(dt)})();return}if(W?.isCharacter&&(U==="n"||U==="N")){let re=j[H];if(!re||re.snippets.length<=1)return;L=(L+1)%re.snippets.length,Rs(H,!0);return}if(W?.isCharacter&&(U==="p"||U==="P")){let re=j[H];if(!re||re.snippets.length<=1)return;L=(L-1+re.snippets.length)%re.snippets.length,Rs(H,!0);return}let te=re=>{if(re<0&&H===0){$="input",Ne(()=>{Rs(0,!1),lr(),Nt()});return}let ke=Math.min(j.length-1,Math.max(0,H+re));if(ke===H)return;let We=H,Xe=ot;H=ke,L=0,wo(),ot!==Xe?Zr():(Ne(()=>{Rs(We,!1),Rs(H,!0)}),lr())};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(-Bt());return;case"PAGE_DOWN":te(Bt());return;case"HOME":te(-H);return;case"END":te(j.length);return}return}},onResize:()=>es()})},ii=(E,U,ie)=>{if(S!=="busy"){if(E==="CTRL_O"){ht();return}if(E==="CTRL_L"){Xn();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}Ra(W);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",k=null,G="",bs(),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"){er(),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")){is(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(pr(),E==="CTRL_F"&&f!==0){hr();return}if(f===0&&!h){if(E==="ESCAPE"){xn();return}if(E==="ENTER"||E==="KP_ENTER"){qe();let Re=xe.expandedText(),It=Ye();Re.trim().length>0&&(It.prompt=Re),R(It);return}if(E==="UP"&&v){let Re=Date.now(),It=Re-b;if(b=Re,It<y){Lt();return}v=!1}if(E==="DOWN"){let Re=xe.state(),It=Re.historyIndex!==-1||Re.queueIndex!==-1,Ut=Et.length===0||tr===Et.length-1;if(!It&&Ut&&a.length>0){at(1);return}}if(E==="PAGE_DOWN"&&(Et.length===0||tr===Et.length-1)&&a.length>0){at(1);return}if(E==="CTRL_P"){a.length>0&&at(1);return}v=!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=Pc(E);Re!==null&&(te={type:"key",name:Re})}if(te===null){Lt();return}let re=xe.feed(te),ke=xe.state(),We=W.buffer.length===ke.buffer.length&&W.buffer.every((Re,It)=>Re===ke.buffer[It])&&W.row===ke.row&&W.col===ke.col;if(re.some(Re=>Re.type==="exit")){xn();return}if(We){Lt();return}let Xe=ws(ke.buffer,Ss);if(Xs(Xe,ke,$c).rendered!==on){je();return}un();return}if(!h&&ie?.isCharacter&&E==="?"){An();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"){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=Ye();W?.cwd&&(te.cwd=W.cwd),qe(),R(te);return}if(E==="q"||E==="Q"){xn();return}if(E==="o"||E==="O"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,st(),lt(W),je();return}if(E==="h"||E==="H"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=pb(s.filters.hostFilter,i),st(),lt(W),je();return}if(E==="i"&&f>0){let W=a[f-1];if(!W)return;os(W);return}if(E==="I"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,st(),lt(W),je();return}if(E==="r"||E==="R"){let W=f>0?a[f-1]?.sessionId:void 0;Es(W);return}if(E==="s"||E==="S"){rs();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;Io({sessionId:W.sessionId});return}if(E==="*"&&f>0){let W=a[f-1];if(!W)return;mt(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}ut=!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&&(v=!0),b=Date.now()),at(-1);return;case"DOWN":case"TAB":case"CTRL_N":at(1);return;case"PAGE_UP":at(-He);return;case"PAGE_DOWN":at(He);return;case"HOME":at(1-f);return;case"END":at(u);return;case"RIGHT":if(ut||f===0)break;case"ENTER":case"KP_ENTER":{if(ut){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":xn();return}}};Be({onKey:(E,U,ie)=>ii(E,U,ie),onResize:()=>{ft||je()}});let as=(E,U)=>{if(ft||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=wt&&Date.now()-ti<Ca,Xe=!wt||We;if(W){ss={x:U?.x??-1,y:U?.y??-1},ni=Xe;return}if(ie&&Xe)return;let dt=te&&ss!==null&&U?.x===ss.x&&U?.y===ss.y,Re=dt&&!ni,It=dt&&ni;if(te&&(ss=null,ni=!1,!dt))return;if(re||ke){if(a.length===0)return;let $e=re?-3:3,ds=Math.max(0,a.length-He),_s=Math.min(ds,Math.max(0,p+$e));if(_s===p)return;if(p=_s,f>0){let jt=f-1;jt<p?f=p+1:jt>=p+He&&(f=p+He)}Pt();return}if(!ie&&!Re)return;let Ut=U?.y;if(typeof Ut!="number")return;{let $e=U?.x,ds=Yt!==null&&Ut===ln()&&typeof $e=="number"&&$e>=Yt.start&&$e<=Yt.end,_s=kn!==null&&Ut===ln()&&typeof $e=="number"&&$e>=kn.start&&$e<=kn.end;(ds!==Ts||_s!==ur)&&(Ts=ds,ur=_s,me(),f===0?(Lt(),t.hideCursor(!1)):t.hideCursor(!0))}if(Re&&Yt!==null&&Ut===ln()){let $e=U?.x;if(typeof $e=="number"&&$e>=Yt.start&&$e<=Yt.end){xn();return}}if(Re&&kn!==null&&Ut===ln()){let $e=U?.x;if(typeof $e=="number"&&$e>=kn.start&&$e<=kn.end){let ds=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=pb(s.filters.hostFilter,i),st(),lt(ds),je();return}}if(Ut>=$n&&Ut<=rr()){if((Re||It)&&f!==0){ut=!1;let $e=f;f=0,Ne(()=>{Pt(),Cn($e,f)});return}ie&&!ut&&f!==0&&(ut=!0,Ne(()=>{Dt(),Pt()}));return}ut&&(ut=!1,Ne(()=>{Dt(),Pt()}));let pn=Ot()+1,Ms=pn+He-1;if(Ut<pn||Ut>Ms)return;let hn=p+(Ut-pn);if(hn<0||hn>=a.length)return;let mr=a[hn];if(!mr)return;let gr=hn+1;if(ie&&f===0)return;let Uc=f===0,jc=f===gr;if(It&&f!==gr){let $e=f;f=gr,an(),Ne(()=>{Pt(),Cn($e,f)});return}if(It)return;if(f!==gr){let $e=f;f=gr,an(),Ne(()=>{Pt(),Cn($e,f)})}if(!Re||Uc||!jc)return;qe();let Ta={kind:"attach",sessionId:mr.sessionId};mr.agentId!==void 0&&(Ta.agentId=mr.agentId),R(Ta)},Ln=()=>{t.grabInput({mouse:"motion"}),se({src:"grab",site:"picker.installGrab",on:!0});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Vt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",si),process.stdout.write(cc),process.stdout.write(fc)),t.on("key",fn),t.on("mouse",as),t.on("resize",bt)},Ps=()=>{process.stdout.write(hs),process.stdout.write(da);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",si),E.stdin.on("data",Vt),Vt=null),Jt=!1,ns="",t.off("key",fn),t.off("mouse",as),t.off("resize",bt),t.grabInput(!1),se({src:"grab",site:"picker.uninstallGrab",on:!1}),t.hideCursor(!1)};if(Ln(),process.platform!=="win32"){let E=!1,U=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),Ln(),ft||Xn())};ko=()=>{E||ft||(E=!0,Ps(),t.fullscreen(!1),process.stdout.write(`${aa}${lc}
229
+ `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(In,3e3)})}function _0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+sa(Ze(t),s)}function Fc(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 $0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function pb(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 F0(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 Nf,$c,E0,fb,P0,M0,hb=J(()=>{"use strict";Xd();he();Un();na();fd();gf();Of();Lf();Bf();Hr();yf();If();ca();Tr();Wu();Ir();Nf=2,$c=4,E0=4,fb=4,P0=20,M0=[["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 N0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Uf(t,e,n,s){Mn();let r=N0(e,n??O0),i=0,o=()=>{let u=ms(t)-8;return Math.max(1,Math.min(L0,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(B0,Math.max(40,rn(t)-8)),h=_n(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 k=e[S];if(!k)continue;let T=S===r?"\u276F":" ",$=k.description??k.name,F=` ${T} ${k.id}`;if(t.moveTo(h.contentX,h.contentY+y),S===r){let j=`${F} ${$}`;t.brightWhite.bgBlue.noFormat(pc(ze(j,m),m))}else{t.noFormat(F);let j=m-F.length-2;j>1&&t.dim.noFormat(` ${ze($,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 Vn({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 O0,L0,B0,mb=J(()=>{"use strict";Hr();O0="opencode",L0=20,B0=88});import D0 from"wrap-ansi";async function gb(t,e,n,s){Mn();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=rn(t),l=ms(t),u=Math.min(H0,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>D0(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=_n(t,{contentHeight:v,contentWidth:u,title:"Agent failed to start"}),S=b.contentW,k=0;t.moveTo(b.contentX,b.contentY+k),t.brightWhite.bold.noFormat(ze(` ${i}`,S)),k+=2;for(let T of y)t.moveTo(b.contentX,b.contentY+k),t.brightRed.noFormat(ze(` ${T}`,S)),k++;return m&&(t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(ze(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),k++),k++,t.moveTo(b.contentX,b.contentY+k),t.dim.noFormat(ze(` ${a}`,S)),b};return Vn({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 H0,yb=J(()=>{"use strict";Hr();H0=100});import*as bb from"fs";import*as vb from"os";import*as Oc from"path";function Sb(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 U0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function j0(t){return t.replace(/\\ /g," ")}function wb(t){return t.replace(/ /g,"\\ ")}function q0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function W0(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=vb.homedir()+n.slice(1)),Oc.isAbsolute(n)?n:Oc.resolve(e,n)}function z0(t){let e;try{e=bb.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function kb(t,e,n=z0){if(!U0(t))return null;let s=j0(t),{dirPrefix:r,base:i}=q0(s),o=W0(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:wb(r+p),candidates:l}}let u=va(d.map(f=>f.name));return{replacement:wb(r+u),candidates:l}}var Ib=J(()=>{"use strict";_c()});function xb(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 Cb(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Ab(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 Rb=J(()=>{"use strict"});import{readFileSync as K0}from"fs";import{nanoid as Tb}from"nanoid";import J0 from"terminal-kit";import jf from"fs/promises";import Kr from"path";function Y0(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function V0(t){let e=Lc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function Q0(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 Lc(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 G0(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function X0(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=Lc(o.representative),d=e[a]??0,l=n[a]?Wf:c[d]??c[0]??"";return{label:G0(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 Z0(t,e,n){return t===Wf?{type:"dismiss",method:Tw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:Rw,params:{sessionId:n,questionId:e.id,answer:t}}}function eT(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]?Wf:Lc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=Z0(c,l,r);u!==null&&i.push(u)}}return i}function tT(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=Lc(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:eT(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function Eb(t){if(!Array.isArray(t))return;let e=Wn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function qf(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 rT(t,e){e.has(t)?e.delete(t):e.add(t)}function iT(){if(Pb)return;Pb=!0;let t=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{se({src:"uncaughtException",stack:t(e)}),qr(),process.stderr.write(`
232
232
  uncaught: ${t(e)}
233
- `),process.exit(1)}),process.on("unhandledRejection",e=>{st({src:"unhandledRejection",stack:t(e)}),jr(),process.stderr.write(`
233
+ `),process.exit(1)}),process.on("unhandledRejection",e=>{se({src:"unhandledRejection",stack:t(e)}),qr(),process.stderr.write(`
234
234
  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(`
235
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&se({src:"process-exit",code:e})})}async function $b(t){iT();let e=await be(),n=t.target??await _t(e);Mp(e.tui.logMaxBytes),n.isLocal&&!t.target&&await Ws(e);let s=J0.terminal;ob(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:op(e),defaultEnterAction:e.tui.defaultEnterAction,...t.agentId?{lastChosenAgent:t.agentId}:{}},o=Df(),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 aT(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await ua();if(f&&process.stderr.write(`\u2728 ${fa(f)}
237
+ `),process.stdout.isTTY){let p=await Mr(e);if(p?.version!==void 0){let h=p.version!==fe,m=Hs(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let v=h?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",b=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(b(`! ${v} \u2014 run \`${Bn()} daemon restart\` to apply.`)+`
238
+ `)}}}if(r.sessionId&&process.stdout.isTTY){let p=rt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Bn()} --session ${p}${h}
239
+ `)}}function oT(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 N=0;N<K;N++){let Z=e[N];if(Z===void 0)continue;let G=n.get(Z);G&&!Nu(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 ${Yn(h)}`:`stopped (${m}) \xB7 ${Yn(h)}`,b;if(c===0)m!==null?b=v:b=f?`thinking \xB7 ${Yn(h)}`:`thought \xB7 ${Yn(h)}`;else{let K=c===1?"tool":"tools",H=m!==null?v:f?Yn(h):`took ${Yn(h)}`,L=[`${c} ${K}`,H];f&&d&&u>0&&L.push(`${u} hidden`),b=L.join(" \xB7 ")}let S=c===0&&f,k=y?"tool-status-cancelled":"tool-status-fail",F=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?k:"tool",body:b,bodyStyle:S?"tool-status-running":m!==null?k:"dim"}],j=[null];for(let K of l){let H=n.get(K);if(H){let L=ia(H,p);for(let N of L)N.hoverSubKey=K;if(F.push(...L),j.push(...L.map(()=>K)),o?.has(K)){let N=ry(H);for(let Z of N)Z.hoverSubKey=K;F.push(...N),j.push(...N.map(()=>K))}}}return{lines:F,rowOwners:j}}async function aT(t,e,n,s,r,i,o){let a=await dT(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=lT(t,c);d.write(c);let l=n.isLocal?async()=>(await _t(await be())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new ro({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 qt(h);await h.start(),m.onNotification(Qa,g=>{let w=ph.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],v=null,b=!1,S=!1,k=(g,w)=>{g&&(v?v(g,w):y.push({event:g,rawUpdate:w}))},T,$=g=>{g!==T&&(T=g,g!==void 0&&x.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},F=null,j=null,K=!1,H=0,L=0,N=!1,Z=!1,G,Se=null,X=null,ce=null,Je=null,er=()=>setInterval(()=>{if(Se===null||V===null)return;let g=Je===null?0:Date.now()-Je;V.setBanner({elapsedMs:Date.now()-Se,stalled:g>=nT}),jt()},1e3),bs=!1,De=g=>{let w=L;L=Math.max(0,L+g);let I=typeof V<"u"&&V!==null;w===0&&L>0?(Z=!1,Se=Date.now(),Je=Date.now(),xe?.setTurnRunning(!0),I&&V.setBanner({status:"busy",elapsedMs:0,stalled:!1}),X===null&&I&&(X=er())):w>0&&L===0?(Z=!1,Se=null,Je=null,xe?.setTurnRunning(!1),X!==null&&(clearInterval(X),X=null),I&&V.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&Z&&(Z=!1,I&&V.setBanner({status:"busy",stalled:!1}))},V=null,xe=null,Gn,ve=null,vs=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=Wn(w,{cwd:lt});cT(w,I),Je=Date.now();let A=w?.sessionUpdate;if(typeof A=="string"&&!vs.has(A)){let C=w??{};typeof C.messageId=="string"&&(Gn=C.messageId)}if(A==="prompt_received"?De(1):I?.kind==="turn-complete"&&(De(-1),K=!0),A==="permission_resolved"){Jr(w);return}if(A==="hydra_compaction"){ks(w);return}if(A==="clarifier_question_asked"){let C=w,M=typeof C.question?.question=="string"?C.question.question:"",D=M.length>50?M.slice(0,49)+"\u2026":M;x.notify(D?`new question: ${D} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}A==="clarifier_question_answered"||A==="clarifier_question_dismissed"||(k(I,w),Sa(w))};m.onNotification("session/update",g=>{if(!b){if(ve!==null){ve.push(g);return}it(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(b)return;L>0&&De(-L),typeof V<"u"&&V!==null&&V.setBanner({status:"cold",elapsedMs:void 0})});let He=new Map,uo=200,Ss=0,Et=!1,on=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 A=w.messageId,C=w.prompt,M=setTimeout(()=>{b||(He.delete(A),Ye.set(A,Mt(A,C)),V&&xe&&In())},uo);He.set(A,M)}else Ye.set(w.messageId,Mt(w.messageId,w.prompt)),V&&xe&&In();if(dn!==void 0&&w.originator?.clientId===dn){let A=ht.shift();A&&(A.messageId=w.messageId,fn.set(w.messageId,A))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(b)return;let w=g??{};if(typeof w.messageId!="string"||!Ye.has(w.messageId))return;Ye.set(w.messageId,Mt(w.messageId,w.prompt));let I=fn.get(w.messageId);if(I){let A=Array.isArray(w.prompt)?w.prompt:[],C="",M=[];for(let D of A){if(!D||typeof D!="object")continue;let O=D;O.type==="text"&&typeof O.text=="string"?C+=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=C,I.attachments=M}V&&xe&&In()}),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=He.get(w.messageId);I!==void 0&&(clearTimeout(I),He.delete(w.messageId)),Ye.delete(w.messageId)&&V&&xe&&In();let C=fn.get(w.messageId);C&&(fn.delete(w.messageId),w.reason==="started"&&(C.flushed=!0,k({kind:"user-text",text:C.displayText,attachments:C.attachments}),qe=C))}),m.onNotification("hydra-acp/cancel_failed",g=>{if(b)return;let w=g??{};if(!(typeof V<"u"&&V!==null))return;Ss=Date.now(),Et=!0;let A=typeof w.code=="number"?` (${w.code})`:"",C=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${A}${C} \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;bt.add(I),qe!==null&&qe.messageId!==void 0&&qe.messageId===I&&(k({kind:"turn-complete",stopReason:"cancelled",amended:!0}),qe=null,bt.delete(I))});let ks=g=>{let w=g??{},I=typeof w.phase=="string"?w.phase:void 0;if(I==="started")x.setCompactionIndicator("compacting...");else if(I==="iteration")x.setCompactionIndicator("compacting...");else if(I==="deferred")x.setCompactionIndicator("compaction queued (waiting for idle)");else if(I==="swapped")x.setCompactionIndicator(null),x.notify("compacted",2e3);else if(I==="rolled_back")x.setCompactionIndicator(null),x.notify("rolled back",2e3);else if(I==="failed"){x.setCompactionIndicator(null);let A=typeof w.error=="string"?w.error:"unknown error",C=A.length>40?A.slice(0,40)+"...":A;x.notify(`compaction failed: ${C}`,5e3)}},tr=()=>{ce===null&&(ce=setInterval(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ce)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(x.setSynthesisIndicator(null),x.notify("synthesis complete",2e3),ce!==null&&(clearInterval(ce),ce=null)):w.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3),ce!==null&&(clearInterval(ce),ce=null))}catch{}},5e3))},fo=()=>{ce!==null&&(clearInterval(ce),ce=null)},Jr=g=>{let w=g??{},I=typeof w.toolCallId=="string"?w.toolCallId:void 0,A;w.outcome&&typeof w.outcome=="object"?A=w.outcome:typeof w.chosenOptionId=="string"&&(A={kind:"selected",optionId:w.chosenOptionId}),$n(I,A?{outcome:A}:void 0)},_e=null,$n=(g,w)=>{if(!_e||_e.toolCallId&&g&&_e.toolCallId!==g)return;let I=_e.resolve;_e=null,x.setPermissionPrompt(null),I(w??{outcome:{outcome:"cancelled"}})},Sa=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"||$n(w.toolCallId,void 0))},nr=()=>{if(!_e){x.setPermissionPrompt(null);return}x.setPermissionPrompt({title:_e.title,detail:_e.detail,options:_e.options.map(g=>({label:g.name})),selectedIndex:_e.selectedIndex})},St=g=>{if(!_e)return;let{options:w,resolve:I}=_e;if(_e=null,x.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 Ur(g);let w=g??{},A=(Array.isArray(w.options)?w.options:[]).map(Y=>({optionId:Y.optionId,name:Ee(Y.name??""),...Y.kind!==void 0?{kind:Y.kind}:{}})),C=w.toolCall?.title??w.toolCall?.name??"tool",M=Ee(C),D=Ee(sw(nw(g))),O=w.toolCall?.toolCallId;return A.length===0?(x.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${M} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Y=>{_e={title:M,detail:D,options:A,selectedIndex:0,resolve:Y,toolCallId:O},nr()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Fn,po,Yr=!0,ho=!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}});po=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(Yr=!1),ho=Zt(g?._meta??void 0).prompt?.amending===!0}catch{}let Ce=a.sessionId,st=a.agentId,lt=a.cwd,an,dn,ut,wt,ft,Vr,Qr,Is,Gr,Sn,sr=!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 Jy({request:()=>m.request("session/new",w),showBanner:(M,D,O)=>Yy(t,M,D,O,{authenticate:Y=>m.request("authenticate",{methodId:Y})}),resolveOnboarding:async M=>{if(M)try{return(await Jd(n)).find(Y=>Y.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(M){t.grabInput(!1),se({src:"grab",site:"runSession.session-new-failed",on:!1}),h.close().catch(()=>{});let D=M instanceof Error?M.message:String(M);se({src:"session-new-failed",agentId:s.agentId??null,message:D});let O=await gb(t,s.agentId,D,{canGoBack:!s.forceNew});if(O==="cancel")return null;let Y={...s};return delete Y.sessionId,delete Y.resume,O==="retry"?Y.forceNew=!0:(delete Y.forceNew,delete Y.agentId),Y}if(I.kind==="cancel")return t.grabInput(!1),se({src:"grab",site:"runSession.auth-cancel",on:!1}),h.close().catch(()=>{}),null;if(I.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 A=I.result;d.write(c),Ce=A.sessionId,r.sessionId=Ce,r.readonly=!1;let C=Zt(A._meta??void 0);C.clientId&&(dn=C.clientId),Fn=C.upstreamSessionId,C.agentId&&(st=C.agentId),C.cwd&&(lt=C.cwd),C.title&&(an=C.title),ut=C.currentModel,wt=C.currentMode,Gr=C.currentUsage,Sn=C.turnStartedAt,C.availableCommands&&(ft=Td(C.availableCommands)),C.availableModes&&(Vr=C.availableModes),Qr=Eb(A.configOptions),Is=C.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:{[At]:g}}:{}});Ce=w.sessionId,w.clientId&&(dn=w.clientId),r.sessionId=Ce,r.readonly=s.readonly===!0;let I=Zt(w._meta??void 0);sr=I.resurrected===!0,Fn=I.upstreamSessionId,I.agentId&&(st=I.agentId),I.cwd&&(lt=I.cwd),I.title&&(an=I.title),ut=I.currentModel,wt=I.currentMode,Gr=I.currentUsage,Sn=I.turnStartedAt,I.availableCommands&&(ft=Td(I.availableCommands)),I.availableModes&&(Vr=I.availableModes),Qr=Eb(w.configOptions),Is=I.queue}let xs=_.tuiHistoryFile(Ce),mo=_.globalTuiHistoryFile(),kt=await Ho(xs).catch(()=>[]),cn=await Ho(mo).catch(()=>[]);cn.length>e.tui.promptHistoryMaxEntries&&(cn=cn.slice(cn.length-e.tui.promptHistoryMaxEntries));let me=[...kt],Ae=new gs({history:ud(cn,me)});xe=Ae;let rr=!1,Ot=(g,w)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let A=(w??g).replace(/\n+$/,""),C=Uo(kt,I),M=C!==kt;kt=C,me=Uo(me,A);let D=Uo(cn,I,e.tui.promptHistoryMaxEntries),O=D!==cn;cn=D,Ae.setHistory(ud(cn,me)),M&&Rr(xs,kt).catch(()=>{}),O&&lm(mo,I).catch(()=>{})};L>0&&Ae.setTurnRunning(!0);let zt=null,ln=null;sb(rb(e.tui.ambiguousWidth,process.env)),oy(e.tui.diffContextLines);let Lt=!1,x,go=()=>{Lt&&(Lt=!1,x.start())},ka=()=>{Lt||(Lt=!0,x.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",go);let Cs=null,Xr=null;x=new Ec({term:t,dispatcher:Ae,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"?ka:void 0,onBlockClick:(g,w)=>{ev(g,w)},onBlockDoubleClick:(g,w)=>Zb(g,w),onBlockVisible:g=>{Qb(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=Ps.get(g);if(w!==void 0&&w.length>0)return new Set(w);let I=x.contiguousRun(g,new Set(Ln.keys()));return I.length>0?new Set(I):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Cs=x.bannerHitAt(g.x,g.y),Xr=Cs?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let I=Xr,A=Cs;if(Xr=null,Cs=null,A!==null&&I!==null&&I.x===g.x&&I.y===g.y&&x.bannerHitAt(g.x,g.y)===A){if(A==="mode"){Es(!0);return}let C=A==="pick"?{type:"switch-session"}:A==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&qf(C))return;ae(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&qf(w)||ae(w)},onKey:g=>{for(let w of g){if(N&&Dc(w)){w.type==="key"&&se({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(_e&&ar(w)){w.type==="key"&&se({src:"key-swallowed",site:"permission",name:w.name});continue}if(Hc(w)){w.type==="key"&&se({src:"key-swallowed",site:"help",name:w.name});continue}if(Aa(w)){w.type==="key"&&se({src:"key-swallowed",site:"questions",name:w.name});continue}if(ko(w)){w.type==="key"&&se({src:"key-swallowed",site:"options",name:w.name});continue}if(xa(w)){w.type==="key"&&se({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(Ia(w)){w.type==="key"&&se({src:"key-swallowed",site:"completion",name:w.name});continue}if(bo(w)){w.type==="key"&&se({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&x.isScrolledBack()){x.scrollToBottom();continue}if(w.type==="attachment-paths"){ue(w.paths);continue}let I=Ae.feed(w);for(let A of I)s.readonly===!0&&qf(A)||ae(A)}wo(),x.setBannerSearchIndicator(Ae.state().historySearchQuery),x.setAttachments(Ae.state().attachments),x.refreshPrompt()}}),V=x,x.setStickyBottomKey("plan");let ir=[{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=ft??[],Xn=Vr??[],yo=Qr??[],Kt=()=>yo.find(g=>g.id==="agent"),Bc=()=>{let g=new Set,w=[];for(let I of[...ir,...je])g.has(I.name)||(g.add(I.name),w.push(I));return w},ot=()=>{let g=Ae.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let I=w.indexOf(" "),A=I===-1?w:w.slice(0,I);if(A.lastIndexOf("/")>0)return[];let C=Bc().filter(M=>M.name.startsWith(A));return C.length===1&&C[0]?.name===A?[]:C},Bt=[],wo=()=>{let g=ot();if(g.length>0){Bt=[],x.setCompletions(g);return}x.setCompletions(Bt)},Ia=g=>{if(g.type!=="key"||g.name!=="tab")return Bt.length>0&&(Bt=[]),!1;let w=ot();if(x.isOverlayOpen()&&w.length===0)return x.toggleFocusedPane(),!0;if(w.length>0){Bt=[];let I=Ae.state().buffer[0]??"",A=lb({matches:w.map(C=>C.name),firstLine:I});return A===null||Ae.replaceFirstLine(A),!0}return or()},or=()=>{let g=Ae.state(),w=g.buffer[g.row]??"",I=Sb(w,g.col);if(I===null)return!1;let A=kb(I.token,lt);return A===null?!1:(A.replacement!==I.token&&Ae.replaceRangeOnCurrentLine(I.start,g.col,A.replacement),Bt=A.candidates.length>1?A.candidates.map(C=>({name:C})):[],!0)},bo=g=>!x.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(F&&(F.cancel(),F=null,j=null),x.closeBtwOverlay(),!0),xa=g=>{if(!x.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&x.isScrolledBack()?(x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=x.scrollbackSearchTerm()+g.ch;return x.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=x.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return x.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return x.advanceScrollbackSearch(),!0;case"ctrl-s":return x.retreatScrollbackSearch(),!0;case"backspace":{let w=x.scrollbackSearchTerm();return w.length===0?x.cancelScrollbackSearch():x.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return x.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return x.cancelScrollbackSearch(),!0;default:return!0}return!0},ar=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),nr(),!0;case"down":return _e.selectedIndex=Math.min(w.length-1,_e.selectedIndex+1),nr(),!0;case"enter":{let I=w[_e.selectedIndex];return I&&St(I.optionId),!0}case"escape":case"ctrl-c":return St(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,A=w[I];return A&&St(A.optionId),!0}return!0},dr=st||po||"?",Nt={...Gr??{}};d.finalize(),x.start({skipFullscreen:!0}),x.setHideThoughts(!i.showThoughts),x.setSessionbar({agent:dr,cwd:lt,sessionId:Ce,title:an,model:ut,usage:{...Nt}}),wt&&x.setBanner({currentMode:wt}),ua().then(g=>{g&&x.notify(`\u2728 ${fa(g)}`,3e4)}).catch(()=>{});let pt=null,Nc=new Promise(g=>{pt=g}),vo=()=>{m.notify("session/cancel",{sessionId:Ce}).catch(()=>{})},cr=()=>{V!==null&&L===1&&(Z=!0,V.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Zn=()=>{if(zt){zt.cancel(),cr();return}if(L>0){vo(),cr();return}As()},As=()=>{R(0)},es=()=>{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]],...sT]},Rs=()=>{if(x.isHelpPromptActive()){x.setHelpPrompt(null);return}x.setHelpPrompt({title:"Hotkeys",entries:es(),hint:"any key dismisses \xB7 /help lists commands"})},lr=()=>{N=!1,x.setCompactionPrompt(null),x.setCompactionIndicator("compaction queued...");let g=Ce;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},Zr=()=>{N=!1,x.setCompactionPrompt(null)},So=g=>{let w=x.compactionPromptSpec();if(!w)return;let I=w.options.length;if(I===0)return;let A=((w.selectedIndex+g)%I+I)%I;A!==w.selectedIndex&&x.setCompactionPrompt({...w,selectedIndex:A})},Dc=g=>{if(!N)return!1;if(g.type==="key"){if(g.name==="escape")return Zr(),!0;if(g.name==="up")return So(-1),!0;if(g.name==="down")return So(1),!0;if(g.name==="enter"){let w=x.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?lr():Zr(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return lr(),!0;if(w==="n"||w==="2")return Zr(),!0}return!0},Hc=g=>x.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",x.setHelpPrompt(null),!0):!1,ts=["tools","plan","thoughts","diffs","mouse","enter"],Dt=0,un=null,ei=[],Pt=[],On=[],Jt=0,ns=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}},ti=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"}},Ca=()=>({title:"Session options",options:ts.map(g=>({label:ti(g),value:ns(g)})),selectedIndex:Dt}),ss=()=>{x.isOptionsPromptActive()&&un===null&&x.setOptionsPrompt(Ca())},ni=()=>{if(x.isOptionsPromptActive()){x.setOptionsPrompt(null);return}Dt=0,x.setOptionsPrompt(Ca())},Yt=()=>{if(un===null)return;let g=X0(un,ei,On,Jt);x.setOptionsPrompt(g)},Ts=()=>{un=null,ei=[],Pt=[],On=[],Jt=0,x.setOptionsPrompt(null)},kn=async()=>{if(un!==null){Ts();return}try{let w=await m.request(Aw,{sessionId:Ce}),I=Y0(w.questions??[]);if(I.length===0){x.notify("no open questions");return}let A=Q0(I);un=A,Jt=0,ei=A.map(C=>V0(C.representative)),Pt=A.map(()=>!1),On=A.map(()=>!1),Yt()}catch(g){x.notify("clarifier unavailable"),se({src:"questions",step:"list_failed",error:g.message})}},ur=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,hr.clear(),ii.clear(),Kb();break;case"plan":i.planExpanded=!i.planExpanded,te=null,Xe();break;case"thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",is.clear(),Gb();break;case"mouse":{let w=!x.isMouseEnabled();x.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}ss()},Vt=g=>{(async()=>{try{switch(g){case"tools":case"plan":x.notify(`${ti(g)} is session-only \u2014 not saved`);return;case"thoughts":await Co("showThoughts",i.showThoughts);break;case"diffs":await Co("showFileUpdates",i.showFileUpdates);break;case"mouse":await Co("mouse",i.mouseEnabled);break;case"enter":await Co("defaultEnterAction",i.defaultEnterAction);break}x.notify(`saved default: ${ti(g)} ${ns(g)}`)}catch(w){x.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},ko=g=>{if(un!==null||!x.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Dt=Math.max(0,Dt-1),ss(),!0;case"down":return Dt=Math.min(ts.length-1,Dt+1),ss(),!0;case"enter":{let w=ts[Dt];return w&&ur(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return x.setOptionsPrompt(null),!0;case"ctrl-d":return x.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,I=ts[w];return I&&(Dt=w,ur(I)),!0}if(g.ch==="s"||g.ch==="S"){let w=ts[Dt];return w&&Vt(w),!0}}return!0},Aa=g=>{if(un===null)return!1;let w=tT(g,!0,un,ei,Pt,On,Jt,Ce);switch(w.type){case"noop":return!0;case"row":return Jt=w.selectedRow,Yt(),!0;case"cycle":return ei[w.selectedRow]=w.newValueIndex,Pt[w.selectedRow]=!0,On[w.selectedRow]=!1,Yt(),!0;case"dismiss-toggle":{let I=w.selectedRow;return On[I]?(On[I]=!1,Pt[I]=!1):(On[I]=!0,Pt[I]=!0),Yt(),!0}case"discard":return Ts(),!0;case"save":{let I=w.dispatches;return Ts(),I.length===0||(async()=>{let A=0,C=0,M=0;for(let O of I)try{await m.request(O.method,O.params),O.type==="dismiss"?C++:A++}catch(Y){M++,se({src:"questions",step:"dispatch_failed",method:O.method,error:Y.message})}let D=[];A>0&&D.push(`${A} answered`),C>0&&D.push(`${C} dismissed`),M>0&&D.push(`${M} failed`),D.length>0&&x.notify(`clarifier: ${D.join(", ")}`)})(),!0}}return!1},si=()=>{b=!0,F?(F.cancel(),F=null,j=null):j!==null&&(Jn(n,j).catch(()=>{}),j=null),process.off("SIGINT",Zn),process.platform!=="win32"&&process.off("SIGCONT",go),X!==null&&(clearInterval(X),X=null),ce!==null&&(clearInterval(ce),ce=null);for(let g of He.values())clearTimeout(g);He.clear(),x.clearWindowTitle(),x.stop({keepFullscreen:!0}),Rr(xs,kt).catch(()=>{}),h.close().catch(()=>{})},R=(g=0)=>{si(),pt&&(pt(null),pt=null),g!==0&&process.exit(g)},P=async()=>{if(se({src:"switch-session",step:"entered",finishSessionNull:pt===null}),!pt)return;F?(F.cancel(),F=null,j=null):j!==null&&(Jn(n,j).catch(()=>{}),j=null),fo(),x.setSynthesisIndicator(null);let g=Ae.state().buffer.join(`
240
+ `);g.replace(/\s+$/,"").length>0&&Ot(g),x.pauseRepaint(),x.stop({keepFullscreen:!0}),Rr(xs,kt).catch(()=>{});let w=!1;try{let I=null,A=null;for(;I===null;){let O=await Kn(n,{includeNonInteractive:!0}),Y=await Hf(t,{cwd:lt,sessions:O,config:e,target:n,currentSessionId:Ce,prefs:o});if(Y.kind==="abort")return;if(Y.kind==="exit"){w=!0,R(0);return}if(Y.kind==="new"){I={choice:Y,sessions:O};break}if(Y.kind==="fork"){let Ie=await Lb(t,n,Y,O);if(Ie.kind==="cancel")return;if(Ie.kind==="back")continue;I={choice:{kind:"attach",sessionId:Ie.ctx.sessionId,...Ie.ctx.agentId?{agentId:Ie.ctx.agentId}:{}},sessions:O},A={readonly:!1,cwd:Ie.ctx.cwd},Ie.ctx.resumeHint!==void 0&&(A.resumeHint=Ie.ctx.resumeHint);break}let ge=O.find(Ie=>Ie.sessionId===Y.sessionId);if(!(ge!==void 0&&!!ge.importedFromMachine&&!ge.upstreamSessionId&&Y.readonly!==!0)){if(n.isLocal&&ge&&!ge.importedFromMachine&&Y.readonly!==!0&&!(await ha(ge.cwd)).ok){let Qt=await zr(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(Qt.kind==="cancel")return;if(Qt.kind==="back")continue;I={choice:Y,sessions:O},A={readonly:!1,cwd:Qt.path,resumeHint:{agentId:Y.agentId??ge.agentId??"",cwd:Qt.path,upstreamSessionId:""}};break}I={choice:Y,sessions:O};break}let pe={...s,readonly:!1},ye=await Fb(t,n,ge,Y,pe);if(ye.kind==="cancel")return;ye.kind!=="back"&&(I={choice:Y,sessions:O},A={readonly:pe.readonly===!0,cwd:ye.ctx.cwd},ye.ctx.resumeHint!==void 0&&(A.resumeHint=ye.ctx.resumeHint))}let{choice:C}=I,M=pt;if(pt=null,process.off("SIGINT",Zn),h.close().catch(()=>{}),w=!0,C.kind==="new"){let{sessionId:O,agentId:Y,...ge}=s,Pe={...ge,cwd:C.cwd??lt,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Pe.initialPrompt=C.prompt),M(Pe);return}if(C.kind!=="attach")return;let D={...s,sessionId:C.sessionId,cwd:A?.cwd??lt,readonly:A?.readonly??C.readonly===!0};C.agentId!==void 0&&(D.agentId=C.agentId),A?.resumeHint!==void 0?D.resumeHint=A.resumeHint:delete D.resumeHint,M(D)}finally{!w&&pt&&(x.start({skipFullscreen:!0}),x.resumeRepaint())}},B=async(g="next")=>{if(!pt)return;let I=(await Kn(n)).filter(Pe=>Pe.status==="warm");if(I.length<=1)return;let A=I.findIndex(Pe=>Pe.sessionId===Ce),D=((A===-1?0:A)+(g==="prev"?-1:1)+I.length)%I.length,O=I[D],Y=pt;pt=null,process.off("SIGINT",Zn),h.close().catch(()=>{});let ge={...s,sessionId:O.sessionId,cwd:lt,readonly:!1};O.agentId!==void 0&&(ge.agentId=O.agentId),Y(ge)},Q=async g=>{if(!pt)return;let w=await Kn(n,{includeNonInteractive:!0}),I=g.trim();if(!I){x.notify("usage: /session <id|next|prev>");return}let A=I.startsWith(yn)?[I]:[I,yn+I],C=w.find(O=>A.includes(O.sessionId));if(!C){let O=w.filter(Y=>A.some(ge=>Y.sessionId.startsWith(ge)));if(O.length===1)C=O[0];else if(O.length>1){x.notify(`ambiguous session id: ${I} (${O.length} matches)`);return}}if(!C){x.notify(`no session matches: ${I}`);return}if(C.sessionId===Ce){x.notify("already on that session");return}let M=pt;pt=null,process.off("SIGINT",Zn),h.close().catch(()=>{});let D={...s,sessionId:C.sessionId,cwd:C.cwd??lt,readonly:C.status!=="warm"};C.agentId!==void 0&&(D.agentId=C.agentId),delete D.resumeHint,M(D)},ae=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?fr(g.text,g.attachments,g.displayText):xn(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?xn(g.text,g.attachments,g.displayText):fr(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=ri(g.index);if(!w)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let A of g.attachments)I.push({type:"image",data:A.data,mimeType:A.mimeType});m.request("hydra-acp/prompt/update",{sessionId:Ce,messageId:w,prompt:I}).then(A=>{let C=A;!C.updated&&C.reason!=="ok"&&x.notify(`queue edit skipped (${C.reason})`)}).catch(A=>{x.notify(`queue edit failed: ${A.message}`)});return}case"queue-remove":{let w=ri(g.index);if(!w)return;m.request("hydra-acp/prompt/cancel",{sessionId:Ce,messageId:w}).then(I=>{let A=I;!A.cancelled&&A.reason!=="ok"&&x.notify(`queue cancel skipped (${A.reason})`)}).catch(I=>{x.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(x.isOverlayOpen()){F&&(F.cancel(),F=null,j=null),x.closeBtwOverlay();return}if(g.prefill&&zt){let w=Ye.size===0,I=Ae.state().buffer.every(A=>A==="");w&&I&&(ln={text:zt.text,attachments:zt.attachments})}zt?zt.cancel():L>0&&vo(),cr();return}case"exit":As();return;case"plan-toggle":Es(g.on);return;case"redraw-banner":x.setBanner({});return;case"redraw":x.fullRedraw();return;case"scroll-to-top":x.scrollToTop();return;case"scroll-to-bottom":x.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":B().catch(()=>{});return;case"toggle-options":ni();return;case"toggle-questions":kn();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,x.setHideThoughts(!i.showThoughts),x.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!x.isMouseEnabled();x.setMouseEnabled(w),i.mouseEnabled=w,x.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":Rs();return;case"escalate-search":x.enterScrollbackSearch(),x.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Be(g.source);return}},ue=async g=>{if(!Yr){x.notify("agent does not accept image attachments");return}let w=0;for(let I of g){if(I.startsWith("data:")){let C=wf(I);if(!C){x.notify("unsupported data: URI");continue}if(C.sizeBytes>Qn){x.notify(`image too large (${vn(C.sizeBytes)}, max ${vn(Qn)})`);continue}Ae.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),w++;continue}let A=ma(I);if(!A){x.notify(`unsupported image type: ${Kr.basename(I)}`);continue}try{let C=await jf.readFile(I);if(C.length>Qn){x.notify(`image too large (${vn(C.length)}, max ${vn(Qn)})`);continue}Ae.addAttachment({mimeType:A,data:C.toString("base64"),name:Kr.basename(I),sizeBytes:C.length}),w++}catch(C){x.notify(`cannot read ${Kr.basename(I)}: ${C.message}`)}}w>0&&(x.setAttachments(Ae.state().attachments),x.refreshPrompt())},Be=async(g="clipboard")=>{let w=g==="primary"?await Uw():await Hw();if(!w.ok){x.notify(w.reason);return}if(w.kind==="image"){if(!Yr){x.notify("agent does not accept image attachments");return}Ae.addAttachment(w.attachment),x.setAttachments(Ae.state().attachments),x.refreshPrompt();return}let I=Ae.feed({type:"paste",text:w.text});for(let A of I)ae(A);x.refreshPrompt()},Ht=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Mt=(g,w)=>{let I=Array.isArray(w)?w:[],A="",C=0;for(let M of I){if(!M||typeof M!="object")continue;let D=M;D.type==="text"&&typeof D.text=="string"?A+=D.text:D.type==="image"&&(C+=1)}return{messageId:g,text:Ee(A),attachmentCount:C}},Ye=new Map,ht=[],fn=new Map,bt=new Set,qe=null,In=()=>{let g=[...Ye.values()],w=g.map(Ht);x.setQueuedPrompts(w),x.setBanner({queued:g.length}),Ae.setQueue(g.map(I=>I.text))},ri=g=>[...Ye.values()][g]?.messageId;if(Is&&Is.length>0){for(let g of Is){if(g.position===0){G=g.messageId;continue}Ye.set(g.messageId,Mt(g.messageId,g.prompt))}Ye.size>0&&In()}let xn=(g,w,I)=>{x.scrollToBottom(),!Ra(g)&&(Ot(g,I),Io(g,w,I))},fr=(g,w,I)=>{if(x.scrollToBottom(),Ra(g))return;if(Ot(g,I),!ho||G===void 0){Io(g,w,I);return}let A=G,C=[];g.length>0&&C.push({type:"text",text:g});for(let O of w)C.push({type:"image",data:O.data,mimeType:O.mimeType});let M={text:g,displayText:I??g,attachments:w,flushed:!1};ht.push(M);let D=()=>{let O=ht.indexOf(M);O>=0&&ht.splice(O,1),M.messageId!==void 0&&fn.delete(M.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:Ce,targetMessageId:A,prompt:C}).then(O=>{let Y=O;if(Y.amended&&Y.reason==="ok"){De(1);return}if(D(),Y.reason==="target_completed"){x.notify("previous response finished \u2014 press Enter to send as a new turn"),Ae.setBuffer(g,w),x.refreshPrompt();return}if(Y.reason==="target_cancelled"){x.notify("amend skipped \u2014 previous turn was cancelled"),Ae.setBuffer(g,w),x.refreshPrompt();return}if(Y.reason==="target_not_found"){x.notify("amend skipped \u2014 no matching prompt"),Ae.setBuffer(g,w),x.refreshPrompt();return}}).catch(O=>{D(),x.notify(`amend failed: ${O.message}`),Ae.setBuffer(g,w),x.refreshPrompt()})},Es=async g=>{if(Xn.length===0){x.notify("no modes advertised by agent");return}let w=x.currentModeId(),I=Xn.findIndex(M=>M.id===w),A=I===-1?0:(I+1)%Xn.length,C=Xn[A]?.id;if(C){x.setBanner({currentMode:C});try{await m.request("session/set_mode",{sessionId:Ce,modeId:C})}catch(M){x.notify(`set_mode failed: ${M.message}`)}}},Ra=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 As(),!0;case"/clear":return mt.clear(),Cn.clear(),at.length=0,E=null,U=null,ie=null,rs.clear(),is.clear(),os.clear(),hr.clear(),Ln.clear(),Ps.clear(),x.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of ir)C.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(je.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of je)C.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return x.appendLines(C),!0}case"/agent":{let C=I===-1?"":w.slice(I+1).trim(),M=Kt();if(!M)return x.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let D=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of M.options){let Y=O.value===M.currentValue?"* ":" ";D.push({prefix:" ",body:`${Y}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return x.appendLines(D),!0}return M.options.some(D=>D.value===C)?C===M.currentValue?(x.notify(`already on agent ${C}`),!0):(x.notify(`switching to ${C}\u2026`),m.request("session/set_config_option",{sessionId:Ce,configId:"agent",value:C}).catch(D=>{x.notify(`set_config_option failed: ${D.message}`)}),!0):(x.notify(`unknown agent: ${C}`),!0)}case"/sessions":return x.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return P().catch(C=>{se({src:"switch-session-failed",stack:C instanceof Error?C.stack??C.message:String(C)})}),!0;case"/session":{let C=I===-1?"":w.slice(I+1).trim();return C?C==="next"||C==="prev"?(B(C).catch(M=>{x.notify(`session ${C} failed: ${M.message}`)}),!0):(Q(C).catch(M=>{x.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 C=I===-1?"":w.slice(I+1).trim(),M=C.length>0?`/hydra title ${C}`:"/hydra title";return Ot(w,w),Io(M,[],w),!0}case"/btw":{let C=I===-1?"":w.slice(I+1).trim();if(!C)return x.isOverlayOpen()?(F&&(F.cancel(),F=null,j=null),x.closeBtwOverlay(),!0):(x.reopenBtwOverlay()||x.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(Ce==="__new__")return x.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;H+=1;let M=H;F&&(F.cancel(),F=null);let D=null;j!==null&&!K?D=j:j!==null&&(Jn(n,j).catch(()=>{}),j=null),K=!1,x.openBtwOverlay(),x.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new kc({getMaxWidth:()=>{let pe=x.width();return pe>0?pe:void 0}});O.on("changed",()=>{x.setBtwOverlayContent(O.getLines())});let Y={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let ge=pe=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:pe}})},Pe={};return D!==null&&(Pe.reuseSessionId=D),Pw(n,Ce,C,Pe).then(pe=>{if(M!==H){pe.cancel();return}F=pe,j=pe.sessionId,x.setBtwOverlayMeta({sessionId:pe.sessionId}),pe.on("event",ye=>{if(M===H)if(ye.kind==="update"){O.append(ye.update);let Ie=Wn(ye.update);if(Ie&&Ie.kind==="usage-update"){let Qt=!1;Ie.used!==void 0&&Y.used!==Ie.used&&(Y.used=Ie.used,Qt=!0),Ie.size!==void 0&&Y.size!==Ie.size&&(Y.size=Ie.size,Qt=!0),Ie.costAmount!==void 0&&Y.costAmount!==Ie.costAmount&&(Y.costAmount=Ie.costAmount,Qt=!0),Ie.costCurrency!==void 0&&Y.costCurrency!==Ie.costCurrency&&(Y.costCurrency=Ie.costCurrency,Qt=!0),Qt&&x.setBtwOverlayMeta({usage:{...Y}})}}else ye.kind==="completed"?(x.setBtwOverlayStatus({label:"done",style:"done"}),F=null):ye.kind==="cancelled"?(x.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),F=null,j=null):ye.kind==="errored"&&(x.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw errored: ${ye.error.message}`),j!==null&&Jn(n,j).catch(()=>{}),F=null,j=null)})}).catch(pe=>{if(M!==H)return;let ye=pe instanceof Error?pe.message:String(pe);x.setBtwOverlayStatus({label:"errored",style:"errored"}),ge(`btw startup failed: ${ye}`),x.appendLines([{prefix:" ",body:`btw startup failed: ${ye}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Ce==="__new__")return x.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=I===-1?"":w.slice(I+1).trim(),M=Ce;return(async()=>{try{let D=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!D.ok){let ye=await D.text().catch(()=>"");x.appendLines([{prefix:" ",body:`/export failed: HTTP ${D.status} ${ye}`.trim(),bodyStyle:"info"}]);return}let O=await D.text(),Y=new Date().toISOString().replace(/[:.]/g,"-"),ge=`hydra-${rt(M)}-${Y}.md`,Pe=C.length>0?et(C):ge,pe=Kr.resolve(Pe);await jf.mkdir(Kr.dirname(pe),{recursive:!0}),await jf.writeFile(pe,O,{encoding:"utf8",mode:384}),x.appendLines([{prefix:" ",body:`Wrote ${pe}`,bodyStyle:"system"}])}catch(D){x.appendLines([{prefix:" ",body:`/export failed: ${D.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Io=async(g,w,I)=>{let A=[];g.length>0&&A.push({type:"text",text:g});for(let Pe of w)A.push({type:"image",data:Pe.data,mimeType:Pe.mimeType});De(1);let C={text:g,displayText:I??g,attachments:w,flushed:!1};ht.push(C),Et=!1;let M=!1,D=null,O=Pe=>{typeof V<"u"&&V!==null&&V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},Y=!1;zt={text:g,attachments:w,cancel:()=>{if(Et){Et=!1,Y=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),m.request("hydra-acp/session/force_cancel",{sessionId:Ce}).catch(pe=>{O(`force-stop failed: ${pe.message}`)});return}if(M)return;M=!0,m.notify("session/cancel",{sessionId:Ce}).catch(()=>{});let Pe=Date.now();D=setTimeout(()=>{zt!==null&&(Ss>=Pe||(Et=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},on)}};let ge;try{let Pe=await m.request("session/prompt",{sessionId:Ce,prompt:A});Pe&&typeof Pe.stopReason=="string"&&(ge=Pe.stopReason)}catch(Pe){let pe=ht.indexOf(C);pe>=0&&ht.splice(pe,1),C.messageId!==void 0&&fn.delete(C.messageId),Y?x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):x.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Pe.message,bodyStyle:"tool-status-fail"}])}finally{if(zt=null,D!==null&&(clearTimeout(D),D=null),De(-1),C.flushed&&qe===C){let Pe=C.messageId!==void 0&&bt.has(C.messageId);Pe&&C.messageId!==void 0&&bt.delete(C.messageId);let pe={kind:"turn-complete"};ge!==void 0&&(pe.stopReason=ge),Pe&&(pe.amended=!0),k(pe),qe=null}if(ln!==null){let{text:Pe,attachments:pe}=ln;ln=null,Ae.state().buffer.every(Ie=>Ie==="")&&(Ae.setBuffer(Pe,pe),x.refreshPrompt())}}},mt=new Map,rs=new Map,is=new Map,Cn=new Map,at=[],pr=0,An=`tools:${pr}`,os=new Map,hr=new Map,ii=new Set,as=new Map,Ln=new Map,Ps=new Map,E=null,U=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=Js(W,We());g.length>0&&x.upsertLines("plan",[{body:""},...g])},dt="",Re=null,It=0,Ut=()=>{if(Re===null)return;let g=x.width(),w=Ys(dt,g>0?{maxWidth:g}:void 0);w.length!==0&&x.upsertLines(Re,w)},Yf=g=>{g.length!==0&&(Re===null&&(x.ensureSeparator(),Re=`agent:${It}`,It+=1,dt=""),dt+=g,Ut())},pn=()=>{Re=null,dt=""},Ms="",hn=null,mr=0,gr=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Uc=()=>{if(hn===null||Ms.length===0)return;let g=Qi(Ms);g.length!==0&&x.upsertLines(hn,g)},jc=g=>{let w=Ln.get(g);if(w===void 0)return[];let I=Qi(w.text);return w.workerTaskId&&I.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),I},Ta=(g,w)=>{g.length!==0&&(hn===null&&(x.ensureSeparator("thought"),hn=`thought:${mr}`,mr+=1,Ms=""),Ms+=g,Ln.set(hn,{text:Ms,workerTaskId:w}),Uc())},$e=()=>{hn=null,Ms=""},ds=g=>oT({...g,collapsedLimit:re}),_s=g=>hr.get(g)??i.toolsExpanded,jt=()=>{if(E===null)return;let{lines:g,rowOwners:w}=ds({order:at,states:mt,startedAt:E,endedAt:U,stopReason:ie,expanded:_s(An),perToolExpanded:ii});x.upsertLines(An,g),as.set(An,w)},Ea=g=>{let w=os.get(g);if(!w)return;let{lines:I,rowOwners:A}=ds({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:_s(g),perToolExpanded:ii});x.upsertLines(g,I),as.set(g,A)},Kb=()=>{E!==null&&!os.has(An)&&jt();for(let g of os.keys())Ea(g)},qc=()=>{E!==null&&os.set(An,{order:[...at],states:new Map(mt),startedAt:E,endedAt:U??Date.now(),stopReason:ie,rowOwners:as.get(An)??[]})},Vf=()=>{pr+=1,An=`tools:${pr}`,E=Date.now(),U=null,ie=null,jt()};function Jb(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 A=[],C=M=>{if(typeof M=="string"){A.push({text:ct(M)});return}if(M&&typeof M=="object"){let D=M;typeof D.__hydraBlob=="string"&&A.push({hash:D.__hydraBlob})}};for(let M of I){if(!M||typeof M!="object")continue;let D=M;if(D.type==="content"&&D.content&&typeof D.content=="object"){let O=D.content;if(O.text!==void 0){C(O.text);continue}}if(D.type==="text"&&D.text!==void 0){C(D.text);continue}D.text!==void 0&&C(D.text)}return A.length>0?A:null}let Qf=(g,w)=>{let I=w.map(M=>"text"in M?M.text:"").join(`
242
+ `);if(I.length===0)return;let{text:A,truncated:C}=sy(I);g.resultText=A,g.resultTruncated=C},Pa=new Set,Yb=(g,w)=>{!w.some(A=>"hash"in A)||Pa.has(g)||(Pa.add(g),(async()=>{let A=await Promise.all(w.map(async M=>"text"in M?M:{text:await Wc(M.hash)??""}));Pa.delete(g);let C=mt.get(g);if(!C)for(let M of os.values()){let D=M.states.get(g);if(D){C=D;break}}if(C){Qf(C,A),mt.has(g)&&jt();for(let[M,D]of os)D.states.has(g)&&Ea(M);x.repaintNow()}})().catch(()=>{Pa.delete(g)}))},Gf=(g,w,I,A,C,M,D,O,Y,ge)=>{let Pe=!mt.has(g),pe=mt.get(g),ye=pe??{initialTitle:w??"tool",latestTitle:w??"tool",status:I??"pending",startedAt:Date.now()};if(!pe&&Y!==void 0&&(ye.workerTaskId=Y),pe&&w!==void 0&&(ye.latestTitle=w),M!==void 0&&ye.detail===void 0&&(ye.detail=M),D!==void 0&&ye.detailFull===void 0&&(ye.detailFull=D),O!==void 0&&O.length>0&&(ye.locations=O),pe&&I!==void 0&&(ye.status=I),pe||(ye.status=I??"pending"),ye.endedAt===void 0&&Nu(ye.status)&&(ye.endedAt=Date.now()),A!==void 0&&(ye.errorText=A),C!==void 0&&(ye.editDiff=C),ge!==void 0){let Ie=Jb(ge);Ie!==null&&(Qf(ye,Ie),Ie.some(Qt=>"hash"in Qt)&&Yb(g,Ie))}mt.set(g,ye),Pe&&(E===null&&(pr+=1,An=`tools:${pr}`,E=Date.now(),U=null,ie=null),at.push(g))},Wc=async g=>{try{let w=await m.request("hydra-acp/session/tool_content",{sessionId:Ce,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},Ma=new Set,Vb=(g,w)=>{Ma.has(g)||w.oldRef===void 0&&w.newRef===void 0||(Ma.add(g),(async()=>{let[I,A]=await Promise.all([w.oldRef?Wc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Wc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&I===null||w.newRef!==void 0&&A===null){Ma.delete(g);let ge=Lu(w,"diff",{deferredStatus:"error"});ge.length>0&&(x.upsertLines(`editdiff:${g}`,ge),x.repaintNow());return}let M={...w.path!==void 0?{path:w.path}:{},oldText:I??"",newText:A??""};rs.set(g,M);let D=mt.get(g);D?.editDiff&&(D.editDiff=M),Ma.delete(g);let O=is.get(g),Y=O===void 0?i.showFileUpdates:O?"diff":"edit";Y!=="none"&&(_a(g,M,Y==="diff"?"diff":"edit"),x.repaintNow())})())},_a=(g,w,I)=>{let A=`editdiff:${g}`,C=Lu(w,I);if(C.length===0){x.removeKey(A);return}x.upsertLines(A,C),I==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&x.notifyWhenVisible(A)},Qb=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),I=rs.get(w);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Vb(w,I)},Xf=g=>{let w=`editdiff:${g}`,I=i.showFileUpdates,A=mt.get(g),C;if(I==="none"||!A?.editDiff||A.status!=="completed")C=null;else{let D=is.get(g);C=D!==void 0?D?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){x.removeKey(w);return}let M=A.editDiff;rs.set(g,M),_a(g,M,C)},Gb=()=>{let g=i.showFileUpdates;for(let[w,I]of rs){let A=`editdiff:${w}`,C=is.get(w),M=C===void 0?g:C?"diff":"edit";if(M==="none"){x.removeKey(A);continue}_a(w,I,M==="diff"?"diff":"edit")}},Xb=g=>{if(!g.path)return null;let w=ct(g.oldText).split(`
243
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(`
244
+ `),A=0,C=Math.min(w.length,I.length);for(;A<C&&w[A]===I[A];)A++;let M=I[A];if(!M)return null;let D=Kr.isAbsolute(g.path)?g.path:Kr.resolve(lt,g.path),O;try{O=K0(D,"utf8")}catch{return null}let Y=O.split(`
245
+ `);for(let ge=0;ge<Y.length;ge++)if(Y[ge]===M)return ge+1;return null},Zb=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),A=rs.get(I),M=mt.get(I)?.locations?.[0],D=M?.path??A?.path;if(!D)return!1;let O=null;M?.line!==void 0?O=M.line:A&&(O=Xb(A));let Y=O===null?"":`:${O}`;return x.tryOpenPathString(D+Y)}if(g.startsWith("tools:")){if(w===0)return!1;let I=as.get(g),A=I?I[w]:void 0;if(!A)return!1;let C=mt.get(A),M=C?.locations?.[0];if(M){let O=M.line===void 0?"":`:${M.line}`;if(x.tryOpenPathString(M.path+O))return!0}let D=C?.detailFull??C?.detail;if(D)return x.tryOpenPathString(D)}return!1},ev=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),A=rs.get(I);if(!A)return;let C=is.get(I)??i.showFileUpdates==="diff";is.set(I,!C),_a(I,A,C?"edit":"diff"),x.repaintNow();return}if(g==="plan"){if(W===null)return;te=!(te??i.planExpanded),Xe(),x.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let C=hr.get(g)??i.toolsExpanded;hr.set(g,!C),g===An&&E!==null?jt():Ea(g),x.repaintNow();return}let I=as.get(g);if(!I)return;let A=I[w];if(!A)return;rT(A,ii),Ea(g),x.repaintNow();return}if(g.startsWith("thought:")){if(!Ln.has(g))return;let I=Ps.get(g);if(I!==void 0){Ps.delete(g),x.setRunCollapsed(I,!1,jc(g)),x.repaintNow();return}let A=x.contiguousRun(g,new Set(Ln.keys()));if(A.length===0)return;let C=A[0];Ps.set(C,A),x.setRunCollapsed(A,!0,[gr()]),x.repaintNow();return}};v=(g,w)=>{if(g.kind==="available-commands"){je=g.commands,wo();return}if(g.kind==="available-modes"){Xn=g.modes;return}if(g.kind==="config-options"){yo=g.options;let A=g.options.find(M=>M.id==="agent");A&&A.currentValue&&A.currentValue!==st&&(st=A.currentValue,x.setSessionbar({agent:A.currentValue}));let C=g.options.find(M=>M.id==="mode");C&&(Xn=C.options.map(M=>({id:M.value,name:M.name??M.value,...M.description!==void 0?{description:M.description}:{}})));return}if(g.kind==="mode-changed"){x.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&x.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==st&&(st=g.agentId,x.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let A=!1;g.used!==void 0&&Nt.used!==g.used&&(Nt.used=g.used,A=!0),g.size!==void 0&&Nt.size!==g.size&&(Nt.size=g.size,A=!0),g.costAmount!==void 0&&Nt.costAmount!==g.costAmount&&(Nt.costAmount=g.costAmount,A=!0),g.costCurrency!==void 0&&Nt.costCurrency!==g.costCurrency&&(Nt.costCurrency=g.costCurrency,A=!0),A&&x.setSessionbar({usage:{...Nt}});return}if(g.kind==="user-text"){rr&&Ot(g.text),pn(),$e(),E!==null&&(U=Date.now(),jt()),qe=null,x.ensureSeparator();let A=Js(g);A.length>0&&x.appendLines(A),qc(),x.clearKey("plan"),W=null,te=null,mt.clear(),Cn.clear(),at.length=0,U=null,Vf(),x.redraw();return}if(g.kind==="agent-text"){$e(),Re===null&&$(g.workerTaskId),Yf(g.text);return}if(g.kind==="agent-thought"){pn(),hn===null&&$(g.workerTaskId),Ta(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){pn(),$e();let A=Cn.get(g.toolCallId),C={plan:g.plan??A?.plan??"",status:g.status??A?.status};if(Cn.set(g.toolCallId,C),C.plan.length===0)return;let M=cy(C);M.length>0&&x.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){pn(),$e(),mt.has(g.toolCallId)||$(g.workerTaskId),Gf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),jt(),Xf(g.toolCallId);return}if(g.kind==="plan"){pn(),$e(),W=g;let A=Js(g,We());A.length>0&&x.upsertLines("plan",[{body:""},...A]);let C=g.entries.length>0&&g.entries.every(M=>(M.status??"pending")==="completed");x.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){pn(),$e(),Gf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(bs=!0),jt(),Xf(g.toolCallId);return}g.kind==="model-changed"&&x.setSessionbar({model:g.model});let I=Js(g);if(I.length>0&&x.appendLines(I),g.kind==="turn-complete"){G=void 0,pn(),$e();let A=g.amended?"amended":g.stopReason;if(!g.amended&&bs&&(A===void 0||A==="end_turn")&&(A="error"),W!==null&&A!==void 0&&A!=="end_turn"){let C=Js({...W,stopped:!0,amended:g.amended===!0},We());C.length>0&&x.upsertLines("plan",[{body:""},...C])}W=null,te=null,x.clearKey("plan"),x.setStickyBottomKey("plan"),E!==null?(U=Date.now(),ie=A??null,jt(),qc()):A!==void 0&&A!=="end_turn"&&A!=="amended"&&x.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${A}`,bodyStyle:"tool-status-fail"}]),mt.clear(),Cn.clear(),at.length=0,E=null,U=null,ie=null,bs=!1,x.ensureSeparator(),Cb({pendingTurns:L,queueSize:Ye.size,ownTurnInFlight:zt!==null,hasInFlightHead:G!==void 0,replayDraining:S,amended:g.amended===!0})&&De(-L)}};let Zf=y;y=[];let $a=[];for(let{event:g}of Zf)g.kind==="user-text"&&typeof g.text=="string"&&$a.push(g.text);x.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of Zf)v(g,w)}finally{S=!1,x.resumeRepaint()}if($a.length>0){let g=tu(kt,$a);g!==kt&&(kt=g,me=tu(me,$a),Ae.setHistory(ud(cn,me)),Rr(xs,kt).catch(()=>{}))}rr=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ce)}/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"?x.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&x.setCompactionIndicator("compaction queued (waiting for idle)"),!sr||w.shouldCompact!==!0)return;let A=w.approxTokens??0;N=!0,x.setCompactionPrompt({message:`This session has ~${Pm(A)} 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(Ce)}`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(x.setSynthesisIndicator("synthesizing context\u2026"),tr()):w.forkSynthesisState==="failed"&&(x.setSynthesisIndicator("\u26A0 synthesis failed"),x.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Sn!==void 0&&L>0?(Se=Sn,x.setBanner({status:"busy",elapsedMs:Date.now()-Sn}),X===null&&(X=er()),E===null&&Vf(),E=Sn,jt()):Sn===void 0&&L>0&&De(-L);let tv=()=>{if(_e){let g=_e.resolve;_e=null,x.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}pn(),$e()},ep=()=>{E!==null&&(U=Date.now(),ie="reconnect-recovery-failed",jt(),qc(),mt.clear(),Cn.clear(),at.length=0,E=null,U=null,ie=null)};return p=g=>{se({src:"reconnect",step:"disconnect",message:g?.message}),x.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{if(se({src:"reconnect",step:"begin",sessionId:Ce}),n.isLocal)try{let O=await _t(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)})}tv();let g={jsonrpc:"2.0",id:`tui-reinit-${Tb()}`,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=Gn!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Tb()}`,method:"session/attach",params:{sessionId:Ce,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Gn}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let O={};return Fn!==void 0&&(O.resume={upstreamSessionId:Fn,agentId:st,cwd:lt}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[At]:O}}:{}})()}};ve=[];let A,C,M;se({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:Gn});try{let O=await h.request(I);if(se({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);M=xb(O.result),A=M.appliedPolicy,M.clientId!==void 0&&(dn=M.clientId)}catch(O){C=O,se({src:"reconnect",step:"attach-fail",message:C.message})}let D=ve??[];if(ve=null,C)ep(),x.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&A!=="after_message")ep(),x.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 D)it(O)}finally{S=!1}}if(M){let O=Ab({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&De(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(Se=O.busySince,x.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),X===null&&(X=er())):x.setBanner({status:"ready",elapsedMs:void 0})}else x.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});se({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
246
246
  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(`
247
+ `),R(g?1:0)}),process.on("SIGINT",Zn),s.initialPrompt&&a.sessionId==="__new__"&&xn(s.initialPrompt,[]),await Nc}async function dT(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:Mb(s,o,e);if(s.resume){let a=await Kn(n,{cwd:o,all:!0}),c=Vd(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 Kn(n,{includeNonInteractive:!0}),c=await Hf(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 Mb(s,o,e)}if(c.kind==="fork"){let u=await Lb(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 Fb(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 ha(d.cwd)).ok){let f=await zr(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 Fb(t,e,n,s,r){for(;;){let i=await ab(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 Ob(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await zr(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 Ob(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await Jd(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 Uf(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 Lb(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await Ob(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 zr(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 Yd(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
249
249
  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()}
250
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function Mb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function _b(t,e,n,s){if(n.agentId||await fp())return"ok";let r;try{r=await Jd(e)}catch{return"ok"}if(r.length===0)return"ok";let i=await be(),o=s.lastChosenAgent??i.defaultAgent,a=await Uf(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 La(a.agentId)}catch{}return"ok"}function cT(t,e){se({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function lT(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 Wf,nT,sT,Pb,Bb=J(()=>{"use strict";Cr();Rt();af();Ve();ff();kr();_r();Vo();Ro();Ew();Un();he();Ir();en();yc();lf();fd();na();Mw();_w();hb();Bf();Lf();mb();of();yb();Of();pu();gf();Cc();kf();_c();Ib();Rb();Us();Gi();Wf="dismiss";nT=12e4;sT=[["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"]];Pb=!1});var Nb={};zc(Nb,{runTui:()=>$b});var Db=J(()=>{"use strict";Bb()});import{readFileSync as uT}from"fs";import{fileURLToPath as fT}from"url";import{dirname as pT,resolve as hT}from"path";var tp=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"]),sv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function np(t){for(let e of Object.keys(t))if(!tp.has(e)&&!sv.has(e))return e}function Kc(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(tp.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 rv(t,e){let n=t[e];if(typeof n=="string")return n}function oi(t,e){return t[e]===!0||t[e]==="true"}var iv="HYDRA_ACP_";function ov(t){return iv+t.toUpperCase().replace(/-/g,"_")}function gt(t,e){let n=rv(t,e);return n!==void 0?n:process.env[ov(e)]}Ve();kr();async function Ep(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=Xc(n);return{target:await Rp(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await be();return{target:await _t(s),sessionId:n,fromUrl:!1}}function cl(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}Ir();he();Ve();cs();import*as _p from"fs/promises";async function $p(t){if(await _p.mkdir(_.home(),{recursive:!0}),await Oa(),!await ci()){let n=di();await li(n),process.stdout.write(`Initialized ${_.authToken()}
252
252
  Service token: ${n}
253
- `);return}if(ii(t,"rotate-token")){let n=ai();await ci(n),process.stdout.write(`Rotated token in ${_.authToken()}
253
+ `);return}if(oi(t,"rotate-token")){let n=di();await li(n),process.stdout.write(`Rotated token in ${_.authToken()}
254
254
  New token: ${n}
255
255
  `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
256
256
  `),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(`
257
+ `)}he();fi();Ve();cs();import{setTimeout as eC}from"timers/promises";import Cg from"chalk";import*as bg from"fs";import*as Ni from"fs/promises";import*as vg from"net";import*as Sg from"tls";import qx from"fastify";import Wx from"@fastify/websocket";var Fp="acp.v1";function Op(t,e){return t.has(Fp)?Fp:!1}Ve();import wg from"pino";import zx from"pino-roll";he();import*as Ct from"fs/promises";import{createHash as zv}from"crypto";import{gzip as Kv,gunzip as Jv}from"zlib";import{promisify as Lp}from"util";var Bp=Lp(Kv),Yv=Lp(Jv),Np=/^[A-Za-z0-9_-]+$/,Vv=/^[a-f0-9]{64}$/,ll=!0;function Dp(t){ll=t}function Ua(t,e){return Np.test(t)?e===void 0||Vv.test(e):!1}function ja(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function ul(t,e){if(!Ua(t))return null;let n=zv("sha256").update(e,"utf8").digest("hex"),s=ja(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=ll?s:r,o=ll?await Bp(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 qa(t,e){if(!Ua(t,e))return null;try{let n=await Ct.readFile(ja(t,e));return(await Yv(n)).toString("utf8")}catch{}try{return await Ct.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Hp(t,e){if(!Ua(t,e))return null;try{return await Ct.readFile(ja(t,e))}catch{}try{let n=await Ct.readFile(_.toolBlobFile(t,e));return await Bp(n)}catch{return null}}async function Up(t,e,n){if(!Ua(t,e))return;let s=ja(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 jp(t){Np.test(t)&&await Ct.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();Ve();wr();import*as Zp from"fs/promises";import*as za from"path";import{z as oe}from"zod";he();import*as Wp from"fs";import*as $t from"fs/promises";import*as Fs from"path";import{spawn as zp}from"child_process";import{Readable as Qv}from"stream";function Nn(){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 hl(t,e=Nn()){if(e)return t[e]}var pi=t=>{process.stderr.write(t+`
258
+ `)};function ml(t){pi=t??(e=>process.stderr.write(e+`
259
+ `))}async function Kp(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Nn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Nn();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=Fs.resolve(n,t.target.cmd);if(await pl(s))return s;if(await Gv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await pl(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 Gv(t){await $t.mkdir(Fs.dirname(t.installDir),{recursive:!0});let e=await $t.mkdtemp(`${t.installDir}.partial-`);try{pi(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await Xv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});pi(`hydra-acp: extracting ${t.agentId}`),hi(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await eS(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 pl(t.installDir)){await $t.rm(e,{recursive:!0,force:!0}).catch(()=>{}),hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}pi(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),hi(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await $t.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function hi(t,e){if(t)try{t(e)}catch{}}async function Xv(t){let e=Zv(t.url),n=Fs.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=Wp.createWriteStream(n),o=Qv.fromWeb(s.body);hi(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,hi(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,pi(qp(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),pi(qp(t.agentId,a,r,!0)),hi(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function qp(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 Zv(t){let e=new URL(t);return Fs.posix.basename(e.pathname)||"archive"}async function eS(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await fl("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await tS("unzip")){await fl("unzip",["-q",t,"-d",e]);return}await fl("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function fl(t,e){return new Promise((n,s)=>{let r=zp(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 tS(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=zp(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function pl(t){try{return await $t.access(t),!0}catch{return!1}}he();import*as Xt from"fs/promises";import*as Dn from"path";import{spawn as nS}from"child_process";var yl=t=>{process.stderr.write(t+`
260
+ `)};function wl(t){yl=t??(e=>process.stderr.write(e+`
261
+ `))}async function Yp(t){let e=Nn();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=aS(t.packageSpec),r=dS(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Dn.join(n,"node_modules",".bin",t.bin);if(await xr(o))return o;if(await xr(n)){let u=await Jp(i);if(u)return u.binPath}await sS({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Jp(i);if(a)return a.binPath;let c=await Qp(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 sS(t){await Xt.mkdir(Dn.dirname(t.installDir),{recursive:!0});let e=await Xt.mkdtemp(`${t.installDir}.partial-`);try{yl(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),gl(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await oS({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Xt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await xr(t.installDir)){await Xt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),gl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}yl(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),gl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Xt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function gl(t,e){if(t)try{t(e)}catch{}}var rS=5,iS=25;function oS(t){return Vp(t,0)}async function Vp(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=nS("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<rS)return await new Promise(r=>setTimeout(r,iS*(e+1))),Vp(t,e+1);throw n}}function aS(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 dS(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Qp(t,e){let n=Dn.join(t,"node_modules",e,"package.json");try{let s=await Xt.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 Jp(t){let e=Dn.join(t.installDir,"node_modules",".bin"),n=Dn.join(e,t.hint);if(await xr(n))return{binName:t.hint,binPath:n};let s=await Qp(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Dn.join(e,i);if(await xr(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=Dn.join(e,i);if(await xr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Dn.join(e,t.basename);if(await xr(r))return{binName:t.basename,binPath:r}}}async function xr(t){try{return await Xt.access(t),!0}catch{return!1}}var cS=oe.object({package:oe.string(),bin:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),mi=oe.object({archive:oe.string().url().optional(),cmd:oe.string().optional(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),lS=oe.object({"darwin-aarch64":mi.optional(),"darwin-x86_64":mi.optional(),"linux-aarch64":mi.optional(),"linux-x86_64":mi.optional(),"windows-x86_64":mi.optional(),"windows-aarch64":mi.optional()}),uS=oe.object({package:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),fS=oe.object({command:oe.string(),args:oe.array(oe.string()).optional(),env:oe.record(oe.string()).optional()}),pS=oe.object({command:oe.string().optional(),url:oe.string().optional(),description:oe.string().optional()}),hS=oe.object({npx:cS.optional(),binary:lS.optional(),uvx:uS.optional(),exec:fS.optional()}),mS=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:hS,onboarding:pS.optional(),requiredEnv:oe.array(oe.string().min(1)).optional()}),Gp=oe.object({version:oe.string(),agents:oe.array(mS),extensions:oe.array(oe.unknown()).optional()}),Wa=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=>bl(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:gS(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=Gp.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 mn(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Gp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Gt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function gS(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 bl(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 gi(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 vl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function vl(t){let e=Nn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=hl(t.distribution.binary,e);if(s?.cmd){let r=za.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await Xp(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??bl(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=za.join(i,"node_modules",".bin",r);if(await Xp(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Xp(t){try{return await Zp.access(t),!0}catch{return!1}}async function gn(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??bl(t)??r.package,a=n.onInstallProgress;return{command:await Yp({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=hl(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Nn()??"this platform"}.`);let i=n.onInstallProgress,o=await Kp({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 SS}from"child_process";import*as Xa from"fs";import*as mh from"path";Rt();function Ga(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
263
  `);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
264
  `)}}),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()} ---
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()}}}Cr();he();var kS=4096,Ls=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??kS,this.killEscalationMs=e.killEscalationMs??IS,this.logger=e.logger,this.fileLog=xS(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=Ga(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
267
  `),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
268
  `),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()} ---
269
+ stderr: ${n}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=SS(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
270
  `),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}
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)})}},IS=2e3;function xS(t){try{let e=_.agentLogFile(t);Xa.mkdirSync(mh.dirname(e),{recursive:!0});let n=Xa.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Er from"fs/promises";import*as md from"os";import*as zo from"path";import{customAlphabet as $k}from"nanoid";Cl();Un();zl();he();wr();import*as fs from"fs/promises";import{z as jn}from"zod";var yk=jn.object({version:jn.literal(1),agentId:jn.string(),upstreamSessionId:jn.string(),deletedAt:jn.string(),upstreamUpdatedAt:jn.string().optional(),cwd:jn.string().optional(),title:jn.string().optional(),reason:jn.enum(["user","expired"]).optional(),interactive:jn.boolean().optional()}),od=class{async add(e){let n={version:1,...e};await Gt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await fs.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await mn(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 yk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await fs.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await fs.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 fs.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 fs.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 qh(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as nm from"fs/promises";Rt();en();rd();nd();var vk=12e4;async function zh(t,e,n){let s=t.timeoutMs??vk,r,i,o=!1;try{let a=(async()=>{r=Ls.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=kk(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=Sk(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 dd(t){let e=ki(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
272
 
273
273
  ${e}
274
274
 
275
- ${Ll}`:`${n}
275
+ ${Bl}`:`${n}
276
276
 
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}
277
+ ${Bl}`;return zh(t,s,Hh)}async function Kh(t){let e=ki(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
278
 
279
279
  ${e}
280
280
 
281
- ${Bl}`:`${n}
281
+ ${Nl}`:`${n}
282
282
 
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(`
283
+ ${Nl}`;return zh(t,s,Uh)}function Sk(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 kk(t){let e=new Set;Wh(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Wh(e,n.availableModels),e}function Wh(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)}}}Yl();he();var Ik=2,cd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ik}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 gn(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 nm.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 k=await Kh({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(k){let $=Zh(k.synopsis,S);$&&em($)&&(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=${tm($)}`))}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 k=S instanceof Error?S.message:String(S);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${k}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:b,iter:p,lastError:k}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:k})}}else{let f=await dd({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=Zh(f.synopsis,r);p&&em(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=${tm(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 Zh(t,e){let n=Qh(e),s=Vh(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 em(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 tm(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 Ft from"fs/promises";function sm(t){return t==="summary"?"summary":"inline"}var Vl=256;function rm(t,e){return e!=="summary"?t:t.map(xk)}function xk(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(im));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Ql(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function Ck(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function im(t){if(Ck(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=Ql(e.text)),typeof e.content=="string"?n.content=Ql(e.content):e.content&&typeof e.content=="object"&&(n.content=im(e.content)),n}function Ql(t){if(typeof t=="string"&&t.length>Vl){let e=t.length-Vl;return`${t.slice(0,Vl)}\u2026[+${e} chars omitted from summary export]`}return t}var Ak=2048;function om(t){let e=new Set,n=s=>{if(am(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 am(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function Rk(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 Zl(t,e){if(!Rk(t))return t;let n=t.params,s=n.update,r=await Gl(s,e);return{...t,params:{...n,update:r}}}async function Gl(t,e){if(typeof t=="string"){if(t.length<=Ak)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 Gl(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Gl(r,e);return n}return t}async function dm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await Xl(n,e);return s===n?t:{...t,params:s}}async function Xl(t,e){if(am(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await Xl(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 Xl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var No=/^[A-Za-z0-9_-]+$/,Tk=1e3,ld=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Tk}async append(e,n){if(No.test(e))return this.enqueue(e,async()=>{await Ft.mkdir(_.sessionDir(e),{recursive:!0});let s=await Zl(n,i=>ul(e,i)),r=JSON.stringify(s)+`
284
+ `;await Ft.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(No.test(e))return this.enqueue(e,async()=>{await Ft.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Zl(i,o=>ul(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
285
285
  `)+`
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(`
286
+ `;await Ft.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(No.test(e))return this.enqueue(e,async()=>{let s;try{s=await Ft.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 Ft.writeFile(_.historyFile(e),i.join(`
288
288
  `)+`
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})
289
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!No.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Ft.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 qa(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await dm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(No.test(e))return this.enqueue(e,async()=>{try{await Ft.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await jp(e);try{await Ft.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();fd();Tr();td();Rt();Rt();en();_l();var um=900*1e3,Fk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pd=$k(Fk,16),hd=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>Ls.spawn(a)),this.store=s??new id,this.tombstones=r.tombstones??new od,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new ld({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 cd({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)=>{await this.dispatchCompactionSwap(a,c,d)}}),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 dispatchCompactionSwap(e,n,s){let r=this.get(e);if(!r){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s});return}let i=this.compactionTailK;try{if(await r.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performCompactionSwap(r,n,i,s);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),r.broadcastCompactionPhase({phase:"deferred"});let a=r.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,a)}catch(o){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${o instanceof Error?o.message:String(o)}, 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 a=await this.store.read(e).catch(()=>{});a?.synopsis&&a.summarizedThroughEntry!==void 0&&this.dispatchCompactionSwap(e,a.synopsis,a.summarizedThroughEntry);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=await this.histories.load(e).catch(()=>[]);if(o.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${o.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),this.synopsisCoordinator.scheduleCompaction(e);return}await this.performCompactionSwap(n,i.synopsis,s,i.summarizedThroughEntry)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performCompactionSwap(e,n,s,r){try{await e.swapUpstream({artifact:n,tailK:s,summarizedThroughEntry:r}),e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"])}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await gi(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_${pd()}`,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 Ci({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 gn(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:yi,clientInfo:{name:"hydra",version:fe}});o=m.agentCapabilities,i.authMethods=qo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ns(m,i)}let a;try{let m=fm(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(()=>{}),Ns(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=ou(a??{}),d=e.agentModes??su(iu(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 wi({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=nu(a??{}),f=su(ru(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 bi({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 Ci({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 wi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await bi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Ci({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 Er.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 gn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:md.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:yi,clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),Ns(p,r)}if(r.authMethods=qo(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(Ok(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!qh(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=`${yn}${pd()}`,v=new Date().toISOString(),b=p.updatedAt??v,S={sessionId:y,lineageId:Lo(),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 k=Wl(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 gn(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:yi,clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=qo(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=nu(a),l=ru(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Si(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=iu(a),p=ou(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(()=>{}),Ns(hm(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 gn(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:yi,clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=qo(o.authMethods);let c=fm(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=nu(d),u=su(ru(d)),f=iu(d),p=ou(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(()=>{}),Ns(hm(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 gn(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:yi,clientInfo:{name:"hydra",version:fe}});a.authMethods=qo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ns(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 gn(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=Ei({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:gm(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=Lk(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return qa(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:Bk(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=Ii(r.update.prompt),o=Ll(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(yn))return;let n=yn+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 Wo(n.sessionId),c=Ei({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 Wo(s.sessionId),i=Ei(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=>Wo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Ei({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=>Wo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Ei(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=Lo(),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 mm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of om(o)){let l=await Hp(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=`${yn}${pd()}`;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=Ol(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=Dk(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 mm(e),m=d==="synthesis",y={...s,lineageId:Lo(),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=jo({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:fe,machine:md.hostname()}),b=`${yn}${pd()}`;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 gn(f,[],{npmRegistry:this.npmRegistry}),k=await dd({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(b,{synopsis:k.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(k){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${k.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 Up(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Er.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Rr(_.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 Wo(e),i=Ei(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 Ah(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<um),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${um/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 Ok(t,e){if(typeof t!="string"||t.length===0)return!1;let n=zo.resolve(t),s=zo.resolve(e);return n===s||n.startsWith(s+zo.sep)}function Lk(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 Wl({sessionId:t.sessionId,lineageId:e?.lineageId??Lo(),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:gm(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 gm(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 Bk(t){return t?{...t}:void 0}function fm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function gd(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=Nk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function nu(t){return gd(t,{nestedKey:"models",configId:"model",fromObject:e=>qn(e.currentModelId)??qn(e.currentModel)??qn(e.modelId)??qn(e.model),fromConfig:e=>qn(e.currentValue)})}function Ns(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 pm(t){return/^[A-Za-z0-9_\-./=:@]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function hm(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 ${pm(s.cwd)} && ${[s.command,...s.args].map(pm).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 qo(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 qn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Nk(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 su(t){return t.length>0?t:void 0}function ru(t){return gd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=xi(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=xi(e.options);return n.length>0?n:void 0}})??[]}function iu(t){return gd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=Fo(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=Fo(e.options);return n.length>0?n:void 0}})??[]}function ou(t){return gd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>qn(e.currentModeId)??qn(e.currentMode)??qn(e.modeId)??qn(e.mode),fromConfig:e=>qn(e.currentValue)})}function Dk(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 mm(t){try{let e=await Er.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 Wo(t){try{let e=await Er.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ei(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Ar?!1:e?!0:void 0}import{spawn as Hk}from"child_process";import*as Mi from"fs";import*as Ds from"fs/promises";import*as ym from"path";var yd=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 Uk=1e3,jk=6e4,au=3e3,Pi=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??Uk,this.restartCapMs=r.restartCapMs??jk;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 Ds.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()},au);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 Ko(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Ko(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 Ko(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 Ko(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 Ko(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{}},au);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 yd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ds.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=ym.join(this.adapter.paths.dir(),n),r;try{let i=await Ds.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&du(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+au;for(;Date.now()<i&&du(r);)await new Promise(o=>setTimeout(o,50));if(du(r))try{process.kill(r,"SIGKILL")}catch{}}await Ds.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=Mi.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
294
  `);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}
295
+ `),o.end();return}let u=et(d),f=[...l,...r.args].map(et),p;try{p=Hk(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{Mi.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
297
297
  `,{encoding:"utf8",mode:384})}catch(h){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
298
298
  `)}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"}
299
+ `)}),p.on("exit",(h,m)=>{try{Mi.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
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
+ `);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 du(t){try{return process.kill(t,0),!0}catch{return!1}}function Ko(t,e){return t.code=e,t}he();var qk={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},wd=class extends Pi{constructor(e,n,s={}){super(e,qk,n,s)}};he();var Wk={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},bd=class extends Pi{connected=new Map;constructor(e,n,s={}){super(e,Wk,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 vd=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();fi();he();import*as Yo from"fs/promises";import*as Sd from"path";var Jo=t=>{process.stderr.write(t+`
302
+ `)};function cu(t){Jo=t??(e=>process.stderr.write(e+`
303
+ `))}async function wm(t,e){let n=Nn();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=Sd.join(_.agentsDir(),n),a;try{a=await Yo.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;Jo(`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=Sd.join(o,d),p;try{p=await Yo.readdir(f,{withFileTypes:!0})}catch(h){Jo(`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=Sd.join(f,m);try{await Yo.rm(y,{recursive:!0,force:!0}),Jo(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(v){Jo(`hydra-acp: prune: failed to remove ${y}: ${v.message}`)}}}}function bm(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 vl(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 lu(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 ${zk(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 vm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await lu({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 zk(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`}en();Vo();he();wr();import*as Im from"path";import{createHash as Jk,randomBytes as Yk,timingSafeEqual as Vk}from"crypto";var xm="hydra_session_",Qk=3600*24*30,Sm=12,Gk=32,Xk=50;function Zk(){return Im.join(_.home(),"session-tokens.json")}function km(t){return Jk("sha256").update(t).digest("hex")}function Cm(t){return Yk(t).toString("hex")}function eI(){return Cm(Sm).slice(0,Sm*2)}function tI(){return`${xm}${Cm(Gk)}`}var kd=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=Zk(),s=await mn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(nI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=tI(),s=km(n),r=eI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Qk,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(xm))return;let n=km(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||!Vk(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(()=>{})},Xk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Gt(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 nI(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")}cs();var Am="Bearer ",Id=class{constructor(e){this.token=e}token;async validate(e){return sI(e,this.token)?"service":void 0}},xd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Cd=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 Rm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Am)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Am.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Tm(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 Ad=class{tokens=new Map;mint(e,n){let s=di();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 sI(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 Rd=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();pu();Tr();Pd();import*as yu from"fs";import*as Xo from"os";import*as Jm from"path";import*as wu from"readline";Us();Un();function Md(t){let e=MI(t),n=_I(e),s=[];$I(s,t),FI(s,e,n);let r=s.join(`
304
304
  `);return r.endsWith(`
305
305
  `)||(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}
306
+ `),r}function MI(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=Wn(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 $I(t,e){let n=e.session,s=rt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Pr(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?`${mu(a.size)}`:void 0;c.push(d?`${mu(a.used)} / ${d} tokens`:`${mu(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 FI(t,e,n){if(!e.some(d=>OI(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(`> ${Pr(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(`> _${Pr(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(`- ${BI(l.status)} ${LI(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} ${Pr(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Pr(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Pr(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function OI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function LI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Pr(t.title)}${n}`}function BI(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 Pr(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function mu(t){return t.toLocaleString("en-US")}Rt();en();Ao();Us();function NI(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=>DI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function DI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Dm(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:Dm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Dm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function HI(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var UI=5,jI=200,Hm=30;async function qm(t,e,n={}){let s=NI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??UI,i=n.maxSessions??jI,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=qI(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 qI(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=WI(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 WI(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=zI(a).filter(d=>HI(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:QI(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 zI(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=_d(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ct(s.text):_d(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(YI(s))return[];let i=_d(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=VI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return KI(s);default:return[]}}function KI(t){let e=Um(t,"name"),n=Um(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=jm(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=jm(i);if(a.length>0){let c={kind:"tool-input",text:Ee(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=JI(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function JI(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 YI(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 _d(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 VI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=_d(n);s.length>0&&e.push(s)}return e.join("")}function Um(t,e){let n=t[e];return typeof n=="string"?n:void 0}function jm(t){try{return JSON.stringify(t)}catch{return""}}function QI(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-Hm),c=Math.min(s.length,o+i.length+Hm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as zm}from"crypto";function Wm(t){let e=zm(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 gu(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(Wm({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Wm({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Fi(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Fi(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=zm(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 $d=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Km(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!br(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Ym(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 qm(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=Fi(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 lu({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=>Jm.join(Xo.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),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":sm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=jo({record:m.record,history:h==="summary"?rm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:Xo.hostname(),hydraHost:Km(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=_i(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=jo({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:fe,machine:Xo.hostname(),hydraHost:Km(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Md(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=Pn(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,k=await e.getHistory(f).catch(()=>[])??[];if(k.length>0&&n.compaction){let T=h??0,$=k.length,j=k.slice(T).reduce((N,Z)=>N+JSON.stringify(Z.params).length,0);b=fu(j);let K=p?.currentModel,H=k.at(-1).recordedAt,L=p?.currentUsage;v=Em({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,k=[];if(m){p&&(v=m.onBroadcast($=>{l.raw.writableEnded||(b?l.raw.write(JSON.stringify($)+`
310
+ `):(k.push($),k.length>S&&k.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(;k.length>0;){let $=k.splice(0,k.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=wu.createInterface({input:yu.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(!$d.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...$d].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 k=_.historyFile(S.sessionId),T=await a(S.sessionId,k,h,m);T.exhausted||b.push(T)}catch(k){if(k.code==="ENOENT")continue;throw k}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,k=1/0;for(let $=0;$<b.length;$++){let F=b[$];F.current!==null&&F.current.ts<k&&(k=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 k of b)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($=>$.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let $ of y)if(!$d.has($))return l.code(400).send({error:`kind "${$}" is not queryable; allowed kinds: ${[...$d].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),k=yu.createReadStream(S),T=wu.createInterface({input:k,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,N=L.sessionUpdate;if(typeof N!="string"||!v.has(N)||b!==void 0&&K.recordedAt<b)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)+`
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 k=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let $=`${m}::${y}`;T=k.filter(F=>`${F.source}::${F.reason}`!==$)}else T=[];if(T.length===k.length&&T.every(($,F)=>$.source===k[F].source&&$.reason===k[F].reason)){l.code(204).send();return}await b.write({...S,attentionFlags:T}),l.code(204).send()})}Rt();function Vm(t,e,n,s={}){t.get("/v1/agents",async()=>gi(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 gn(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 Qm(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var GI=/^[A-Za-z0-9._-]+$/;function Fd(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=XI(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){Zo(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){Zo(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){Zo(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){Zo(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){Zo(o,c)}})}function Zo(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 XI(t){let e=t.name;if(typeof e!="string"||!GI.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 Gm(t,e){Fd(t,"extension",e)}function Xm(t,e){Fd(t,"transformer",e)}function Zm(t,e){t.get("/v1/config",async()=>e)}import{z as Oi}from"zod";he();import*as js from"fs/promises";import*as sg from"path";import{randomBytes as ZI,scrypt as ex,timingSafeEqual as tx}from"crypto";import{promisify as nx}from"util";var rg=nx(ex);function bu(){return sg.join(_.home(),"password-hash")}var eg=32768,tg=8,ng=1,sx=64,rx=16,ig=128*1024*1024;async function og(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=ZI(rx),n=await rg(t,e,sx,{N:eg,r:tg,p:ng,maxmem:ig}),s=`scrypt$${eg}$${tg}$${ng}$${e.toString("hex")}$${n.toString("hex")}
315
+ `;await js.mkdir(_.home(),{recursive:!0}),await js.writeFile(bu(),s,{encoding:"utf8",mode:384})}async function Od(){try{return(await js.readFile(bu(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ld(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await js.readFile(bu(),"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 rg(t,o,a.length,{N:s,r,p:i,maxmem:ig});return c.length!==a.length?!1:tx(c,a)}var ix=Oi.object({password:Oi.string().min(1),label:Oi.string().min(1).max(256).optional(),ttlSec:Oi.number().int().positive().optional()}),ox=Oi.object({id:Oi.string().optional()}).optional();function ag(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=ax(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=ix.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Od())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Ld(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=ox.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 ax(t){return t.ip||"unknown"}Cr();Li();import{nanoid as xu}from"nanoid";td();Rt();en();import{randomBytes as cg}from"crypto";import*as lg from"os";import*as ug from"path";function le(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function fx(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 tn(t,e,n){let s=t.get(e);if(!s)throw le(z.SessionNotFound,n??`session ${e} not found`);return s}async function vu(t,e){let n=Fi(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=cg(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=gu({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 vx(d,t),d}function fg(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Tm({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=zn(n),a=new qt(o),c={clientId:`hydra_client_${xu(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=eh.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)),bx()}),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 le(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw le(-32602,"emit_message requires method");let v=tn(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==="queue"){if(h!=="session/prompt")throw le(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await v.emitToQueue(i.name,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 le(-32602,"client_broadcast requires an envelope object");return v.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 tn(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>mx(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 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:b,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=tn(e.manager,p,`child session ${p} not found`);return new Promise(v=>{let k=[],T=[],$=0,F=!1,j,K,H=!1,L=()=>{H||(H=!0,clearTimeout(N),j?.(),K?.(),v(F?{entries:k,truncated:!0}:{entries:k}))};j=y.onBroadcast(Z=>{let G=fx(Z);for(k.push(Z),T.push(G),$+=G;k.length>0&&(k.length>1e3||$>1048576);)k.shift(),$-=T.shift()??0,F=!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=>gx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>yx(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=>px(u,e)),a.onRequest("session/new",async u=>{let f=th.parse(u),p=Zt(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,v,b=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=cg(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,k,T=Fi(e);T!==void 0&&(b=[...b??[],...T.descriptors]);let $=gu({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:dg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...$?{mintMcpServersForSwap:$}:{}})}catch(N){throw v!==void 0&&v.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&&v!==void 0&&e.mcpTokenRegistry!==void 0){let N=y,Z=e.mcpTokenRegistry;v.complete(F),F.onClose(()=>{Z.unbind(N)})}if(S!==void 0&&k!==void 0&&e.mcpTokenRegistry!==void 0){let N=S,Z=e.mcpTokenRegistry;k.complete(F),F.onClose(()=>{Z.unbind(N)})}T!==void 0&&T.bindToSession(F);let j,K;try{j=Bd(a,F,c),{entries:K}=await F.attach(j,"full")}catch(N){throw await F.close({deleteRecord:!1}).catch(()=>{}),N}c.attached.set(F.sessionId,{sessionId:F.sessionId,clientId:j.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let N of K){if(a.isClosed())break;await a.notify(N.method,N.params).catch(()=>{})}})()});let H=Su(F),L=ku(F);return{sessionId:F.sessionId,...H?{modes:H}:{},...L?{models:L}:{},configOptions:F.buildConfigOptions(),_meta:Iu(e.manager,F,{clientId:j.clientId})}}),a.onRequest("session/attach",async u=>{let f=sh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=Zt(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 le(z.SessionNotFound,`session ${f.sessionId} not found`);let N=await e.manager.loadHistory(b),Z=f.clientId??`cli_${xu(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:wx(L)}}let k=!S;if(!S){let L=await e.manager.loadFromDisk(b),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=v!==void 0?{...Z,forwardedEnv:v}:Z;S=await vu(e,{...G,onInstallProgress:dg(a)})}let T=Bd(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,N=750;(async()=>{let Z=null;for(let G of F){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<F.length&&!a.isClosed();L++){let N=F[L],Z=a.notify(N.method,N.params).catch(()=>{});(L+1)%200===0&&await Z}S.replayPendingPermissions(T);let K=Su(S),H=ku(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:Iu(e.manager,S,{resurrected:k})}}),a.onRequest("session/detach",async u=>{let f=rh.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:{[At]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=ih.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Ar).map(oh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw le(z.InternalError,"agent registry unavailable");return gi(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=ah.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 vu(e,m);let y=Bd(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=Va.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=Va.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=ch.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),tn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Va.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),tn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=lh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),tn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=uh.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 tn(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 vu(e,k)}let y=Bd(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 k of v){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}m.replayPendingPermissions(y);let b=Su(m),S=ku(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Iu(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=hx(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=tn(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=>le(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=tn(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 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),tn(e.manager,y).forwardRequest(f,u)})})}async function px(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&&ug.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 v={};for(let[S,k]of Object.entries(process.env))typeof k=="string"&&(v[S]=k);Object.assign(v,h.env);let b=lg.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 Ns(p,a)}}function dg(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(Qa,n).catch(()=>{})}}function Su(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 ku(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 hx(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=Si(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 mx(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 tn(n.manager,r).addTransformer(i),{ok:!0}}async function gx(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 tn(n.manager,r).setAttentionFlag(e,i,s.payload),{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 le(z.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw le(z.InvalidParams,"hydra-acp/attention/clear requires string reason");return tn(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function wx(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]:Ja(e,n)}}function Iu(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 Mo(e.agentMeta,Ja(s,r))}function bx(){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:Mo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function vx(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 Bd(t,e,n,s,r){return{clientId:r??`cli_${xu(8)}`,connection:t,clientInfo:s}}var Nd=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 Sx}from"crypto";import{McpServer as kx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ix}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Tt}from"zod";function*Cu(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 nn(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var pg="Bearer ";function Bi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(pg))return;let n=e.slice(pg.length).trim();return n.length>0?n:void 0}function xx(t){let e=new kx({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 nn(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 nn(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 nn(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 nn({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 nn(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 nn(n)}),e}var Cx=1e4;function hg(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=xx(a),l=new Ix({sessionIdGenerator:()=>Sx()});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=Bi(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),Cx)}),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)})}nd();import{randomUUID as Ax}from"crypto";import{McpServer as Rx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Tx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as qs}from"zod";function Ex(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Px(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 Mx(t){let e=new Rx({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:qs.string().min(1).describe("Case-insensitive substring to search for."),limit:qs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:qs.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 nn({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 Cu(o)){if(u==="tool_call"&&!r)continue;let f=ki([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=Ex(u),m=Px(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 nn({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:qs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:qs.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 nn({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=ki(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:qs.string().optional(),file_path:qs.string().optional(),limit:qs.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 nn({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 Cu(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[k,T]of Object.entries(S))b.rawInput[k]=T;if(Array.isArray(y.locations))for(let k of y.locations){let T=k?.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 k=h.rawInput[S];if(typeof k=="string"&&k.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 nn({calls:u,truncated:f})}),e}var _x=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=Mx(a),l=new Tx({sessionIdGenerator:()=>Ax()});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=Bi(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 Dd=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 Hx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Ux}from"crypto";import{Server as $x}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Fx,ListToolsRequestSchema as Ox}from"@modelcontextprotocol/sdk/types.js";function gg(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new $x({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(Ox,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(Fx,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Hd(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=Bx(d,a.sendNotification);try{let u=await s(),f=await Nx(e.connection,t,c,o.params.arguments??{},u);return Dx(f,c)}catch(u){return Hd(u instanceof Error?u.message:String(u))}finally{l()}}),r}var Lx=15e3;function Bx(t,e,n=Lx){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 Nx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function Dx(t,e){if(t===null||typeof t!="object")return Hd(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Hd(`extension ${e} omitted content array`)}function Hd(t){return{content:[{type:"text",text:t}],isError:!0}}var jx=1e4;function yg(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=gg(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),jx)}),k=await Promise.race([v.sessionReady.catch(()=>{}),S]);if(b!==void 0&&clearTimeout(b),k===void 0)throw new Error("session not ready");return k.sessionId}),y=new Hx({sessionIdGenerator:()=>Ux()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Bi(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 kg(t,e){Yx(t);let n=t.daemon.tls?await Ni.readFile(et(t.daemon.tls.key)):void 0,s=t.daemon.tls?await Ni.readFile(et(t.daemon.tls.cert)):void 0;await Ni.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await Kx(t.daemon.logLevel),o=qx({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(Wx,{options:{handleProtocols:Op}}),ml(V=>{o.log.info(V)}),wl(V=>{o.log.info(V)});let a=await kd.load(),c=new Rd,d=new Ad,l=new Cd([new Id(e),new xd(a),d]),u=Rm({validator:l});o.addHook("onRequest",async(V,xe)=>{V.routeOptions.config?.skipAuth||V.url==="/acp"||V.url?.startsWith("/acp?")||await u(V,xe)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Wa(t,{onFetched:()=>{wm(h,b)}});cu(V=>o.log.info(V));let m={info:V=>o.log.info(V),warn:V=>o.log.warn(V)},y=V=>Ls.spawn({...V,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});Dp(t.compressToolContent);let v=new vd,b=new hd(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 wd(ap(t),void 0,{tokenRegistry:d}),k=new bd(dp(t),void 0,{tokenRegistry:d});Qm(o,fe,Hs(t));let T=new Nd,$=new Dd,F,j=()=>{if(F!==void 0)return F;let V=o.server.address();return F=`http://127.0.0.1:${V&&typeof V=="object"?V.port:t.daemon.port}`,F};Ym(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}),Vm(o,h,b,{npmRegistry:t.npmRegistry}),Gm(o,S),Xm(o,k),Zm(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]}),ag(o,{store:a,rateLimiter:c}),hg(o,T),mg(o,T),yg(o,T,$),fg(o,{validator:l,manager:b,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(V,xe)=>S.reportVersion(V,xe),onTransformerVersion:(V,xe)=>k.reportVersion(V,xe),transformers:k,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,N,Z=t.daemon.host,G=L;if(K&&n&&s){N=Jx({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let V=N.address();V&&typeof V=="object"&&(G=V.port)}await Ni.mkdir(_.home(),{recursive:!0}),await gp({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 b.reconcilePermissionFlags()}catch(V){o.log.warn(`permission flag reconcile failed: ${V.message}`)}b.resurrectPendingQueues().catch(V=>{o.log.warn(`queue replay scan failed: ${V.message}`)}),b.resumePendingCompactions().catch(V=>{o.log.warn(`compaction resume scan failed: ${V.message}`)});let X=t.daemon.agentSyncIntervalMinutes*60*1e3,ce=X>0?bm({registry:h,manager:b,intervalMs:X,logger:m}):void 0,Je=t.daemon.sessionGcIntervalMinutes*60*1e3,er=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,bs=Je>0?vm({manager:b,intervalMs:Je,maxAgeMs:er,logger:m}):void 0;return{app:o,manager:b,registry:h,extensions:S,transformers:k,mcpTokenRegistry:T,extensionMcp:$,processRegistry:d,shutdown:async()=>{bs&&bs(),ce&&ce(),clearInterval(f),clearInterval(p);let V=async(xe,Gn)=>{try{await Gn()}catch(ve){o.log.warn(`shutdown step ${xe} failed: ${ve instanceof Error?ve.message:String(ve)}`)}};await V("sessionTokenStore.flush",()=>a.flush()),await V("extensions.stop",()=>S.stop()),await V("transformers.stop",()=>k.stop()),await V("manager.closeAll",()=>b.closeAll()),await V("manager.flushSynopsis",()=>b.flushSynopsis(3e4)),await V("manager.shutdownSynopsis",()=>b.shutdownSynopsis()),await V("manager.flushMetaWrites",()=>b.flushMetaWrites()),await V("manager.flushHistoryWrites",()=>b.flushHistoryWrites()),ml(null),wl(null),cu(null),N&&await V("tlsTerminator.close",()=>new Promise(xe=>N.close(()=>xe()))),await V("app.close",()=>o.close());try{bg.unlinkSync(_.pidFile())}catch{}await V("fileStream.flushSync",()=>i.flushSync())}}}async function Kx(t){let e=await zx({file:_.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=wg.destination(2);return{stream:wg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function Jx(t){let e=Sg.createServer(t.tlsOptions,n=>{let s=vg.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 Yx(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.`)}_r();en();Vo();ea();async function Ag(t={}){let e=await be(),n=await xo();if(await Ud(e)){let r=await Ui();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
316
+ `);return}if(oi(t,"foreground")){process.title="hydra-daemon";let r=await kg(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
317
317
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
318
318
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
319
319
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
320
320
  `),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.
321
+ `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}jd(),await qd(e);let s=await Ui();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
322
+ `)}async function Rg(){let t=await Ui();if(!t){process.stdout.write(`No running daemon found.
323
323
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
324
324
  `)}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}...
325
+ `)}}async function Tg(){let t=await be();await xo();let e=await Ui();if(e&&En(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
326
326
  `);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.
327
+ `),process.exit(1)}await tC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
328
328
  `),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}
329
+ `);if(jd(),await qd(t),await Ud(t)){let n=await Ui();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
330
+ `)}}async function tC(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!En(t))return!0;await eC(50)}return!1}async function Eg(t){await Hi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Pg(){let t=await Ui();if(!t){process.stdout.write(`Daemon: not running
331
+ `),process.stdout.write(`CLI version: ${fe}
332
+ `);return}let e=En(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 be();n=await Mr(o),s=Hs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
334
334
  `),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}
335
+ `);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}
336
+ `);return}process.stdout.write(`CLI version: ${fe}
337
337
  `),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)+`
338
+ `),r||process.stdout.write(Cg.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Cg.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function Ui(){return us()}Ve();cs();zs();kr();Ao();Un();na();Tr();import*as wn from"fs/promises";import*as qg from"os";import*as bn from"path";Xd();async function Wg(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
339
  `);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
340
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
341
341
  `);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)+`
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(k=>k.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=>Ji(y,u)),p={columns:t.columns??e.tui.sessionColumns??zi,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=Yi(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ks(Ki,h,m,p)+`
343
+ `);for(let y of f)process.stdout.write(Ks(y,h,m,p)+`
344
344
  `);l>0&&process.stdout.write(`
345
345
  ... ${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}
346
+ `)}async function zg(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
347
+ `),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
348
  `),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}
349
+ `)}async function Kg(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
350
+ `),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
351
  `),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)}
352
+ `)}async function Jg(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
353
  `);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}.
354
+ `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${qi(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
355
355
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
356
356
  `),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}
357
+ `)}async function Yg(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 yr(),r=await ji(),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
359
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
360
360
  `)||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}
361
+ `);return}let c=e==="."?bC(o,t):e;await wn.mkdir(bn.dirname(bn.resolve(c)),{recursive:!0}),await wn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
362
+ `)}async function Vg(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 hC(t);if(r!==null){let o=mC(r.raw);n=Md(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${bn.basename(t,bn.extname(t))}-${a}.md`}else{let o=await yr(),a=await ji(),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
364
  `),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
365
  `)||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
366
+ `);return}let i=e==="."?s:e;await wn.mkdir(bn.dirname(bn.resolve(i)),{recursive:!0}),await wn.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
367
+ `)}async function hC(t){try{if(!(await wn.stat(t)).isFile())return null}catch{return null}let e=await wn.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 mC(t){try{return Pn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
369
+ `),process.exit(1)}}async function Qg(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=bn.resolve(e.cwd);try{(await wn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
371
371
  `),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.
372
+ `),process.exit(1)}n=a}let s;t==="-"?s=await wC():s=await wn.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 be();yC(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
374
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
375
375
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
376
376
  `:`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)+`
377
+ `)}function gC(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 yC(t,e){let n;try{n=Pn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
378
+ `),process.exit(1)}let s=gC(n),r=Ji(s),i={columns:Gd,cwdMaxWidth:e},o=Yi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Ks(Ki,o,a,i)+`
379
+ `),process.stdout.write(Ks(r,o,a,i)+`
380
380
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
381
381
  lineage: ${n.session.lineageId}
382
382
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -384,75 +384,75 @@ origin session: ${n.session.sessionId}
384
384
  origin upstream: ${c}
385
385
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
386
386
  `:`
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+`
387
+ `))}async function wC(){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 bC(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 Gg(t,e={}){let n=await be(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await _t(n),l=e.cwd?bn.resolve(e.cwd):process.cwd(),u=await Kn(d,{cwd:l,all:!0}),f=Vd(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}=vC(e.host,n),a=rt(s),c=pp({host:r,port:i,sessionId:a});process.stdout.write(c+`
389
389
  `),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)+`
390
+ `)}function vC(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=jg(t,Tn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=jg(e.daemon.publicHost,Tn);return{host:n,port:s,isFallback:!1}}return SC(e.daemon.host)?{host:kC(),port:e.daemon.port,isFallback:!1}:br(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 SC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function kC(){let t=qg.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function jg(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}}Wu();Xd();Hu();Ve();he();ea();zs();var rA={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function rc(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Xi(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function ic(t){let e=rA[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.
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?qi(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:Xi(p.name,f.map(y=>y.name)),status:Xi(p.status,f.map(y=>y.status)),version:Xi(p.version,f.map(y=>y.version)),pid:Xi(p.pid,f.map(y=>y.pid)),restarts:Xi(p.restarts,f.map(y=>y.restarts)),started:Xi(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
392
  `);for(let y of f)process.stdout.write(m(y)+`
393
393
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
394
394
  `)}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
395
  `),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.
396
+ `),process.exit(2);return}await be();let u=await Wi(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${py(e.singular)} '${d}' already exists in config.
397
+ `),process.exit(1);return}let h=Kd(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 Ru(u),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
398
+ `);let v={name:d,...y};try{let b=await Fe(n,{method:"POST",body:v,rethrowNetworkError:!0});if(b.ok){let S=b.body,k=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${k}
399
+ `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${b.status}${rc(b.body)}). Restart the daemon to apply.
400
400
  `)}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)}).
401
+ `),process.exit(2);return}await be();let l=await Wi(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${py(e.singular)} '${d}' not found in config.
402
+ `),process.exit(1);return}delete f[d],u[e.plural]=f,await Ru(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
403
+ `);try{let p=await Fe(`${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}${rc(p.body)}).
405
405
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
406
406
  `)}}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)}
407
+ `),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}${rc(u.body)}
408
408
  `),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)}
409
+ `)}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}.
410
+ `);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}${rc(y.body)}
411
411
  `),h+=1;continue}let v=y.body,b=v.pid!=null?` pid=${v.pid}`:"";process.stdout.write(`${m.name}: ${v.status}${b}
412
412
  `)}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
413
+ `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Wd(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 Hi(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 py(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Fr=ic("extension"),hy=Fr.list,my=Fr.add,gy=Fr.remove,yy=Fr.start,wy=Fr.stop,by=Fr.restart,vy=Fr.logs;var Or=ic("transformer"),Sy=Or.list,ky=Or.add,Iy=Or.remove,xy=Or.start,Cy=Or.stop,Ay=Or.restart,Ry=Or.logs;tf();ta();Li();Cr();Ve();kr();_r();Rt();en();Ka();of();import SA from"os";import{spawn as kA}from"child_process";async function IA({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 xA(c,s),u=await rf(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
415
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
416
416
  `),{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}
417
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:SA.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 xA(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
419
  `),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
420
  ${s.join(`
421
421
  `)}
422
422
  `);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
423
  `),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)+`
424
+ `),process.exit(2)}async function Vy(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(()=>(tf(),My)),s=await n(t,"hydra agent auth"),r=await be(),i=await _t(r);await Ws(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await $r(i.wsUrl,o),c=zn(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:fe}})}catch{}let l;try{l=await IA({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:kA})}finally{a.close()}process.exit(l.exitCode)}ea();tl();zs();async function Qy(t){let e=oi(t,"force");if(await Od()&&!e){let r=await ui("Current password: ");await Ld(r)||(process.stderr.write(`Wrong password.
426
+ `),process.exit(1))}let n=await ui("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
427
+ `),process.exit(2));let s=await ui("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
428
+ `),process.exit(1)),await og(n),process.stdout.write(`Password set.
429
+ `)}async function Gy(){let e=(await Fe("/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:hc(n.id,s.map(o=>o.id)),label:hc(n.label,s.map(o=>o.label)),createdAt:hc(n.createdAt,s.map(o=>o.createdAt)),expiresAt:hc(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
431
  `);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}
432
+ `)}async function Xy(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
433
+ `),process.exit(2));let e=await Fe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
434
434
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
435
435
  `),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}
436
+ `),process.exit(1)}function hc(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Vs from"fs";Ve();kr();_r();af();Rt();var mc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(cf(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(df(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(!df(e)&&!cf(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(df(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(!cf(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=Zt(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 df(t){return"method"in t&&"id"in t&&t.id!==void 0}function cf(t){return!("method"in t)&&"id"in t}yc();en();he();Ro();import{writeFileSync as PA}from"fs";var MA=t=>{PA("/proc/self/comm",t)};function io(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??MA;try{s(e.commName??Bn())}catch{}}function oo(t,e=Bn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function bc(t){io(oo(process.argv.slice(2)),{commName:"hydra-shim"});let e=await be(),n=t.target??await _t(e);n.isLocal&&!t.target&&await Ws(e);let s=new mc,r=Ga(process.stdin,process.stdout),i=n.isLocal?async()=>(await _t(await be())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new ro({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await BA(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 NA(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(iw("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&jA(i)){e.send({jsonrpc:"2.0",id:i.id,result:Ur(i.params)});return}$A(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(iw("client\u2192daemon",i),s.observeFromClient(i),HA(i)){e.send(UA(i));return}if(DA(i)){if(t.sessionId){e.send(qA(i,t.sessionId));return}let o=i;t.agentId&&(o=wc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=wc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=wc(o,{title:r.name}),r.used=!0),t.model&&(o=wc(o,{model:t.model})),e.send(o);return}e.send(i)})}function $A(t,e,n){let s=FA(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=LA(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function FA(t){if(!OA(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function OA(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function LA(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function BA(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 NA(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
440
  `)}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(`
441
+ `)}}function DA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function HA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function UA(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 jA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function qA(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var WA=25*1024*1024,rw=!1,jr=null;function iw(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!rw){rw=!0;try{jr=_.shimWireLogFile(),Vs.mkdirSync(_.home(),{recursive:!0});let n=Vs.statSync(jr,{throwIfNoEntry:!1});n&&n.size>WA&&Vs.renameSync(jr,`${jr}.1`)}catch{jr=null}}if(jr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
442
+ `;Vs.appendFile(jr,n,()=>{})}catch{}}}function wc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Cr();Li();ta();Ve();kr();_r();Us();Rt();en();yc();import{mkdtempSync as tR,rmSync as nR}from"fs";import{tmpdir as sR}from"os";import{join as rR}from"path";function ow(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())}}}Gi();import zA from"chalk";import KA from"strip-ansi";var vc=new zA.Instance({level:3});function aw(t,e){if(t.length===0)return"";let n=Ys(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(JA(i,e));let r=s.join(`
443
443
  `);return r.endsWith(`
444
444
  `)||(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:
445
+ `),r}function JA(t,e){let n=ZA(t.body,e);return e==="ansi"?n=eR(n,t.bodyStyle):n=KA(n),n}var YA="\x1B[1m",VA="\x1B[96m",QA="\x1B[93m",GA="\x1B[0m",XA="\0";function ZA(t,e){let n=t.replace(/\^\^/g,XA);return e==="ansi"&&(n=n.replace(/\^\+/g,YA).replace(/\^C/g,VA).replace(/\^Y/g,QA).replace(/\^:/g,GA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function eR(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return vc.bold.yellowBright(t);case"heading-2":return vc.bold.cyanBright(t);case"heading-3":return vc.bold(t);case"dim":return vc.dim(t);default:return t}}var iR=1*1024*1024,dw="mcp__hydra-acp-stdin__";function cw(t,e){return{sessionId:t,prompt:e,_meta:{[At]:{ancillary:!0}}}}function oR(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 aR(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(dw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(dw))}async function lw(t){if(io(oo(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=tR(rR(sR(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{nR(c,{recursive:!0,force:!0})}catch{}})}let e=await be(),n=t.target??await _t(e);n.isLocal&&!t.target&&await Ws(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await $r(n.wsUrl,s),i=zn(r),o=new qt(i),a=await cR({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:dR(n.baseUrl,n.token)});process.exit(a.exitCode)}function dR(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 cR(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?Ur(X):aR(X)?Ur(X):tw(X));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Ar,version:fe}})}catch{}let u=await fR(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=aw(h,c);if(h="",X.length===0)return;let ce=m>0?`
447
+ `:"";y(ce+X),m+=1},b=()=>{v(),f&&!p&&y(`
448
+ `),f=!1};e.onNotification("session/update",X=>{let ce=X?.update,Je=Wn(ce,{cwd:n.cwd});if(Je){if(Je.kind==="agent-text"){d?y(Je.text):h+=Je.text;return}if(Je.kind==="turn-complete"){b();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":v();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",cw(u,ce)),S=!0}catch(Je){a(`hydra-acp cat: prompt failed: ${Je.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(Je=>setTimeout(Je,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,N=!1,Z=async()=>{if(!L){L=!0;try{for(;H.length>0;){let X=H.shift();if(X===void 0)break;await k(X)}}finally{L=!1,N&&H.length===0&&await K(T)}}};if(r&&!n.sessionId)return n.prompt&&await k(""),await K(0),F;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),lR({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:k,onEof:()=>{N=!0,!L&&H.length===0&&K(T)},onError:X=>{a(`hydra-acp cat: stdin error: ${X.message}
451
+ `),T=1,N=!0,!L&&H.length===0&&K(T)},onPromptFailed:X=>{a(`hydra-acp cat: ${X.message}
452
+ `),T=1,N=!0,!L&&H.length===0&&K(T)}}),F;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let X=ow({scheduleFlushCheck:ce=>{let Je=setImmediate(ce);return()=>clearImmediate(Je)},onChunk:ce=>{H.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&&H.length===0&&K(T)}),s.on("error",ce=>{a(`hydra-acp cat: stdin error: ${ce.message}
453
+ `),T=1,N=!0,!L&&H.length===0&&K(T)}),F}let Se="";return s.on("data",X=>{Se+=typeof X=="string"?X:X.toString("utf8")}),s.on("end",()=>{N=!0,Se.length>0&&H.push(Se),Z()}),s.on("error",X=>{a(`hydra-acp cat: stdin error: ${X.message}
454
+ `),T=1,N=!0,!L&&H.length===0&&K(T)}),F}function lR(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??iR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(b,S)=>{let k=b.toString("base64");h=h.then(()=>n.write(s,k,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=uR(r.prompt,b.capacityBytes);e.request("session/prompt",cw(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 uR(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
456
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
457
457
  - \`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
458
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -467,49 +467,49 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
467
467
  User's question:
468
468
  ${t}`:`${s}
469
469
 
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}
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 fR(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Ar,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=oR(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 Zt(o._meta),o.sessionId}Ve();he();function Sc(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 uw(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 pR(t){try{return JSON.parse(t)}catch{return t}}function fw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function pw(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
471
+ `),process.exit(2));let e=Sc(t),n=await be(),s=uw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
472
+ `),process.exit(1)),process.stdout.write(`${fw(s)}
473
+ `)}async function hw(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
474
+ `),process.exit(2));let n=Sc(t),s=pR(e);try{await ls(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} = ${fw(s)}
476
+ `)}async function mw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
477
+ `),process.exit(2));let e=Sc(t);try{await ls(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
478
  `),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
479
+ `)}async function gw(t){let e=await be(),n=t?uw(e,Sc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
480
480
  `),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)+`
481
+ `)}function yw(){process.stdout.write(`${_.config()}
482
+ `)}Ve();cs();_r();en();zs();async function vw(t={}){let{report:e,configLoaded:n}=await hR();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
483
483
  `);return}process.stdout.write(`CLI: ${e.cli}
484
484
  `),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(`
485
+ `),e.daemonReachable&&(ww("Extensions",e.extensions),ww("Transformers",e.transformers)))}function ww(t,e){if(process.stdout.write(`
486
486
  ${t}:
487
487
  `),e.length===0){process.stdout.write(` (none)
488
488
  `);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}
489
+ `)}}async function hR(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await be()}catch{return{report:t,configLoaded:!1}}let n=await Mr(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 yr()}catch{return{report:t,configLoaded:!0}}let r=await ji(),i={Authorization:`Bearer ${s}`};return t.extensions=await bw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await bw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function bw(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 mR}from"child_process";import{accessSync as gR,constants as yR,statSync as wR}from"fs";import{delimiter as bR,join as vR}from"path";var SR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function kR(t){return SR.has(t)}function IR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function xR(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 CR(t){try{if(!wR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return gR(t,yR.X_OK),!0}catch{return!1}}function AR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(bR).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=vR(o,r+a);if(CR(c))return c}}function RR(t,e){let n=mR(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 Sw(t){let e=IR(t);if(e===void 0||kR(e))return!1;let n=AR(e);if(n===void 0)return!1;RR(n,xR(t))}lf();var Zs=!1,Hb=!1;function Ub(t){!t||Hb||(Hb=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
491
+ `))}async function mT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Po(),kp));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],k=b.slice(1),{flags:T}=Kc(v);if(qb(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??gt(T,"agent");if(!$){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
493
+ `),process.exit(2);return}let F=await Wb(cl(T),{allowPrompt:!1}),j=gt(T,"name"),K=gt(T,"model");Zs=!0;let H=T["dangerously-skip-permissions"]===!0;Ub(H);let L={agentId:$,agentArgs:k,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 bc(L);return}zf(e)===void 0&&!e.some(v=>v==="--prompt"||v.startsWith("--prompt="))&&Sw(e);let{positional:s,flags:r}=Kc(e);if(qb(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${gT()}
494
+ `);return}if(r.help===!0){Jf();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=gt(r,"name"),d=gt(r,"agent"),l=gt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Ub(u);let f=cl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Wb(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){Zs=!0,await jb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}Zs=!0;let v={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(v.sessionId=m),y!==void 0&&(v.target=y),await bc(v);return}switch(a){case"shim":{Zs=!0;let v={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(v.sessionId=m),y!==void 0&&(v.target=y),await bc(v);return}case"cat":{let v=zf(e),b=typeof r.prompt=="string"?r.prompt:void 0,S=v??b,k=gt(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 $=Kf(r,"stream-threshold");$!==void 0&&(T.streamThreshold=$);let F=Kf(r,"stream-bytes");F!==void 0&&(T.streamBufferBytes=F),d!==void 0&&await oc(d),Zs=!0,await lw(T);return}case"version":{Zs=!0,await vw({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 Pg();return}if(S==="start"){await Ag(r);return}if(S==="stop"){await Rg();return}if(S==="restart"){await Tg();return}if(S==="log"||S==="logs"){await Eg(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=gt(r,"columns"),S;if(b!==void 0)try{S=Ug(b)}catch(k){process.stderr.write(`${k.message}
497
+ `),process.exit(2);return}await Wg({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 fy(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 uy(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 zg(s[2]);return}if(v==="remove"){await Kg(s[2]);return}if(v==="collect"){let b=gt(r,"max-age-days"),S=gt(r,"limit"),k={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}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
499
+ `),process.exit(2);return}k.limit=T}await Jg(k);return}if(v==="export"){let b=gt(r,"out"),S=gt(r,"tools");await Yg(s[2],b,S);return}if(v==="transcript"){let b=gt(r,"out");await Vg(s[2],b);return}if(v==="import"){let b=gt(r,"cwd");await Qg(s[2],{replace:r.replace===!0,info:r.info===!0,...b!==void 0?{cwd:b}:{}});return}if(v==="share"){let b=gt(r,"host"),S=gt(r,"cwd");await Gg(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],k=b[1],T=b.slice(2);if(S===void 0||S==="list"){await hy();return}if(S==="add"){await my(k,T);return}if(S==="remove"){await gy(k);return}if(S==="start"){await yy(k);return}if(S==="stop"){await wy(k);return}if(S==="restart"){await by(k);return}if(S==="log"||S==="logs"){await vy(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],k=b[1],T=b.slice(2);if(S===void 0||S==="list"){await Sy();return}if(S==="add"){await ky(k,T);return}if(S==="remove"){await Iy(k);return}if(S==="start"){await xy(k);return}if(S==="stop"){await Cy(k);return}if(S==="restart"){await Ay(k);return}if(S==="log"||S==="logs"){await Ry(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 Ku();return}if(v==="refresh"){await ac();return}if(v==="install"){await Yu(s[2]);return}if(v==="sync"){await Vu(s[2]);return}if(v==="set"){await Gu(s[2],s[3]);return}if(v==="pin"){await Xu(s[2],s[3]);return}if(v==="add"){let b=e.indexOf(a),S=e.slice(b+1);await Zu(S[1],S.slice(2));return}if(v==="remove"){await ef(s[2]);return}if(v==="log"||v==="logs"){let b=e.indexOf(a),S=e.slice(b+2),{name:k,rest:T}=Wd(S);await Qu(k,T);return}if(v==="auth"){await Vy(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 ac();return}if(v==="pin"){await dc(!0);return}if(v==="unpin"){await dc(!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 Qy(r);return}process.stderr.write(`Unknown auth password action: ${b}
505
+ `),process.exit(2);return}if(v===void 0||v==="list"){await Gy();return}if(v==="revoke"){await Xy(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 gw(s[2]);return}if(v==="get"){await pw(s[2]);return}if(v==="set"){await hw(s[2],s[3]);return}if(v==="unset"){await mw(s[2]);return}if(v==="path"){yw();return}process.stderr.write(`Unknown config subcommand: ${v}
507
+ `),process.exit(2);return}case"tui":Zs=!0,await jb(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
508
+ `),Jf(),process.exit(2)}}async function jb(t,e){let n=gt(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 oc(e.agentId),io(oo(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Db(),Nb)),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=Kf(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Kf(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 qb(t){let e=np(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
510
510
 
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)});
511
+ `),Jf(),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 Wb(t,e){try{return await Ep(t,e)}catch(n){se({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`${n.message}
512
+ `),process.exit(1)}}function gT(){try{let t=pT(fT(import.meta.url));return JSON.parse(uT(hT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Jf(){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 zb(){if(!Zs)try{let t=await ua();t&&process.stderr.write(`\u2728 ${fa(t)}
514
+ `)}catch{}}mT().then(zb).catch(async t=>{se({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`hydra-acp: ${t.message}
515
+ `),await zb(),process.exit(1)});