@hydra-acp/cli 0.1.93 → 0.1.94

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,31 +1,32 @@
1
1
  #!/usr/bin/env node
2
- var Kb=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var Uf=(t,e)=>{for(var n in e)Kb(t,n,{get:e[n],enumerable:!0})};import*as ge from"path";import*as Hc from"os";function Ge(t){let e=Hc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function Xb(){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[Gb];if(t&&t.length>0)return ge.resolve(t);let e=Xb();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(Hc.homedir(),".hydra-acp")}var Gb,_,he=J(()=>{"use strict";Gb="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 ri from"fs/promises";function ii(){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 oi(){try{let e=(await ri.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function mr(){let t=await oi();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function ai(t){await ri.mkdir(_.home(),{recursive:!0}),await ri.writeFile(_.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function ko(){let t=await oi();if(t)return t;let e=ii();return await ai(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
- `),e}var is=J(()=>{"use strict";he()});import*as It from"fs/promises";import*as Wf from"fs";import*as Cn from"path";import{randomBytes as Zb}from"crypto";async function Yt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await ev(t,r,n)}async function ev(t,e,n={}){let s=await tv(t),r=nv(s);await It.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${sv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await It.writeFile(i,e,o),await It.rename(i,s)}catch(o){throw await It.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{Wf.chmodSync(s,n.mode)}catch{}}async function tv(t){let e;try{e=await It.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await It.readlink(t),s=Cn.isAbsolute(n)?n:Cn.resolve(Cn.dirname(t),n);try{let r=await It.realpath(Cn.dirname(s));return Cn.join(r,Cn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function pn(t){let e;try{e=await It.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 nv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function sv(){return Zb(4).toString("hex")}var gr=J(()=>{"use strict"});import*as Ps from"fs/promises";import{homedir as Uc}from"os";import{z as q}from"zod";function Jf(t){return t.tui.inAppSelection??t.tui.mouse}function Vf(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Yf(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function Ma(){return await fv(),await pn(_.config())??{}}async function fv(){let t;try{t=await Ps.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await Ps.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await Ps.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 _a(){let t=await Ma(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await Ps.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 ai(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Yt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
- `)}async function we(){return await _a(),jc.parse(await Ma())}async function os(t){await _a();let e=await Ma();t(e),jc.parse(e),await Yt(_.config(),e,{mode:384})}async function Io(t,e){await os(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function $a(t){await os(e=>{e.defaultAgent=t})}async function Qf(t,e){await os(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function Gf(t,e){await os(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 os(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 Xf(t){await os(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Zf(){let t=await Ma();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Xe(t){return t==="~"||t==="$HOME"?Uc():t.startsWith("~/")?Uc()+t.slice(1):t.startsWith("$HOME/")?Uc()+t.slice(5):t}var Kf,rv,An,iv,ov,av,dv,cv,zf,lv,uv,jc,Je=J(()=>{"use strict";he();is();gr();Kf="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",rv=q.object({cert:q.string(),key:q.string()}),An=55514,iv=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(An),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:rv.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),ov=q.object({url:q.string().url().default(Kf),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),av=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()}),dv=q.object({packageSpec:q.string().optional()}),cv=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()}),zf=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),lv=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)}),uv=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:iv.default({}),registry:ov.default({url:Kf,ttlHours:24,pinned:!1}),agents:q.record(q.string(),av).default({}),agentOverrides:q.record(q.string(),dv).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(zf,lv).default({}),transformers:q.record(zf,uv).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:cv.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 yr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Wc(t){return{httpScheme:"https",wsScheme:"wss"}}function zc(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 ${Fa(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${Fa(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=pv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${Fa(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${Fa(t)}`);let i=yr(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=An;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function ep(t){let e=t.port!==void 0&&t.port!==An?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function pv(t){try{return new URL(t)}catch{return null}}function Fa(t){return t.length>80?`${t.slice(0,77)}...`:t}var xo=J(()=>{"use strict";Je()});function wr(t,e){return`${t}:${e}`}function tp(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function hv(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 mv(){let t=await pn(_.remotes());return t===void 0?{version:1,entries:{}}:gv(t)}function gv(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 Kc(t){await Yt(_.remotes(),t,{mode:384})}var Oa,Jc=J(()=>{"use strict";he();gr();Oa=class t{data;constructor(e){this.data=e}static async load(){let e=await mv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(tp(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Kc(i),new t(i)}get(e,n){let s=this.data.entries[wr(e,n)];if(s&&!tp(s,Date.now()))return s}async set(e,n,s){this.data.entries[wr(e,n)]=s,await Kc(this.data)}async delete(e,n){let s=wr(e,n);return s in this.data.entries?(delete this.data.entries[s],await Kc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=hv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function di(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)}):yv()}function yv(){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 Vc=J(()=>{"use strict"});import*as np from"path";function Fn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=np.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Co=J(()=>{"use strict"});import*as La from"fs/promises";async function as(){try{let t=await La.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 sp(t){await La.writeFile(_.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function Rn(t){try{return process.kill(t,0),!0}catch{return!1}}var ci=J(()=>{"use strict";he()});var cp={};Uf(cp,{_resetForTests:()=>Av,clearPin:()=>xv,fetchPeerFingerprint:()=>Xc,formatFingerprint:()=>Ba,getPin:()=>Qc,installGlobalTlsTrust:()=>el,loadPinsFromStore:()=>Gc,setPin:()=>Ao,sha256Hex:()=>Zc,wsTlsOptions:()=>Ro});import{createHash as wv}from"crypto";import*as rp from"tls";import{Agent as bv,Dispatcher as vv,buildConnector as Sv,getGlobalDispatcher as kv,setGlobalDispatcher as Iv}from"undici";function Ao(t,e,n){br.set(wr(t,e),ip(n))}function xv(t,e){br.delete(wr(t,e))}function Qc(t,e){return br.get(wr(t,e))}function Gc(t){br.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Ao(e.host,e.port,e.entry.pinnedFingerprint)}async function Xc(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=rp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,Zc(l.raw))}),o.once("error",l=>c(l))})}function Zc(t){return wv("sha256").update(t).digest("hex")}function Ba(t){let e=ip(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function ip(t){return t.replace(/:/g,"").toLowerCase()}function el(){if(Yc)return;Yc=!0;let t=kv(),e=new bv({connect:Sv({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>ap(s,r)})}),n=new vv;n.dispatch=(s,r)=>{let i=Cv(s.origin);return(i&&op(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(()=>{})),Iv(n)}function Cv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function op(t){for(let e of br.keys())if(dp(e)?.host===t)return!0;return!1}function ap(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=Zc(e.raw);for(let[s,r]of br.entries()){let i=dp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Ba(n)})`)}function dp(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 Ro(t){return op(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>ap(e,n)}:{autoSelectFamily:!0}}function Av(){br.clear(),Yc=!1}var br,Yc,To=J(()=>{"use strict";Jc();br=new Map,Yc=!1});import*as pp from"os";async function Ut(t){let e=await ko(),n=await as();if(n&&Rn(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:yr(r)}}function lp(t,e){let{httpScheme:n,wsScheme:s}=Wc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:mp(t),isLocal:t.isLoopback}}async function hp(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??di,r=e.confirmImpl??Pv,i=e.tlsHandshakeImpl??Rv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await oi();if(b)return Ev(t,b)}let c=e.store??await Oa.load();Gc(c),el();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Ao(t.host,t.port,d.pinnedFingerprint),lp(t,d.token);if(!a)throw new tl(t.host,t.port);let l=mp(t),{httpScheme:u}=Wc(t.host),f;if(u==="https"&&Qc(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
- subject: ${b.subject??"(unknown)"}
11
- issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${Ba(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Ao(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:fp()})});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:fp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),lp(t,y.session_token)}async function Rv(t,e){let n=await Tv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Xc(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Tv(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?up(p.subject):void 0,issuer:p?.issuer?up(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 up(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 Ev(t,e){let n=await as(),r=n&&Rn(n.pid)?n.loopbackPort:t.port,i=t.port===An?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 Pv(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 fp(){try{let t=pp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function mp(t){return t.port===An?t.host:`${t.host}:${t.port}`}var tl,vr=J(()=>{"use strict";Je();is();xo();Jc();Vc();Co();ci();To();xo();tl=class extends Error{host;port;constructor(e,n){let s=n===An?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Fn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});var z,qa=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 Me}from"zod";var Dp,sS,Hp,Up,jp,hl=J(()=>{"use strict";Dp=Me.object({protocolVersion:Me.number().optional(),clientCapabilities:Me.record(Me.unknown()).optional(),clientInfo:Me.object({name:Me.string(),version:Me.string().optional()}).optional()}),sS=Me.enum(["full","pending_only","none","after_message"]),Hp=Me.object({cwd:Me.string(),mcpServers:Me.array(Me.unknown()).optional(),_meta:Me.record(Me.unknown()).optional()}),Up=Me.object({upstreamSessionId:Me.string(),agentId:Me.string(),cwd:Me.string(),title:Me.string().optional(),agentArgs:Me.array(Me.string()).optional()}),jp=Me.object({sessionId:Me.string(),historyPolicy:sS.default("full"),afterMessageId:Me.string().optional(),clientId:Me.string().optional(),clientInfo:Me.object({name:Me.string(),version:Me.string().optional()}).optional(),_meta:Me.record(Me.unknown()).optional()})});import{z as ae}from"zod";function Wa(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 zp(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Eo(t._meta,Wa(t))};return t.title!==void 0&&(e.title=t.title),e}var qp,Wp,ml,bE,rS,vE,gl=J(()=>{"use strict";za();qp=ae.object({sessionId:ae.string()}),Wp=ae.object({cwd:ae.string().optional(),cursor:ae.string().optional()}),ml=ae.object({used:ae.number().optional(),size:ae.number().optional(),costAmount:ae.number().optional(),costCurrency:ae.string().optional()}),bE=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:ml.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(["live","cold"]).default("live"),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()}),rS=ae.object({sessionId:ae.string(),cwd:ae.string(),title:ae.string().optional(),updatedAt:ae.string().optional(),_meta:ae.record(ae.unknown()).optional()}),vE=ae.object({sessions:ae.array(rS),nextCursor:ae.string().optional()})});function iS(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 Gt(t){if(!t)return{};let e=t[Ct];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=Up.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=ml.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="live"||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=iS(n.env);r!==void 0&&(s.env=r)}return s}function Eo(t,e){return{...t??{},[Ct]:e}}var Ct,za=J(()=>{"use strict";hl();gl();Ct="hydra-acp"});import{z as ee}from"zod";var Kp,Ka,Jp,AE,RE,TE,Vp,EE,Yp,PE,Qp,ME,_E,Gp=J(()=>{"use strict";Kp=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),Ka=ee.object({sessionId:ee.string()}),Jp=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),AE=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:Jp,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),RE=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),TE=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),Vp=ee.object({sessionId:ee.string(),messageId:ee.string()}),EE=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),Yp=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),PE=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),Qp=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),ME=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),_E=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:Jp,amendedAt:ee.number()})});import{z as _s}from"zod";var Xp,Ja,hi,Zp=J(()=>{"use strict";Xp=_s.object({agentId:_s.string(),version:_s.string(),source:_s.enum(["binary","npm"]),phase:_s.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:_s.number().optional(),totalBytes:_s.number().optional(),packageSpec:_s.string().optional()}),Ja="hydra-acp/agents/install_progress",hi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var At=J(()=>{"use strict";qa();hl();za();gl();Gp();Zp()});import{nanoid as oS}from"nanoid";var yl,jt,kr=J(()=>{"use strict";At();yl=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},jt=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 yl;let s=oS(),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 mi(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 gi(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 wl=J(()=>{"use strict"});import*as nh from"fs/promises";function wS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var uS,fS,yi,pS,hS,mS,gS,yS,th,Qa,sh=J(()=>{"use strict";uS=64*1024*1024,fS=1*1024*1024,yi=64*1024,pS=6e4,hS=100,mS=1e3,gS=64*1024,yS=256*1024,th=20;Qa=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??uS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(fS,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,yi));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,yi)),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,yi)),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,pS));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(wS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??hS,mS)),f=Math.max(1,Math.min(e.maxBytes??gS,yS)),p=Math.max(0,Math.min(e.contextBefore??0,th)),h=Math.max(0,Math.min(e.contextAfter??0,th)),m=[],y=[],b=[],v=0,S=!1,x=0,T=0,$=(K,H)=>{for(let Q of b)Q.remaining>0&&(Q.match.after===void 0&&(Q.match.after=[]),Q.match.after.push({cursor:K,line:H}),Q.remaining--,v+=H.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(H)!==l&&m.length<u){let Q={cursor:K,line:H};if(p>0&&y.length>0){Q.before=y.slice();for(let be of Q.before)v+=be.line.length}v+=H.length,m.push(Q),h>0&&b.push({match:Q,remaining:h})}if(p>0)for(y.push({cursor:K,line:H});y.length>p;)y.shift();let D=m.length>=u&&b.length===0,X=v>=f;return D||X};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(()=>nh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Ga,tP,rh=J(()=>{"use strict";Ga=[{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."}],tP=new Map(Ga.map(t=>[t.verb,t]))});function ih(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function wi(t,e){return bl(t,e.map(n=>n.modelId))}function bl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=ih(t),s=e.filter(i=>ih(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 Xa=J(()=>{"use strict"});function oh(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=vl(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=vl(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?vS(r,i.outIndex,bS(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)?SS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!kS(f)&&(f=IS(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 vl(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function bS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function vS(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 SS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function kS(t){let n=vl(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function IS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var ah=J(()=>{"use strict"});function bi(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=kl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Il(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Sl(c))):d==="turn_complete"&&i()}return i(),TS(s.join(`
15
- `),n)}function Sl(t){let e=CS(t),n=AS(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function CS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function AS(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of xS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${RS(r,200)}`)}return n}function kl(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 Il(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function RS(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function TS(t,e){if(t.length<=e)return t;let n=t.split(`
16
- `);for(;n.length>0;){let s=dh+n.join(`
17
- `);if(s.length<=e)return s;n.shift()}return dh}var dh,xS,Za=J(()=>{"use strict";dh=`[older history truncated]
18
- `,xS=["file_path","filePath","path","command","pattern","query"]});function xl(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??ES}`),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=Po("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=Po("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=Po("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=Po("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=Po("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=ch(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=ch(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=PS(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(`
19
- `)}function Po(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(`
20
- `)}`}function ch(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 PS(t,e){if(t.length===0||e<=0)return"";let n=MS(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(`
21
- `)}function MS(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:kl(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=Il(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Sl(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var ES,lh=J(()=>{"use strict";Za();ES="(untitled)"});import*as Bn from"fs/promises";async function Mo(t,e){let n=_.queueFile(t);if(e.length===0){await Bn.unlink(n).catch(()=>{});return}await Bn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
2
+ var sv=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var qc=(t,e)=>{for(var n in e)sv(t,n,{get:e[n],enumerable:!0})};import*as ge from"path";import*as zc from"os";function Xe(t){let e=zc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function cv(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function Ce(){let t=process.env[dv];if(t&&t.length>0)return ge.resolve(t);let e=cv();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return ge.join(zc.homedir(),".hydra-acp")}var dv,_,he=J(()=>{"use strict";dv="HYDRA_ACP_HOME";_={home:Ce,config:()=>ge.join(Ce(),"config.json"),authToken:()=>ge.join(Ce(),"auth-token"),remotes:()=>ge.join(Ce(),"remotes.json"),pidFile:()=>ge.join(Ce(),"daemon.pid"),logFile:()=>ge.join(Ce(),"daemon.log"),currentLogFile:()=>ge.join(Ce(),"current.log"),registryCache:()=>ge.join(Ce(),"registry.json"),agentsDir:()=>ge.join(Ce(),"agents"),agentLogFile:t=>ge.join(Ce(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ge.join(Ce(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ge.join(Ce(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ge.join(Ce(),"sessions"),sessionDir:t=>ge.join(Ce(),"sessions",t),sessionFile:t=>ge.join(Ce(),"sessions",t,"meta.json"),historyFile:t=>ge.join(Ce(),"sessions",t,"history.jsonl"),toolsDir:t=>ge.join(Ce(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ge.join(Ce(),"sessions",t,"tools",e),queueFile:t=>ge.join(Ce(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ge.join(Ce(),"sessions",".tombstones"),tombstoneAgentDir:t=>ge.join(Ce(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ge.join(Ce(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ge.join(Ce(),"extensions"),extensionLogFile:t=>ge.join(Ce(),"extensions",`${t}.log`),extensionPidFile:t=>ge.join(Ce(),"extensions",`${t}.pid`),transformersDir:()=>ge.join(Ce(),"transformers"),transformerLogFile:t=>ge.join(Ce(),"transformers",`${t}.log`),transformerPidFile:t=>ge.join(Ce(),"transformers",`${t}.pid`),transformerState:(t,e)=>ge.join(Ce(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ge.join(Ce(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ge.join(Ce(),"prompt-history"),tuiLogFile:()=>ge.join(Ce(),"tui.log"),shimWireLogFile:()=>ge.join(Ce(),"shim-wire.log")}});import*as oi from"fs/promises";function ai(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function di(){try{let e=(await oi.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function gr(){let t=await di();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function ci(t){await oi.mkdir(_.home(),{recursive:!0}),await oi.writeFile(_.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function Io(){let t=await di();if(t)return t;let e=ai();return await ci(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
+ `),e}var ds=J(()=>{"use strict";he()});import*as xt from"fs/promises";import*as np from"fs";import*as An from"path";import{randomBytes as lv}from"crypto";async function Qt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await uv(t,r,n)}async function uv(t,e,n={}){let s=await fv(t),r=pv(s);await xt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${hv()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await xt.writeFile(i,e,o),await xt.rename(i,s)}catch(o){throw await xt.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{np.chmodSync(s,n.mode)}catch{}}async function fv(t){let e;try{e=await xt.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await xt.readlink(t),s=An.isAbsolute(n)?n:An.resolve(An.dirname(t),n);try{let r=await xt.realpath(An.dirname(s));return An.join(r,An.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function hn(t){let e;try{e=await xt.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function pv(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function hv(){return lv(4).toString("hex")}var yr=J(()=>{"use strict"});import*as _s from"fs/promises";import{homedir as Kc}from"os";import{z as q}from"zod";function ip(t){return t.tui.inAppSelection??t.tui.mouse}function op(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function ap(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function $a(){return await Iv(),await hn(_.config())??{}}async function Iv(){let t;try{t=await _s.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await _s.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await _s.readlink(_.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${_.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Fa(){let t=await $a(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await _s.access(_.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${_.authToken()} and ${_.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await ci(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Qt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
+ `)}async function we(){return await Fa(),Jc.parse(await $a())}async function cs(t){await Fa();let e=await $a();t(e),Jc.parse(e),await Qt(_.config(),e,{mode:384})}async function xo(t,e){await cs(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Oa(t){await cs(e=>{e.defaultAgent=t})}async function dp(t,e){await cs(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function cp(t,e){await cs(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function Yc(t,e){await cs(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function lp(t){await cs(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function up(){let t=await $a();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Ze(t){return t==="~"||t==="$HOME"?Kc():t.startsWith("~/")?Kc()+t.slice(1):t.startsWith("$HOME/")?Kc()+t.slice(5):t}var rp,mv,Rn,gv,yv,wv,bv,vv,sp,Sv,kv,Jc,Ye=J(()=>{"use strict";he();ds();yr();rp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",mv=q.object({cert:q.string(),key:q.string()}),Rn=55514,gv=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default(Rn),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:mv.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),yv=q.object({url:q.string().url().default(rp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),wv=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),bv=q.object({packageSpec:q.string().optional()}),vv=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),sp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Sv=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),kv=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Jc=q.object({daemon:gv.default({}),registry:yv.default({url:rp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),wv).default({}),agentOverrides:q.record(q.string(),bv).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(sp,Sv).default({}),transformers:q.record(sp,kv).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:vv.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function wr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function Vc(t){return{httpScheme:"https",wsScheme:"wss"}}function Qc(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${La(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${La(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=xv(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${La(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${La(t)}`);let i=wr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=Rn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function fp(t){let e=t.port!==void 0&&t.port!==Rn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function xv(t){try{return new URL(t)}catch{return null}}function La(t){return t.length>80?`${t.slice(0,77)}...`:t}var Co=J(()=>{"use strict";Ye()});function br(t,e){return`${t}:${e}`}function pp(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Cv(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Av(){let t=await hn(_.remotes());return t===void 0?{version:1,entries:{}}:Rv(t)}function Rv(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function Gc(t){await Qt(_.remotes(),t,{mode:384})}var Ba,Xc=J(()=>{"use strict";he();yr();Ba=class t{data;constructor(e){this.data=e}static async load(){let e=await Av(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(pp(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Gc(i),new t(i)}get(e,n){let s=this.data.entries[br(e,n)];if(s&&!pp(s,Date.now()))return s}async set(e,n,s){this.data.entries[br(e,n)]=s,await Gc(this.data)}async delete(e,n){let s=br(e,n);return s in this.data.entries?(delete this.data.entries[s],await Gc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Cv(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function li(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){if(l===10||l===13){process.stdout.write(`
7
+ `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):Tv()}function Tv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var Zc=J(()=>{"use strict"});import*as hp from"path";function Ln(){let t=process.argv[1];if(!t)return"hydra-acp";let e=hp.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Ao=J(()=>{"use strict"});import*as Na from"fs/promises";async function ls(){try{let t=await Na.readFile(_.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function mp(t){await Na.writeFile(_.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function Tn(t){try{return process.kill(t,0),!0}catch{return!1}}var ui=J(()=>{"use strict";he()});var Sp={};qc(Sp,{_resetForTests:()=>Bv,clearPin:()=>Ov,fetchPeerFingerprint:()=>sl,formatFingerprint:()=>Da,getPin:()=>tl,installGlobalTlsTrust:()=>il,loadPinsFromStore:()=>nl,setPin:()=>Ro,sha256Hex:()=>rl,wsTlsOptions:()=>To});import{createHash as Ev}from"crypto";import*as gp from"tls";import{Agent as Pv,Dispatcher as Mv,buildConnector as _v,getGlobalDispatcher as $v,setGlobalDispatcher as Fv}from"undici";function Ro(t,e,n){vr.set(br(t,e),yp(n))}function Ov(t,e){vr.delete(br(t,e))}function tl(t,e){return vr.get(br(t,e))}function nl(t){vr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Ro(e.host,e.port,e.entry.pinnedFingerprint)}async function sl(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=gp.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,rl(l.raw))}),o.once("error",l=>c(l))})}function rl(t){return Ev("sha256").update(t).digest("hex")}function Da(t){let e=yp(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function yp(t){return t.replace(/:/g,"").toLowerCase()}function il(){if(el)return;el=!0;let t=$v(),e=new Pv({connect:_v({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>bp(s,r)})}),n=new Mv;n.dispatch=(s,r)=>{let i=Lv(s.origin);return(i&&wp(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),Fv(n)}function Lv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function wp(t){for(let e of vr.keys())if(vp(e)?.host===t)return!0;return!1}function bp(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=rl(e.raw);for(let[s,r]of vr.entries()){let i=vp(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Da(n)})`)}function vp(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}function To(t){return wp(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>bp(e,n)}:{autoSelectFamily:!0}}function Bv(){vr.clear(),el=!1}var vr,el,Eo=J(()=>{"use strict";Xc();vr=new Map,el=!1});import*as Cp from"os";async function jt(t){let e=await Io(),n=await ls();if(n&&Tn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:wr(r)}}function kp(t,e){let{httpScheme:n,wsScheme:s}=Vc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Rp(t),isLocal:t.isLoopback}}async function Ap(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??li,r=e.confirmImpl??Uv,i=e.tlsHandshakeImpl??Nv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let v=await di();if(v)return Hv(t,v)}let c=e.store??await Ba.load();nl(c),il();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Ro(t.host,t.port,d.pinnedFingerprint),kp(t,d.token);if(!a)throw new ol(t.host,t.port);let l=Rp(t),{httpScheme:u}=Vc(t.host),f;if(u==="https"&&tl(t.host,t.port)===void 0){let v=await i(t.host,t.port);if(v.kind==="untrusted"){let b=v.subject||v.issuer?`
10
+ subject: ${v.subject??"(unknown)"}
11
+ issuer: ${v.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
+ sha256: ${Da(v.fingerprint)}${b}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Ro(t.host,t.port,v.fingerprint),f=v.fingerprint}else if(v.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${v.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${t.host}:${t.port}`,m=await n(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:xp()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:xp(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),kp(t,y.session_token)}async function Nv(t,e){let n=await Dv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await sl(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Dv(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?Ip(p.subject):void 0,issuer:p?.issuer?Ip(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function Ip(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function Hv(t,e){let n=await ls(),r=n&&Tn(n.pid)?n.loopbackPort:t.port,i=t.port===Rn?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function Uv(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function xp(){try{let t=Cp.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Rp(t){return t.port===Rn?t.host:`${t.host}:${t.port}`}var ol,Sr=J(()=>{"use strict";Ye();ds();Co();Xc();Zc();Ao();ui();Eo();Co();ol=class extends Error{host;port;constructor(e,n){let s=n===Rn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Ln()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});import{appendFileSync as jv,renameSync as qv,statSync as Wv}from"fs";function Pp(t){Ep=t}function st(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{zv(n);let s=JSON.stringify({t:new Date().toISOString(),...t});jv(n,`${s}
15
+ `)}catch{}}function zv(t){try{if(Wv(t).size<Ep)return;qv(t,`${t}.0`)}catch{}}var Ep,dl=J(()=>{"use strict";he();Ep=5*1024*1024});var z,za=J(()=>{"use strict";z={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as _e}from"zod";var Zp,wS,eh,th,nh,vl=J(()=>{"use strict";Zp=_e.object({protocolVersion:_e.number().optional(),clientCapabilities:_e.record(_e.unknown()).optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional()}),wS=_e.enum(["full","pending_only","none","after_message"]),eh=_e.object({cwd:_e.string(),mcpServers:_e.array(_e.unknown()).optional(),_meta:_e.record(_e.unknown()).optional()}),th=_e.object({upstreamSessionId:_e.string(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),agentArgs:_e.array(_e.string()).optional()}),nh=_e.object({sessionId:_e.string(),historyPolicy:wS.default("full"),afterMessageId:_e.string().optional(),clientId:_e.string().optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional(),_meta:_e.record(_e.unknown()).optional()})});import{z as ae}from"zod";function Ka(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),t.compactionState!==void 0&&(n.compactionState=t.compactionState),t.forkSynthesisState!==void 0&&(n.forkSynthesisState=t.forkSynthesisState),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue),e.resurrected===!0&&(n.resurrected=!0)),n}function ih(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Po(t._meta,Ka(t))};return t.title!==void 0&&(e.title=t.title),e}var sh,rh,Sl,LE,bS,BE,kl=J(()=>{"use strict";Ja();sh=ae.object({sessionId:ae.string()}),rh=ae.object({cwd:ae.string().optional(),cursor:ae.string().optional()}),Sl=ae.object({used:ae.number().optional(),size:ae.number().optional(),costAmount:ae.number().optional(),costCurrency:ae.string().optional()}),LE=ae.object({sessionId:ae.string(),upstreamSessionId:ae.string().optional(),cwd:ae.string(),title:ae.string().optional(),agentId:ae.string().optional(),currentModel:ae.string().optional(),currentUsage:Sl.optional(),importedFromMachine:ae.string().optional(),importedFromUpstreamSessionId:ae.string().optional(),parentSessionId:ae.string().optional(),forkedFromSessionId:ae.string().optional(),forkedFromMessageId:ae.string().optional(),originatingClient:ae.object({name:ae.string(),version:ae.string().optional()}).optional(),interactive:ae.boolean().optional(),priority:ae.number().int().nonnegative().optional(),updatedAt:ae.string(),attachedClients:ae.number().int().nonnegative(),status:ae.enum(["warm","cold"]).default("warm"),busy:ae.boolean().default(!1),awaitingInput:ae.boolean().default(!1),compactionState:ae.any().optional(),forkSynthesisState:ae.enum(["running","failed"]).optional(),_meta:ae.record(ae.unknown()).optional()}),bS=ae.object({sessionId:ae.string(),cwd:ae.string(),title:ae.string().optional(),updatedAt:ae.string().optional(),_meta:ae.record(ae.unknown()).optional()}),BE=ae.object({sessions:ae.array(bS),nextCursor:ae.string().optional()})});function vS(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function Xt(t){if(!t)return{};let e=t[At];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=th.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Sl.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="warm"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.resurrected=="boolean"&&(s.resurrected=n.resurrected),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=vS(n.env);r!==void 0&&(s.env=r)}return s}function Po(t,e){return{...t??{},[At]:e}}var At,Ja=J(()=>{"use strict";vl();kl();At="hydra-acp"});import{z as ee}from"zod";var oh,Ya,ah,qE,WE,zE,dh,KE,ch,JE,lh,YE,VE,uh=J(()=>{"use strict";oh=ee.object({sessionId:ee.string(),prompt:ee.array(ee.unknown()),_meta:ee.record(ee.unknown()).optional()}),Ya=ee.object({sessionId:ee.string()}),ah=ee.object({clientId:ee.string(),name:ee.string().optional(),version:ee.string().optional()}),qE=ee.object({sessionId:ee.string(),messageId:ee.string(),originator:ah,prompt:ee.array(ee.unknown()),position:ee.number().int().nonnegative(),queueDepth:ee.number().int().positive(),enqueuedAt:ee.number()}),WE=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),zE=ee.object({sessionId:ee.string(),messageId:ee.string(),reason:ee.enum(["started","cancelled","abandoned"])}),dh=ee.object({sessionId:ee.string(),messageId:ee.string()}),KE=ee.object({cancelled:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),ch=ee.object({sessionId:ee.string(),messageId:ee.string(),prompt:ee.array(ee.unknown())}),JE=ee.object({updated:ee.boolean(),reason:ee.enum(["ok","not_found","already_running"])}),lh=ee.object({sessionId:ee.string(),targetMessageId:ee.string(),prompt:ee.array(ee.unknown()),replaceQueue:ee.boolean().optional(),onTargetCompleted:ee.enum(["reject","send_anyway"]).optional()}),YE=ee.object({amended:ee.boolean(),reason:ee.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:ee.string().optional()}),VE=ee.object({sessionId:ee.string(),cancelledMessageId:ee.string(),newMessageId:ee.string(),prompt:ee.array(ee.unknown()),originator:ah,amendedAt:ee.number()})});import{z as Fs}from"zod";var fh,Va,gi,ph=J(()=>{"use strict";fh=Fs.object({agentId:Fs.string(),version:Fs.string(),source:Fs.enum(["binary","npm"]),phase:Fs.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Fs.number().optional(),totalBytes:Fs.number().optional(),packageSpec:Fs.string().optional()}),Va="hydra-acp/agents/install_progress",gi={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Rt=J(()=>{"use strict";za();vl();Ja();kl();uh();ph()});import{nanoid as SS}from"nanoid";var Il,qt,Ir=J(()=>{"use strict";Rt();Il=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},qt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new Il;let s=SS(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:i}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:z.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??z.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0:this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});async function yi(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(c=>c.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function wi(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var xl=J(()=>{"use strict"});import*as gh from"fs/promises";function $S(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var AS,RS,bi,TS,ES,PS,MS,_S,mh,Xa,yh=J(()=>{"use strict";AS=64*1024*1024,RS=1*1024*1024,bi=64*1024,TS=6e4,ES=100,PS=1e3,MS=64*1024,_S=256*1024,mh=20;Xa=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??AS,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(RS,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,n){let s=Math.max(0,Math.min(n,bi));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,bi)),s=this.oldestAvailable,r=this.writeCursor-n,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let n=Math.max(0,Math.min(e,bi)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,TS));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp($S(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??ES,PS)),f=Math.max(1,Math.min(e.maxBytes??MS,_S)),p=Math.max(0,Math.min(e.contextBefore??0,mh)),h=Math.max(0,Math.min(e.contextAfter??0,mh)),m=[],y=[],v=[],b=0,S=!1,x=0,T=0,$=(K,H)=>{for(let G of v)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:K,line:H}),G.remaining--,b+=H.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(d.test(H)!==l&&m.length<u){let G={cursor:K,line:H};if(p>0&&y.length>0){G.before=y.slice();for(let be of G.before)b+=be.line.length}b+=H.length,m.push(G),h>0&&v.push({match:G,remaining:h})}if(p>0)for(y.push({cursor:K,line:H});y.length>p;)y.shift();let D=m.length>=u&&v.length===0,Z=b>=f;return D||Z};for(let K=0;K<o.length;K++){if(o[K]!==10)continue;let H=o.subarray(x,K).toString("utf8"),L=r+x;if(x=K+1,T=x,$(L,H)){S=!0;break}}if(!S&&x<o.length&&this.closed){let K=o.subarray(x).toString("utf8"),H=r+x;$(H,K)&&(S=!0),T=o.length}let F=Math.min(r+T,this.writeCursor),j={matches:m,truncated:S,nextCursor:F,scannedBytes:T};return i>0&&(j.gap=i),this.closed&&F>=this.writeCursor&&(j.eof=!0),j}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>gh.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Za,wP,wh=J(()=>{"use strict";Za=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],wP=new Map(Za.map(t=>[t.verb,t]))});function bh(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function vi(t,e){return Cl(t,e.map(n=>n.modelId))}function Cl(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=bh(t),s=e.filter(i=>bh(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var ed=J(()=>{"use strict"});function vh(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Al(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=n.get(l);u?u.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=Al(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?OS(r,i.outIndex,FS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?LS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!BS(f)&&(f=NS(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function Al(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function FS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function OS(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function LS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function BS(t){let n=Al(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function NS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Sh=J(()=>{"use strict"});function Si(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=Tl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=El(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Rl(c))):d==="turn_complete"&&i()}return i(),qS(s.join(`
16
+ `),n)}function Rl(t){let e=HS(t),n=US(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function HS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function US(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of DS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${jS(r,200)}`)}return n}function Tl(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function El(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function jS(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function qS(t,e){if(t.length<=e)return t;let n=t.split(`
17
+ `);for(;n.length>0;){let s=kh+n.join(`
18
+ `);if(s.length<=e)return s;n.shift()}return kh}var kh,DS,td=J(()=>{"use strict";kh=`[older history truncated]
19
+ `,DS=["file_path","filePath","path","command","pattern","query"]});function Pl(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??WS}`),t.synopsis.goal!==void 0&&t.synopsis.goal.trim().length>0&&e.push(`[Goal] ${t.synopsis.goal}`),t.synopsis.outcome!==void 0&&t.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${t.synopsis.outcome}`);let n=Mo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=Mo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=Mo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=Mo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=Mo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Ih(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Ih(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=zS(t.tail,t.tailK);return e.push("--- begin recent turns (verbatim, last "+t.tailK+") ---"),d.length>0&&e.push(d),e.push("--- end recent turns ---"),e.push(""),e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"),e.join(`
20
+ `)}function Mo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
21
+ `)}`}function Ih(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function zS(t,e){if(t.length===0||e<=0)return"";let n=KS(t);if(n.length===0)return"";let s=n.slice(-e),r=[];for(let i of s)if(i.user.length>0&&r.push("User: "+i.user),i.agent.length>0&&r.push("Assistant: "+i.agent),i.tools.length>0)for(let o of i.tools)r.push(o);return r.join(`
22
+ `)}function KS(t){let e=[],n=null;for(let s of t){if(s.method!=="session/update")continue;let i=s.params?.update;if(!i||typeof i.sessionUpdate!="string")continue;let o=i.sessionUpdate;if(o==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:Tl(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=El(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Rl(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var WS,xh=J(()=>{"use strict";td();WS="(untitled)"});import*as Dn from"fs/promises";async function _o(t,e){let n=_.queueFile(t);if(e.length===0){await Dn.unlink(n).catch(()=>{});return}await Dn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
22
23
  `)+`
23
- `;await Bn.writeFile(n,s,"utf8")}async function uh(t){let e=_.queueFile(t),n;try{n=await Bn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
24
- `))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 fh(t){let e=_.queueFile(t);await Bn.unlink(e).catch(()=>{})}var Cl=J(()=>{"use strict";he()});import{customAlphabet as yh}from"nanoid";import*as vh from"fs/promises";function Ir(){return`m_${bh()}`}function nt(t){return t.startsWith(mn)?t.slice(mn.length):t}function qt(t,e){return t.code=e,t}function mh(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&OS.has(s)}function LS(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 BS(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 NS(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 Si(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 DS(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 HS(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 US(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 jS(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:Ir()}}}function Tl(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 qS(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 WS(t){let e=zS(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=KS(t.resolver),n}function zS(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 KS(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 vi(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Rl(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function gh(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 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}
25
26
  ${s.join(`
26
- `)}`}function El(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 wh,bh,ph,_S,hh,mn,$S,Al,FS,ki,OS,Nn=J(()=>{"use strict";wl();sh();rh();Xa();ah();lh();Cl();At();wh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bh=yh(wh,16),ph=yh(wh,16),_S=20,hh=20,mn="hydra_session_";$S=1e3,Al=300*1e3,FS=64,ki=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??`${mn}${bh()}`,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??$S,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){HS(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_${ph()}`,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 b=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()))},Al);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:()=>y(),timer:b,transformerName:d.name,method:"session/update",envelope:h,chainIdx:p,originatedBy:m,side:"response"})});return}n.add(d.name)}let o=US(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=DS(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 gi({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedModel:a,agentReportedModel:u.initialModel,logger:this.logger}),await mi({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(v){this.logger?.warn(`swapUpstream: historyStore.load failed: ${v.message}`)}let p=xl({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 v=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${p.length} toolCalls=${v.toolCalls} thinkingChars=${v.thinkingChars} messageChars=${v.messageChars} used=${v.lastUsed??"?"} size=${v.lastSize??"?"} reply=${JSON.stringify(v.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 v of this.agentChangeHandlers)try{v({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(v){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${v.message}`)}await y.kill().catch(()=>{}),this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0});let b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
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
28
  Compaction completed.
28
- `},_meta:{"hydra-acp":{synthetic:!0}}}});for(let v of this.clients.values())v.connection.notify("session/update",b).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 gi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await mi({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=_S){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 qt(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw qt(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:oh(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!mh(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Tl(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 qt(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw qt(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=Ir();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Gt((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=vi(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:Ir()};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>FS;){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 qt(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=Ir(),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=Ir(),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 qt(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_${ph()}`,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??Rl(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:Rl(e))))},Al);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}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):Al,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:Rl(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=vi((e??{}).prompt),r=El(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=Si(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=Si(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=Si(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(LS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(BS(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(",")}]`),NS(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(Ga.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=Ga.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 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
30
  ${e}
30
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}):
31
32
  ${s.join(`
@@ -38,7 +39,7 @@ ${s}
38
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(`
39
40
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
40
41
  ${a}
41
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=wi(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=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
43
  ${d}.
43
44
  ${l}:
44
45
  ${c.join(`
@@ -46,9 +47,9 @@ ${l}:
46
47
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(d=>d.id===i):!0,c=r.map(d=>{let l=d.id===i?"\u25B6 ":" ",u=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${u}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
47
48
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
48
49
  ${o}
49
- `},_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 qt(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:`
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:`
50
51
  _(no config options advertised yet)_
51
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>gh(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=>Ph(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
52
53
  ${u.join(`
53
54
 
54
55
  `)}
@@ -58,16 +59,16 @@ ${u.join(`
58
59
  Available options:
59
60
  ${l}
60
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:`
61
- ${gh(o)}
62
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=bl(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
+ ${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:`
63
64
  ${p}.
64
65
  ${h}:
65
66
  ${f.join(`
66
67
  `)}
67
- `},_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 qt(new Error("/hydra agent requires an agent id"),z.InvalidParams);if(e===this.agentId)throw qt(new Error(`already on agent ${e}`),z.InvalidParams);if(!this.spawnReplacementAgent)throw qt(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 qt(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(`
68
- `)),{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 qt(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=vi(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(`
69
- `)}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(-hh),i=xl({synopsis:e,title:n,tail:r,tailK:hh});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 Qa(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??yi,yi)),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(()=>fh(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(()=>vh.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=!mh(e,r),o=i?jS(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 qt(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=qS(s),i=Ir(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===z.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(x=>{f--,m(()=>{let T=WS({toolCallId:r,result:x,resolver:v});for(let $ of u)$.client.clientId!==v.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??qt(new Error("no client handled permission request"),z.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Ir(),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(()=>Mo(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=vi(e.prompt).replace(/\s+$/,""),s=!n.includes(`
70
- `)&&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)}};OS=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 Ii}from"zod";var JS,Sh,kh=J(()=>{"use strict";JS=Ii.object({source:Ii.string(),reason:Ii.string(),raisedAt:Ii.number(),payload:Ii.unknown()}),Sh=Ii.array(JS)});import{z as _e}from"zod";function Ch(t){let e=t.trim();if(e.length===0)return;let n=xi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=xi(e.slice(i,o+1)))}if(n===void 0){let i=Rh(e);i!==void 0&&(n=xi(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,xh))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=$o.safeParse(s.synopsis);i.success&&VS(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Ah(t){let e=t.trim();if(e.length===0)return;let n=xi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=xi(e.slice(d,l+1)))}if(n===void 0){let d=Rh(e);d!==void 0&&(n=xi(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,xh))}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 xi(t){try{return JSON.parse(t)}catch{return}}function Rh(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 VS(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 Ih,$o,xh,Pl,Ml,ed=J(()=>{"use strict";Ih=_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()}),$o=_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()}),xh=200,Pl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
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:
71
72
  {
72
73
  "title": "short summary, max 80 chars",
73
74
  "synopsis": {
@@ -77,7 +78,7 @@ ${h}:
77
78
  "open_threads": ["work started but not finished"]
78
79
  }
79
80
  }
80
- Use empty arrays/strings where a field doesn't apply.`;Ml=`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.`;Bl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
81
82
  {
82
83
  "title": "short summary, max 80 chars",
83
84
  "goal": "the user's original ask",
@@ -89,251 +90,293 @@ Use empty arrays/strings where a field doesn't apply.`;Ml=`Reply with ONLY a JSO
89
90
  "unresolved_errors": ["errors left open at session end"],
90
91
  "tool_state": ["runtime state relevant for recall"]
91
92
  }
92
- Use empty arrays/strings where a field doesn't apply.`});import*as Ci from"fs/promises";import*as xP from"path";import{customAlphabet as YS}from"nanoid";import{z as ne}from"zod";function Fo(){return`${XS}${GS()}`}function nk(t){if(!_l.test(t))throw new Error(`unsafe session id: ${t}`)}function Bl(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 QS,GS,XS,$l,Fl,ZS,Ol,Ll,ek,tk,_l,td,Nl=J(()=>{"use strict";he();gr();kh();ed();QS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",GS=YS(QS,16),XS="hydra_lineage_";$l=ne.object({name:ne.string(),description:ne.string().optional()}),Fl=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),ZS=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Ol=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Ll=ne.object({name:ne.string(),version:ne.string().optional()}),ek=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),tk=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:$o.optional(),compactionState:Ih.optional(),rollbackBreadcrumb:ek.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Ol.optional(),agentCommands:ne.array($l).optional(),agentModes:ne.array(Fl).optional(),agentModels:ne.array(ZS).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Ll.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:Sh.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),_l=/^[A-Za-z0-9_-]+$/;td=class{async write(e){nk(e.sessionId);let n={version:1,...e};await Yt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!_l.test(e))return;let n=await pn(_.sessionFile(e));if(n!==void 0)try{return tk.parse(n)}catch{return}}async delete(e){if(_l.test(e)){try{await Ci.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Ci.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 Ci.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 rk}from"url";import*as Oo from"path";import*as sd from"fs";function ik(){try{let t=Oo.dirname(rk(import.meta.url));for(let e=0;e<8;e+=1){let n=Oo.join(t,"package.json");if(sd.existsSync(n)){let r=JSON.parse(sd.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=Oo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var pe,xr,Xt=J(()=>{"use strict";pe=ik(),xr="hydra-acp-cat"});function Dl(t){let e=new Map;for(let n of Bh(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 Fh(t){return Dl(t).map(e=>e.name)}function Hl(t){let e=new Map;for(let n of Bh(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 Oh(t){return Hl(t).map(e=>e.path)}function Lh(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Bh(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:_h(i),paths:new Set},e.set(c,d)):d.toolName=_h(i);for(let l of $h(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 $h(i.rawInput,i.locations))a.paths.add(c)}return e}function _h(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function $h(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 Ul=J(()=>{"use strict"});import{promises as Bo}from"fs";import*as Jl from"path";async function No(t){let e;try{e=await Bo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return mk(e)}function mk(t){let e=[];for(let n of t.split(`
93
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Do(t,e,n=Vh){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 Cr(t,e){await Bo.mkdir(Jl.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await Bo.writeFile(t,n.length>0?n.join(`
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(`
94
95
  `)+`
95
- `:"")}async function Yh(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await Bo.mkdir(Jl.dirname(t),{recursive:!0}),await Bo.appendFile(t,JSON.stringify(n)+`
96
- `,{encoding:"utf8"}))}function ad(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function Vl(t,e,n=Vh){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=Do(r,o,n)))}return r}var Vh,dd=J(()=>{"use strict";Vh=500});import{z as Re}from"zod";function Ho(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 Tn(t){return wk.parse(t)}var gk,yk,wk,Ar=J(()=>{"use strict";Nl();ed();gk=Re.object({method:Re.string(),params:Re.unknown(),recordedAt:Re.number()}),yk=Re.object({sessionId:Re.string(),lineageId:Re.string(),upstreamSessionId:Re.string().optional(),agentId:Re.string(),cwd:Re.string(),title:Re.string().optional(),synopsis:$o.optional(),summarizedThroughEntry:Re.number().int().nonnegative().optional(),currentModel:Re.string().optional(),currentMode:Re.string().optional(),currentUsage:Ol.optional(),agentCommands:Re.array($l).optional(),agentModes:Re.array(Fl).optional(),interactive:Re.boolean().optional(),originatingClient:Ll.optional(),priority:Re.number().int().nonnegative().optional(),createdAt:Re.string(),updatedAt:Re.string()}),wk=Re.object({version:Re.literal(1),exportedAt:Re.string(),exportedFrom:Re.object({hydraVersion:Re.string(),machine:Re.string(),hydraHost:Re.string().optional()}),session:yk,history:Re.array(gk),promptHistory:Re.array(Re.string()).optional(),toolBlobs:Re.record(Re.string()).optional()})});import{createHash as _k}from"crypto";function ru(t){if(Array.isArray(t))return t.map(ru);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=ru(t[n]);return e}return t}function Ls(t){let{tui:e,...n}=t,s=JSON.stringify(ru(n));return _k("sha256").update(s).digest("hex").slice(0,16)}var Jo=J(()=>{"use strict";Je()});function iu(t){return Math.floor(t/4)}function hm(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=iu(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 ou=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 gm=J(()=>{"use strict"});import{posix as Wk}from"path";import zk from"strip-ansi";function at(t){return zk(t).replace(Kk,"")}function Ae(t){return at(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Un(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 Xk(n);case"agent_thought_chunk":case"agent_thought":return Zk(n);case"user_message_chunk":return eI(n);case"prompt_received":return tI(n);case"tool_call":return nI(n,e);case"tool_call_update":return aI(n,e);case"plan":return lI(n);case"current_mode_update":return uI(n);case"current_model_update":return fI(n);case"turn_complete":return pI(n);case"usage_update":return Gk(n);case"available_commands_update":return Yk(n);case"available_modes_update":return Qk(n);case"session_info_update":return Vk(n);case"config_option_update":return Jk(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function Jk(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 Vk(t){let e=Ze(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 xd(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 Yk(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:xd(e)}:null}function Qk(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 Gk(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 Xk(t){let e=Yo(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Vo(t)}}function Zk(t){let e=typeof t.text=="string"?at(t.text):Yo(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Vo(t)}}function eI(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=Yo(t.content);return n===null?null:{kind:"user-text",text:n}}function tI(t){let e=hI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function bm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function ym(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 Cd(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=ym(r.oldText),o=ym(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 vm(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:at(n)}function nI(t,e={}){let n=Ze(t,"toolCallId")??Ze(t,"id");if(!n)return null;let s=Ze(t,"title")??Ze(t,"name")??Ze(t,"label")??"tool call",r=Ze(t,"name")??Ze(t,"title");if(bm(r)){let h=vm(t);if(h!==null){let m=Ze(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:h};return m!==void 0&&(y.status=m),y}}let i=Im(Ae(s),t,e),o=Ze(t,"status"),a=Ze(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Cd(t);d!==null&&(c.editDiff=d);let l=km(t);l!==void 0&&(c.detail=l);let u=au(t);u!==void 0&&(c.detailFull=u);let f=Sm(t);f!==void 0&&(c.locations=f);let p=Vo(t);return p!==void 0&&(c.workerTaskId=p),c}function Sm(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 km(t){let e=au(t);if(e===void 0)return;let n=Ae(e),s=t.rawInput;return s&&typeof s.command=="string"?iI(n,wm):oI(n,wm)}function au(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 at(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 Ge(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 Ge(Ae(s))}}}function rI(t){for(let e of sI)if(t.startsWith(e))return!0;return!1}function Im(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ge(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 Ge(o)}return rI(t)?Ge(`/${t}`):n.cwd&&n.cwd.length>0?Ge(Wk.resolve(n.cwd,t)):t}function iI(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function oI(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function aI(t,e={}){let n=Ze(t,"toolCallId")??Ze(t,"id");if(!n)return null;let s=Ze(t,"title"),r=s!==void 0?Im(Ae(s),t,e):void 0,i=Ze(t,"status"),o=Cd(t),a=km(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=Ze(t,"name")??s;if(bm(d)){let h={kind:"exit-plan-mode",toolCallId:n},m=vm(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=au(t);u!==void 0&&(l.detailFull=u);let f=Sm(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=dI(t);h!==null&&(l.errorText=h),cI(t,h)&&(l.upstreamInterrupted=!0)}let p=Vo(t);return p!==void 0&&(l.workerTaskId=p),l}function dI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Yo(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 at(s)}return null}function cI(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 lI(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 uI(t){let e=Ze(t,"currentModeId")??Ze(t,"currentMode")??Ze(t,"mode");return e?{kind:"mode-changed",mode:Ae(e)}:null}function fI(t){let e=Ze(t,"currentModel")??Ze(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 pI(t){let e=Ze(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 Yo(t){if(typeof t=="string")return at(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?at(e.text):null}function hI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Yo(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Ze(t,e){let n=t[e];return typeof n=="string"?n:void 0}var Kk,wm,sI,Bs=J(()=>{"use strict";he();gm();Kk=/[\x00-\x08\x0b-\x1f\x7f]/g;wm=64;sI=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Ei(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=gI(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)mI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Pi(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 mI(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 gI(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=Cd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Ad=J(()=>{"use strict";Bs()});function jn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),t.on("close",()=>r()),t.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var $i=J(()=>{"use strict";At()});import{spawn as Ox}from"child_process";import{setTimeout as Lx}from"timers/promises";async function dg(){let t=await as();if(t&&Rn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function Bx(t){let e=await Er(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===Ls(t)?"match":"mismatch":"missing"}async function Hs(t){let e=await Bx(t);if(e!=="match"){if(e==="mismatch"){let n=Fn();throw new Error(`unable to attach to running daemon \u2014 run \`${n} daemon stop\` and try again.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
97
- `),Nd(),await Dd(t)}}async function Bd(t){let e=await dg();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Er(t,e=1e3){let n=await dg();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 Nd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Ox(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Dd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await Bd(t))return;await Lx(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Pr=J(()=>{"use strict";Co();Jo();ci()});import{WebSocket as jx}from"ws";async function Mr(t,e,n=qx){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=Ro(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 jx(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 bu(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 qx,bu,Xo=J(()=>{"use strict";To();qx=1e4,bu=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 Ud from"fs/promises";function Wx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Di(){let t=await as();if(t&&Rn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await we();return gg(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function gg(t,e,n){return`${n?"https":"http"}://${Wx(t)}:${e}`}async function $e(t,e={}){let n=await mr(),s=await Di(),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}
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(`
101
+ `).slice(-n-1);process.stdout.write(d.join(`
102
+ `)),o.endsWith(`
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}
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}
98
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}
99
- `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function Hi(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 jd(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
100
- `),process.exit(2)),s=n?zx(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 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
101
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
102
111
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
103
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}
104
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function zx(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Ui(){let t=await Ud.readFile(_.config(),"utf8");return JSON.parse(t)}async function vu(t){await Ud.writeFile(_.config(),JSON.stringify(t,null,2)+`
105
- `,{encoding:"utf8",mode:384})}var Us=J(()=>{"use strict";Je();is();he();ci();Xo()});async function tn(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 Su(t,n):c}finally{clearTimeout(a)}}async function qn(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 tn(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??"live",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 yg(t,e=fetch){let n=await tn(`${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 tn(`${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 qd(t,e=fetch){let n=await tn(`${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 Wd(t,e,n={},s=fetch){let r=await tn(`${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 Wn(t,e,n=fetch){let s=await tn(`${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 wg(t,e,n,s=fetch){let r=await tn(`${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 bg(t,e,n,s=fetch){let r=await tn(`${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 vg(t,e,n=fetch){let s=await tn(`${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 Sg(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await tn(`${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 kg(t,e,n=fetch){let s=await tn(`${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 zd(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="live"?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 Su,Zo=J(()=>{"use strict";Su=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 ku(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function Ig(t,e){let n=t??"?",s=ku(e);return s?`${n}${Kx}${s}`:n}function xg(t){return t??"?"}function Cg(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Iu(e,n)}function Iu(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var Kx,xu=J(()=>{"use strict";Kx="\u2022"});function Ag(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(!Jd.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Jd.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Wi(t,e=Date.now()){return{session:nt(t.sessionId),upstream:Yx(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:Qx(t.status,t.busy,t.awaitingInput,Vx(t.compactionState),t.forkSynthesisState),agent:xg(t.agentId),model:ku(t.currentModel)??"-",age:Gx(t.updatedAt,e),title:t.title??"-",cwd:Ge(t.cwd),cost:Cg(t.currentUsage)}}function Vx(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 Yx(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function Qx(t,e,n,s,r){return t==="cold"?"COLD":n?r==="failed"?"LIVE\u25E6\u26A0":"LIVE\u25E6":e?r==="failed"?"LIVE\u2022\u26A0":"LIVE\u2022":r==="running"?"LIVE\u2728":r==="failed"?"LIVE\u26A0":s?"LIVE\u27F3":"LIVE"}function zi(t,e={}){let n=e.columns??ji,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]=Xx(qi[r],t.map(i=>i[r]));return s}function Gx(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 Xx(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function js(t,e,n,s={}){let r=s.columns??ji,i=s.cwdMaxWidth??Jx,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(Kd);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Cu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(Kd);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Cu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*Kd.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],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=(v,S,x)=>{if(v==="cwd")return ea(t[v],S).padEnd(S);let T=Zx(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>Cu.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(Kd);return b.length>n?b.slice(0,n):b}function Zx(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function ea(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 Jd,ji,Cu,qi,Kd,Jx,Vd=J(()=>{"use strict";xu();he();Nn();Jd=["session","upstream","host","state","agent","model","age","cwd","title","cost"],ji=["session","state","age","cwd","title","agent","cost"],Cu=new Set(["cwd","title"]),qi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Kd=" ",Jx=32});import{spawn as cC}from"child_process";import{Writable as lC}from"stream";function Yd(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=uC(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??cC,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}
106
- `)});let c=new lC({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}
107
- `)});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 uC(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 Au=J(()=>{"use strict"});import fC from"chalk";import{highlight as pC,supportsLanguage as Qd}from"cli-highlight";import Xd from"string-width";function qs(t,e={}){switch(t.kind){case"user-text":{let n=Ru(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 Ru(t.text," ","agent");case"agent-thought":return Ru(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return OC(t,e.maxPlanItems??$C);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 Tu(t,e){return Ki(t,e).styled}function Ki(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=Ki(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=t.slice(u+1,p);a+=`${n}${h}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=t.slice(u+1,p),y=t.slice(p+2,h),b=Ki(m,e),v=c,S=y.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let x of b.links)l.push({start:v+x.start,end:v+x.end,url:x.url});c+=b.cleanLength,S&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function hC(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 Ng(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 Dg(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
108
- `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",x,T)=>{let $={prefix:S,body:b,bodyStyle:v};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 b=Ug(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.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,X=s?Ng(D):o;h(Tu(L,X),D,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&mC(T)&&ta(v).length===ta(T).length){let H=ta(v),L=[],D=b+2;for(;D<d.length&&d[D].includes("|");)L.push(ta(d[D])),D++;let X=kC(H,L,a);for(let Q of X)r!==void 0&&(Q.prefixStyle=r),c.push(Q);b=D-1;continue}let $=v.match(/^(\s*)[-*+]\s+(.*)$/);if($){let H=$[1]??"",L=$[2]??"",D=Ki(L,o),X=H.length+2,Q=D.links.map(be=>({start:be.start+X,end:be.end+X,url:be.url}));h(`${H}\u2022 ${D.styled}`,n,m(),Q,D.ansi);continue}let F=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if(F){let H=F[1]??"",L=F[2]??"",D=F[3]??"",X=Ki(D,o),Q=H.length+L.length+2,be=X.links.map(G=>({start:G.start+Q,end:G.end+Q,url:G.url}));h(`${H}${L}. ${X.styled}`,n,m(),be,X.ansi);continue}let j=v.trim()==="",K=Ki(v,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 Ws(t,e){return Dg(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Ji(t){return Dg(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function ta(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 mC(t){if(!t.includes("|"))return!1;let e=ta(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Gd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Xd(e)}function wC(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:Xd(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:Gd(r)}),n=i}return e}function bC(t,e){let n=[],s="",r=0;for(let i of t){let o=Xd(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 vC(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=bC(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=Xd(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 SC(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,Hg)),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 kC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Gd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Gd(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*Hg,n-gC-(s-1)*yC);i=SC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=vC(wC(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],x=Gd(v),T=Tu(v,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",Ng("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 Ug(t,e){if(t.length===0||!Qd(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=pC(e.join(`
109
- `),{language:t,theme:IC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
110
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function CC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Qd("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Qd("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=xC[s];return r&&Qd(r)?r:""}function Ru(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
111
- `),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 AC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function zn(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 jg(t){if(t.length<=4096&&t.split(`
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(`
112
121
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
113
122
  `);return i.length>40&&(s=i.slice(0,40).join(`
114
- `),r=!0),{text:s,truncated:r}}function na(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 ${zn(l-t.startedAt)}`}let c={prefix:` ${PC(t.status)} `,prefixStyle:MC(t.status),body:o,bodyStyle:LC(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 qg(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
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(`
115
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(`
116
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=CC(r);if(i.length>0){let o=Ug(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 zg(t){Wg=t>=0?t:0}function Eu(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=` (~${AC(d)})`}else{let d=TC(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(Ge(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=Pu(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(...Ws(c)),s.length>0&&s.unshift({body:""}),s}function Kg(t){let e=at(t.oldText).split(`
117
- `),n=at(t.newText).split(`
118
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function TC(t){let{oldLines:e,newLines:n}=Kg(t),s=0,r=0;for(let i of Jg(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Bg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Pu(t,e={}){let n=e.maxLines??RC,s=e.contextLines??Wg,{oldLines:r,newLines:i}=Kg(t),o=Jg(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(Bg(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(Bg(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(`
119
- `)}function Jg(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(...EC(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 EC(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 Mu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function PC(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 MC(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 Vg(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ws(t.plan));let n=t.status;if(n!==void 0){let s=_C(n);s!==null&&e.push(s)}return e}function _C(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 FC(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 OC(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}=FC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Tu(v,hC(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function LC(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 Hg,gC,yC,et,IC,xC,RC,Wg,$C,Vi=J(()=>{"use strict";he();Bs();Hg=6,gC=2,yC=3;et=new fC.Instance({level:3}),IC={keyword:et.blueBright,built_in:et.cyan,type:et.cyanBright,literal:et.blue,number:et.greenBright,string:et.yellow,regexp:et.red,comment:et.gray,function:et.yellow,title:et.yellow,class:et.yellowBright,attr:et.cyan,attribute:et.cyan,variable:et.white,params:et.white,meta:et.magenta,symbol:et.magenta,addition:et.greenBright,deletion:et.redBright,section:et.cyan,tag:et.cyan,name:et.cyanBright};xC={".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"};RC=40,Wg=Number.POSITIVE_INFINITY;$C=5});import{highlight as BC,supportsLanguage as NC}from"cli-highlight";async function Qg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
120
- `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await $e(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await $e(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=Tn(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
121
- `),process.exit(1)}let u=Ei(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:Pi(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
125
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=HC(r);if(i.length>0){let o=sy(i,s.map(a=>Ae(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Ae(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function ay(t){oy=t>=0?t:0}function Ou(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${UC(d)})`}else{let d=qC(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Ae(Xe(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=Lu(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...Ks(c)),s.length>0&&s.unshift({body:""}),s}function dy(t){let e=ct(t.oldText).split(`
126
+ `),n=ct(t.newText).split(`
127
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function qC(t){let{oldLines:e,newLines:n}=dy(t),s=0,r=0;for(let i of cy(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Zg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Lu(t,e={}){let n=e.maxLines??jC,s=e.contextLines??oy,{oldLines:r,newLines:i}=dy(t),o=cy(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(Zg(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(Zg(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
128
+ `)}function cy(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...WC(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function WC(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Bu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function zC(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function KC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function ly(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ks(t.plan));let n=t.status;if(n!==void 0){let s=JC(n);s!==null&&e.push(s)}return e}function JC(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function VC(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function QC(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:c,end:d}=VC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of t.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=t.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",v=m==="completed"?"plan-done":m==="in_progress"?n?"plan-pending":"plan":"plan-pending",b=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Fu(b,EC(v));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:v})}return f}function GC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var ny,MC,_C,tt,NC,DC,jC,oy,YC,Qi=J(()=>{"use strict";he();Ds();ny=6,MC=2,_C=3;tt=new RC.Instance({level:3}),NC={keyword:tt.blueBright,built_in:tt.cyan,type:tt.cyanBright,literal:tt.blue,number:tt.greenBright,string:tt.yellow,regexp:tt.red,comment:tt.gray,function:tt.yellow,title:tt.yellow,class:tt.yellowBright,attr:tt.cyan,attribute:tt.cyan,variable:tt.white,params:tt.white,meta:tt.magenta,symbol:tt.magenta,addition:tt.greenBright,deletion:tt.redBright,section:tt.cyan,tag:tt.cyan,name:tt.cyanBright};DC={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};jC=40,oy=Number.POSITIVE_INFINITY;YC=5});import{highlight as XC,supportsLanguage as ZC}from"cli-highlight";async function fy(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
129
+ `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Me(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Me(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=En(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
130
+ `),process.exit(1)}let u=Mi(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:_i(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
122
131
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
123
- `);return}let i=Yd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(_u(r,a)),await i.flush()}function _u(t,e){if(t.length===0)return`No file edits found in this session.
124
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=UC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
125
- `:n.join("")}function DC(t){let e=[];for(let n of t.hunks){let s=Pu(n,{maxLines:1/0});HC(s)&&e.push({body:s,oldCount:Yg(n.oldText),newCount:Yg(n.newText)})}return e}function HC(t){if(t.length===0)return!1;for(let e of t.split(`
126
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function UC(t,e){let n=DC(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=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(`
127
136
  `)+`
128
137
 
129
- `;return!e||!NC("diff")?i:BC(i,{language:"diff"})}function Yg(t){if(t.length===0)return 0;let e=t.split(`
130
- `);return e[e.length-1]===""&&e.pop(),e.length}var $u=J(()=>{"use strict";Us();Ar();Ad();Vi();Au()});async function Gg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
131
- `),process.exit(2));let n=await $e(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await $e(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=Tn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
132
- `),process.exit(1)}let a=Lu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=Ei(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:Pi(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
133
- `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=Yd({disabled:e.noPager===!0});f.stream.write(Zd(a,e.verbose===!0)),f.stream.write(`
134
- `),f.stream.write(_u(d??[],u)),await f.flush();return}process.stdout.write(Zd(a,e.verbose===!0))}function Lu(t,e){let n=t.session,s=t.history,r=Lh(s),i=Dl(s),o=Hl(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 Zd(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:")}${qC(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,Fu),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>Fu&&n.push(` ... ${t.tools.length-Fu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>jC.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,Ou),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>Ou&&n.push(` ... ${o.length-Ou} more (use --verbose to see all)`)}return n.join(`
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(`
135
144
  `)+`
136
- `}function qC(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 Fu,Ou,jC,Bu=J(()=>{"use strict";Us();Ar();Ul();Ad();Au();$u();Fu=10,Ou=15,jC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var nc,ls,Qi,sa,xy,ra,ju,sc,Fr,Cy,Or,Ay,Lr,Ry,Br,Gi,Xi,Ty,Zi,Ey,Py,My,qu,_y,rc,ic,ia,$y,Fy,oa=J(()=>{"use strict";nc="\x1B[?2004h",ls="\x1B[?2004l",Qi="\x1B[200~",sa="\x1B[201~",xy="\x1B[?1049l",ra="\x1B[?7h",ju="\x1B[?7l",sc="\x1B[?25h",Fr="\x1B[?1l",Cy="\x1B[>1u",Or="\x1B[<u",Ay="\x1B[>4;2m",Lr="\x1B[>4;0m",Ry="\x1B[>5;1m",Br="\x1B[>5;0m",Gi="\x1B[?1000l",Xi="\x1B[?1002l",Ty="\x1B[?1003l",Zi="\x1B[?1006l",Ey="\x1B[?1015l",Py="\x1B[?w",My="\x1B[=24;1w",qu="\x1B[=0;0w",_y="\x1B]22;pointer\x07",rc="\x1B]22;default\x07",ic="\x1B[?1004h",ia="\x1B[?1004l",$y="\x1B[?2026h",Fy="\x1B[?2026l"});function us(){process.stdout.write(Or),process.stdout.write(ls),process.stdout.write(Lr),process.stdout.write(Br),process.stdout.write(Gi),process.stdout.write(Xi),process.stdout.write(Zi),process.stdout.write(Fr),process.stdout.write("\x1B>")}function En(t){return t.width??80}function Nr(t){return t.height??24}function fs(t,e){let n=En(t),s=Nr(t),r=e.contentWidth??zC,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=Oy.repeat(a-2),p=QC(f,e.title);t.moveTo(l,u),t.dim.noFormat(KC),GC(t,p),t.dim.noFormat(JC);for(let h=1;h<=c;h++)t.moveTo(l,u+h),t.dim.noFormat(Ly),t.moveTo(l+a-1,u+h),t.dim.noFormat(Ly);return t.moveTo(l,u+d-1),t.dim.noFormat(VC+Oy.repeat(a-2)+YC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function QC(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 GC(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 dt(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function oc(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function zs(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 zC,Oy,Ly,KC,JC,VC,YC,to=J(()=>{"use strict";oa();zC=64,Oy="\u2500",Ly="\u2502",KC="\u250C",JC="\u2510",VC="\u2514",YC="\u2518"});function By(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 eA(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??XC,footer:ZC};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}] ${By(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 tA(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 nA(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function Ny(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[Ct];if(!(typeof s!="object"||s===null))return s}function sA(t){let e=Ny(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function rA(t){let e=Ny(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 Dy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!nA(e))throw e;let n=sA(e)??t.fallbackAgentId??"",s=rA(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 iA(t,e,n){t.grabInput(!1),us(),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+`
145
+ `}function rA(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var Hu,Uu,sA,qu=J(()=>{"use strict";qs();Rr();Jl();Td();_u();Du();Hu=10,Uu=15,sA=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var _y={};qc(_y,{assertKnownAgent:()=>rc,resolveAgentIdOrExit:()=>Ku,runAgentsAdd:()=>Xu,runAgentsInstall:()=>Ju,runAgentsList:()=>zu,runAgentsLogs:()=>Vu,runAgentsPin:()=>Gu,runAgentsRefresh:()=>ic,runAgentsRemove:()=>Zu,runAgentsSet:()=>Qu,runAgentsSync:()=>Yu,runRegistryPin:()=>oc});async function zu(){let e=(await Me("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
146
+ `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:fs(s.id,n.map(a=>a.id)),name:fs(s.name,n.map(a=>a.name)),version:fs(s.version,n.map(a=>a.version)),source:fs(s.source,n.map(a=>a.source)),distributions:fs(s.distributions,n.map(a=>a.distributions)),installed:fs(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
147
+ `);for(let a of n)process.stdout.write(i(a)+`
148
+ `);let o=e.fetchedAt!==void 0?` (synced ${ji(e.fetchedAt)})`:"";process.stdout.write(`
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(", ")}).
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"}
156
+ `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
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)+`
161
+ `);for(let c of r)process.stdout.write(a(c)+`
162
+ `);process.stdout.write(`
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(", ")}).
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}.
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]...
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+`
137
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(`
138
183
  failed to spawn ${e.command}: ${c.message}
139
184
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
140
185
  failed to spawn ${e.command}: ${a.message}
141
- `),i({exitCode:-1})}})}function oA(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 Wu(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(oA(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 Hy(t,e,n,s,r){us();let i=eA(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=fs(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(dt(` ${a}`,p)),h++),c&&(t.moveTo(f.contentX,f.contentY+h),t.brightRed.noFormat(dt(` ${c}`,p)),h++),t.moveTo(f.contentX,f.contentY+h),t.brightWhite.bold.noFormat(dt(` ${i.title}`,p)),h+=2,t.moveTo(f.contentX,f.contentY+h),t.noFormat(dt(` ${i.description}`,p)),h++,i.command&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(dt(i.command,p-7)),h++),i.url&&(t.moveTo(f.contentX,f.contentY+h),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(dt(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(dt(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 zs({term:t,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=tA(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 ${By(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>iA(t,v));(async()=>{let v=await Wu(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var XC,ZC,zu=J(()=>{"use strict";qa();za();to();XC="This agent requires authentication before use.",ZC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as zy}from"timers/promises";function mA(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var uA,fA,pA,hA,no,Ku=J(()=>{"use strict";Xo();$i();uA=200,fA=5e3,pA=2,hA=60,no=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=uA;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Mr(s,this.opts.subprotocols);this.bindStream(jn(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=hA)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*pA,fA)}}bindStream(e){this.current=e,e.onMessage(n=>{if(mA(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}
142
- `)}}});function Ky(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 Dr(t){return{outcome:{outcome:"selected",optionId:Ky(t,["allow_once","allow_always"])}}}function Jy(t){return{outcome:{outcome:"selected",optionId:Ky(t,["reject_once","reject_always"])}}}function cc(t){return t&&typeof t=="object"?t:void 0}function aa(t){return typeof t=="string"&&t.length>0?t:void 0}function Vy(t){let e=cc(t),n=cc(e?.toolCall),s={paths:[]};if(!n)return s;let r=aa(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=aa(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(cc(d)?.path);let c=cc(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=aa(c.command);d&&(s.command=d);let l=aa(c.url);l&&(s.url=l);let u=aa(c.description);u&&(s.description=u)}return s}function Yy(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 lc=J(()=>{"use strict"});function hR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function hw(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 mR(t,e){let n=hw(t),s=hw(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 da(){if(Js!==void 0)return Js;if(hR())return Js=null,Js;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:mw,version:pe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&mR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Js={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{}Js=null}}catch{Js=null}return Js}function ca(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${mw}`}var mw,Js,Yu=J(()=>{"use strict";Xt();mw="@hydra-acp/cli"});import*as la from"fs/promises";import*as Qu from"path";async function ua(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Qu.resolve(Xe(e)),s;try{s=await la.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 gw(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 la.stat(r)).isDirectory())return r}catch{}return null}async function yw(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=Qu.resolve(Xe(r)),o;try{o=(await la.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 Gu=J(()=>{"use strict";Je()});var ww,bw,vw,Sw=J(()=>{"use strict";ww="hydra-acp/question/list",bw="hydra-acp/question/answer",vw="hydra-acp/question/dismiss"});import{EventEmitter as gR}from"events";import{WebSocket as yR}from"ws";function wR(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=Ro(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 yR(t,e,n),o=()=>{i.off("error",a),s(jn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function kw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??wR,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new jt(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 Wd(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 Xu(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(()=>{}),Wn(t,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[Ct]:{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 Xu,Iw=J(()=>{"use strict";To();Zo();kr();$i();At();Xu=class extends gR{_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(()=>{}),Wn(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 Zu,mc,xw=J(()=>{"use strict";Vi();Bs();Zu=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())}},mc=class extends Zu{_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=Un(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=Ji(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Ji(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=na(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=na(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=qs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Ws(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 vR(t,e){return`[pasted #${t} +${e} lines]`}var bR,gc,ef,SR,ps,tf=J(()=>{"use strict";bR=/\[pasted #(\d+) \+\d+ lines\]/g,gc=/\[pasted #(\d+) \+\d+ lines\]$/,ef=/^\[pasted #(\d+) \+\d+ lines\]/;SR=500,ps=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>SR&&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(`
143
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(vR(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(`
144
- `)}expandPastes(e){return e.replace(bR,(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 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(`
145
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(`
146
- `);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(gc);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(ef);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(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=`
147
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+`
148
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=`
149
194
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
150
- `+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(gc);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(gc);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(ef);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(gc);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(ef);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(`
151
- `),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 io,yc,nf=J(()=>{"use strict";io=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())}},yc=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import kR from"path";function fa(t){return Cw[kR.extname(t).toLowerCase()]??null}function IR(t){return fa(t)!==null}function sf(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(!xR.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 CR(t){return sf(t)!==null}function wn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Aw(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(!CR(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!IR(o))return null;n.push(o)}return n.length>0?n:null}var Kn,Cw,xR,wc=J(()=>{"use strict";Kn=10*1024*1024,Cw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};xR=new Set(Object.values(Cw))});import AR from"string-width";function Rw(t,e){if(!t||e<=0)return 0;let n=0;for(let s of RR.segment(t)){let r=AR(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Tw(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 RR,Ew=J(()=>{"use strict";RR=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as TR}from"child_process";import rf from"fs/promises";import ER from"os";import PR from"path";async function _w(t={}){let e={...of,...t};return e.platform==="darwin"?FR(e):e.platform==="linux"?OR(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function $w(t={}){let e={...of,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await oo(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await oo(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 pa(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:af(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Fw(t,e={}){let{target:n="both",...s}=e,r={...of,...s},i=await MR(r,t,n);if(i.ok)return i;let o=_R(r,t,n);return o.ok||o.reason!==Ow?o:i}async function MR(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await bc(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 oo(t,"wl-copy")?Mw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await oo(t,"xclip")?Mw(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 Mw(t,e,n,s,r,i,o){let a=n;if(i){try{await bc(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await bc(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await bc(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function _R(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Pw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Pw} 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??$R)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Ow}}function $R(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 FR(t){let e=PR.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 Lw(t.spawn,"osascript",s);let r=await HR(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await rf.unlink(e).catch(()=>{})}try{let r=await pa(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:af(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function OR(t){let e=await LR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await DR(t,e),s=NR(n);if(s)try{let r=await pa(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Kn?{ok:!1,reason:`clipboard image is ${wn(r.length)}, max ${wn(Kn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await pa(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:af(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function LR(t){return t.env.WAYLAND_DISPLAY&&await oo(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await oo(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function NR(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of BR)if(e.has(n))return n;return null}async function DR(t,e){try{return(await pa(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
152
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function af(t){return t.replace(/\r\n?/g,`
153
- `)}async function oo(t,e){try{return await Lw(t.spawn,"which",[e]),!0}catch{return!1}}async function HR(t,e){try{let n=await rf.readFile(t);return e&&await rf.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Kn?{ok:!1,reason:`clipboard image is ${wn(n.length)}, max ${wn(Kn)}`}:{ok:!0,kind:"image",attachment:{mimeType:fa(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Lw(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 bc(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 pa(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 of,Pw,Ow,BR,df=J(()=>{"use strict";wc();of={platform:process.platform,env:process.env,spawn:TR,tmpdir:ER.tmpdir};Pw=74994;Ow="no TTY available for OSC 52 clipboard write";BR=["image/png","image/jpeg","image/gif","image/webp"]});function UR(){ha===0&&process.stdout.write($y),ha++}function jR(){ha!==0&&(ha--,ha===0&&process.stdout.write(Fy))}function Oe(t){UR();try{t()}finally{jR()}}var ha,cf=J(()=>{"use strict";oa();ha=0});import{spawn as qR}from"child_process";import{statSync as WR}from"fs";import{homedir as Bw}from"os";import{isAbsolute as Nw,resolve as zR}from"path";import We from"string-width";import KR from"wrap-ansi";function t0(t){let e=t.replace(/\r\n?$|\n$/,"");return e0.test(e)?e:null}function n0(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function Dw(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 ms(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 Ys(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 Hw(t,e,n,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){hs(t,e,n,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){hs(t,e.slice(c),n,o);return}d>c&&hs(t,e.slice(c,d),n,o);let l=r!==null&&d===r;hs(t,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function ma(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function hs(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":t(e.replace(/\^K/g,"^:"));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 s0(t,e){return e<=0?[t]:t.length===0?[""]:KR(t,e,{hard:!0,trim:!1}).split(`
154
- `)}function Yw(t){Vw=t}function Qw(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 We(t,{ambiguousIsNarrow:!Vw})}function ao(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 r0.test(n)?{text:t.slice(e,e+2),width:0}:null}function Uw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=ao(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 jw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=ao(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function i0(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=ao(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function Gw(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(ao(t,e))return!0;return!1}function*vf(t){let e=0;for(;e<t.length;){let n=ao(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(ao(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 bf.segment(t.slice(e,s)))yield{text:i,width:Vs(i)};e=s}}function o0(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 a0(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&Gw(t);return!s&&!Jw.test(t)?d0(t,e):c0(t,e,s)}function d0(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 c0(t,e,n){let s=[],r=n?[...vf(t)]:l0(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 l0(t){let e=[];for(let{segment:n}of bf.segment(t))e.push({text:n,width:Vs(n)});return e}function wt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&Gw(t);if(!s&&t.length<=e&&!Jw.test(t))return t;if(!s)return Vs(t)<=e?t:e<=1?qw(t,e):qw(t,e-1)+"\u2026";let r=[...vf(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?Ww(r,e):Ww(r,e-1)+"\u2026"}function qw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of bf.segment(t)){let i=Vs(r);if(s+i>e)break;n+=r,s+=i}return n}function Ww(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function u0(t){let e=t.indexOf(`
155
- `);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(`${Sc(t.used)}/${Sc(t.size)}`):e.push(Sc(t.used)):typeof t.size=="number"&&e.push(`/${Sc(t.size)}`),typeof t.costAmount=="number"&&e.push(Iu(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Sc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function xc(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 kc(){let t=[Gi,Xi,Ty,Zi,Ey,qu,ls,Lr,Br,Or,Fr,"\x1B>",ra,sc,rc,"\x1B]9;4;0\x07",xy].join("");try{process.stdout.write(t)}catch{}}function Xw(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 Kw(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 lf,vc,uf,ff,JR,He,Ve,VR,Ye,pf,hf,YR,QR,GR,mf,gf,yf,XR,ZR,e0,Ic,Jw,bf,Vw,r0,wf,Sf=J(()=>{"use strict";nf();xu();he();Nn();wc();Vi();Ew();df();cf();oa();lf=500,vc=1,uf=/[A-Za-z0-9_]/,ff=/[A-Za-z0-9_./\-~+@]/,JR=/\x1b\[[0-9;]*[A-Za-z]/g,He=1,Ve=0,VR=1,Ye=1,pf=8,hf=5,YR=12,QR=12,GR=30,mf=6,gf=4,yf=2,XR=1e3,ZR=1e4,e0=/^(https?|ftp):\/\/\S+$/;Ic=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??XR,this.painter=new io(this.term),this.scheduler=new yc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??ZR,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(ju),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(rc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(ra),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(kc(),this.term.fullscreen(!1),this.term(`
156
- `)))}installBracketedPaste(){process.stdout.write(nc),process.stdout.write(Ay),process.stdout.write(Ry),process.stdout.write(Cy),process.stdout.write(ic);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(ls),process.stdout.write(Lr),process.stdout.write(Br),process.stdout.write(Or),process.stdout.write(ia),process.stdout.write(Fr),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(Py),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(qu),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>kc(),this.onProcessSignal=e=>{kc(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{kc(),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(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(`
157
202
  uncaught: ${e.stack??e.message}
158
- `),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(My),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(Qi)){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(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(`
159
204
  `)){let s=n.split(`
160
- `);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=Kw(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=Kw(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=Qi,s=sa;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,`
161
- `);this.pasteBuffer="";let a=Aw(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=t0(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(`
162
- `),[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=wf(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(JR,""):(c=a.slice(o.start,o.end),ma(r.bodyStyle)&&(c=jw(c))),n.push(c)}return n.join(`
163
- `)}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(ju),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=xc(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=n0(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)<=vc&&Math.abs(o.y-d.y)<=vc&&Date.now()-d.t<=lf||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<=lf&&Math.abs(e.x-r.x)<=vc&&Math.abs(e.y-r.y)<=vc){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}=Uw(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),!uf.test(r[a]))return null;let c=a;for(;c>0&&uf.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&uf.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}=Uw(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let h=p.url;return{raw:h.startsWith("file://")?h.slice(7):h,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!ff.test(r[a]))return null;let c=a;for(;c>0&&ff.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&ff.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Bw():`${Bw()}/${n.slice(2)}`);let s=Nw(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=Nw(n)?n:zR(this.sessionbar.cwd,n);if(s)return i;try{if(WR(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=qR(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)},lf);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&&Fw(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"?_y:rc))}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 b=ma(p.bodyStyle)?Tw(vf(p.body),y):Rw(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+b}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-He-Ye-Ve-VR-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-Ye-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=this.term.width,n=this.term.height,s=this.sessionbar.title?.trim(),r=Ig(this.sessionbar.agent,this.sessionbar.model),i=Ge(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(n,o,()=>{let a=We(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=We(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=wt(i,f),m=s?wt(s,p):"",y=We(h)+(s?u+We(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let n=this.term.width,s=wf(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?zn(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+We(o)+We(u)+f.length+We(s);for(let T of c)y+=We(" \xB7 ")+We(T.text);y+=We(p);let b=We(h)+We(d)+We(m),v=Math.max(0,n-y-b),S="\u2500".repeat(v),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=We(i)+We(a)+We(o),d=Math.max(0,n-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s?"":this.hoveredBannerHit??"",p=`bsep|${n}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.hoveredBannerHit;for(let b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b],S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+We(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=We(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+We(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?wf(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=zw(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+We(n)+i.length+We(r)+o.length+We(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:n,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let f=Math.max(0,r.length-s);this.scrollOffset>f&&(this.scrollOffset=f)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let f=0;f<s;f++){let p=n+f,h=f-d,m=h>=0?c[h]:void 0,y=this.activeMatchCol(m,l),b=m?this.selectionRangeForChunk(m):null,S=m!==void 0&&m.blockKey!==void 0&&(m.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m.blockKey))&&(this.hoveredSubKey===null||(m.hoverSubKey??null)===this.hoveredSubKey),x=Dw("sb",e,m,this.scrollbackHighlight,y,b)+(S?"|H":"");this.paintRow(p,x,()=>{m&&this.writeFormattedLine(m,e,y,u,b,S)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let f=new Set;for(let h of c)h.blockKey!==void 0&&f.add(h.blockKey);let p=[];for(let h of this.pendingVisibleKeys)f.has(h)&&p.push(h);for(let h of p)this.pendingVisibleKeys.delete(h),this.onBlockVisible(h)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(hf,this.queuedTexts.length)}chipRows(){return Math.min(gf,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(mf,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-Ye-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>mf,h=this.completions.length-mf+1,m=f?p?`comp|${n}|overflow|${h}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?wt(b,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-He-Ye-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>gf,u=this.attachments.length-gf,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${wn(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(o0(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-Ye-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>hf,p=this.queuedTexts.length-hf,h=u===void 0?"":f?`+ ${p+1} more queued`:wt(u0(u),n-4),m=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,n-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=ms(s.buffer,n),i=Ys(r,s,pf),o=this.term.height-i.rendered-Ve-Ye-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-yf-Ve-Ye-He+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${wt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${wt(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-Ye-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(` ${wt(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}. ${wt(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-Ye-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 ${wt(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(` ${wt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${wt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(GR,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-Ye-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} ${wt(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(` ${wt(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}. ${wt(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-Ye-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-Ye-He+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ve-Ye-He;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Ve-Ye-He+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ve-Ye-He;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-yf-Ve-Ye-He+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Ve-Ye-He+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Ve-Ye-He;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Ve-Ye-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=ms(s.buffer,n),i=Ys(r,s,pf),a=this.term.height-i.rendered-Ve-Ye-He+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Ve-Ye-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 yf;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=ms(s.buffer,n);return Math.min(pf,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(YR,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(QR,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-Ye-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 ${wt(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}${wt(`${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-Ye-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=Dw(`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),a=ma(e.bodyStyle),c=e.ansi?s0(e.body,o):a0(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&&hs(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,n-Vs(e.prefix??"")),c=ma(e.bodyStyle),d=e.ansi?e.body:wt(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;Hw(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else hs(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=ma(e.bodyStyle);if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=jw(m)),hs(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=i0(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Hw(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):hs(this.term,d,e.bodyStyle,o);if(e.fillRow){let u=e.ansi?We(d):Vs(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;hs(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)}};Jw=/[^\x20-\x7e]/,bf=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Vw=!1;r0=/[a-zA-Z+\-:_!#/]/;wf=nt});function f0(t,e,n=Cc){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 Zw(t,e){us();let n=nt(e.sessionId),s=e.importedFromMachine??"another machine",r=Ge(e.cwd),i=Cc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Cc.length*2+2,d=fs(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(dt(p.value,l-p.label.length-2)),f++;return f++,eb(t,d,f,{intro:"What do you want to do?",choices:Cc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return zs({term:t,render:o,onKey:(a,c,d,l)=>{let u=p0(a,d);if(!u)return;let f=f0(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 eb(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(oc(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 p0(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 tb(t,e,n){let s=nt(e.sessionId),r=e.title??Ge(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=fs(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(dt(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+dt(r,d-2)),l++,l++,eb(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 Cc,kf=J(()=>{"use strict";he();Nn();to();Cc=[{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 ya(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 nb(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=ya(e);return o.length<=r.length?null:o+i}var Ac=J(()=>{"use strict"});import*as sb from"os";async function jr(t,e,n={}){let s=n.defaultCwd??(e?await gw(e.cwd):void 0)??sb.homedir();us();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:nt(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ge(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=fs(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(dt(F.value,T-F.label.length-2)),$++;$++,t.moveTo(l.contentX,l.contentY+$),t.noFormat(` ${i}`),$+=2,v($),$+=2,c!==null?(t.moveTo(l.contentX,l.contentY+$),t.red.noFormat(` ${dt(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+$),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=x=>{if(!l)return;let T=x??b();t.moveTo(l.contentX,l.contentY+T).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+T),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+T),t.bold.noFormat(" cwd: ");let $=l.contentW-6-2;t.noFormat(h0(a,$)),d||t.bgWhite(" ")},S=()=>{if(v(),!l)return;let x=b()+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(` ${dt(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return zs({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(),ua(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,yw(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=ya(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 h0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var If=J(()=>{"use strict";he();Nn();Gu();Ac();to()});function Cf(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Af(t,e){let n=()=>{process.stdout.write(Or),process.stdout.write(ls),process.stdout.write(Lr),process.stdout.write(Br),process.stdout.write(Gi),process.stdout.write(Xi),process.stdout.write(Zi),process.stdout.write(Fr),process.stdout.write("\x1B>")};n();let s=e.prefs??Cf();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=Tc(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=b0(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??ji,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Wi(R,Date.now())),l=zi(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",x=null,T=!1,$="input",F=new ps({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,D=null,X=!1,Q="",be=[],G=[],de=()=>{be.push(Q),be.length>500&&be.shift(),G=[]},ze=()=>{let R=be.pop();R!==void 0&&(G.push(Q),Q=R)},Gs=()=>{let R=G.pop();R!==void 0&&(be.push(Q),Q=R)},gs=()=>{be=[],G=[]},Le=null,V=!1,Se=new ps({history:[]});e.initialPrompt&&Se.setBuffer(e.initialPrompt);let Jn=e.config.tui.promptHistoryMaxEntries;No(_.globalTuiHistoryFile()).then(R=>{let P=R.length>Jn?R.slice(R.length-Jn):R;Se.setHistory(P)}).catch(()=>{});let ye=new io(t),ys=Nr(t),st=En(t),Be=0,co="",ws=0,Tt=[],sn=1,bs=0,Xs=0,lo=0,Wr="",Te=[],Pn=1,wa=0,Zs=[],bt=1,Mn=0,uo=0,zr=0,fo=()=>{ys=Nr(t),st=En(t);let R=Math.max(10,st-xf-1);ws=Math.max(10,st-rb);let P=Math.max(10,st-8);co=w0(r,P);let N=Se.state();Tt=ms(N.buffer,ws);let Y=Ys(Tt,N,Rc);sn=Y.rendered,bs=Y.windowStart,Xs=Y.cursorVisualRow,lo=Y.cursorVisualCol;let oe=6+sn,fe=Math.max(3,ys-oe);Be=Math.min(a.length,fe),Wr=js(qi,l,R,c).padEnd(R),Te=d.map(Fe=>js(Fe,l,R,c).padEnd(R))},ke=()=>{d=a.map(R=>Wi(R,Date.now())),l=zi(d,c),u=1+a.length,fo()},tt=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>v0(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)),rn()},ct=R=>{if(R!==void 0){let P=a.findIndex(N=>N.sessionId===R);if(P>=0){f=P+1,rn();return}}f=a.length>0?1:0,p=0,rn()},rn=()=>{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))},on=()=>Math.max(2,st-3),mt=!1,gt=!0,lt=!1,Kr=[],Jr=()=>{let R=on(),P=`\u2500 ${co} `,N=Math.max(1,R-P.length),Y="\u2500".repeat(N);(f===0||mt)&&gt?t.brightBlue.noFormat(`\u256D${P}${Y}\u256E`):t.dim.noFormat(`\u256D${P}${Y}\u256E`)},vs=()=>{let R=on(),P="\u2500".repeat(R);(f===0||mt)&&gt?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},Vr=R=>{let P=Tt[R];return P?(Se.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},bn=R=>{let P=on(),N=Vr(R),Y=Math.max(0,P-1-N.length),oe=" ".repeat(Y);(f===0||mt)&&gt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${N}${oe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${N}${oe}`),t.dim.noFormat("\u2502"))},er=R=>{let P=Te[R]??"",N=a[R],Y=N&&N.priority&&N.priority>0?"* ":" ";f===R+1&&!mt&&gt?t.brightWhite.bgBlue.noFormat(`${Y}${P}`):t.noFormat(`${Y}${P}`)},Ss=()=>{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 Y=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;N.push({kind:"host",text:Y})}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},po=()=>{let R=Ss();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},vt=R=>nt(R),an=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,Q,Le??"",h?`1|${m}|${a.length}`:"0",po(),Cs?"h1":"h0",dr?"ho1":"ho0"].join("")},me=()=>{Oe(()=>{ye.paintRow(dn(),an(),()=>{let R=()=>{Jt=null,vn=null};if(S==="confirm-kill"&&x)R(),t.brightYellow.noFormat(` kill ${vt(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="live"?t.brightRed.noFormat(` kill + delete ${vt(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${vt(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),t.dim.noFormat(` working on ${vt(x.sessionId)}\u2026`);else if(S==="rename"&&x)R(),t.brightYellow.noFormat(` title: ${Q}`),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=Ss(),N=po(),Y="Esc \xB7 Go Back",oe=Y.length,fe=5,Fe=N.length,Nt=Math.max(1,st-Fe-oe-fe);if(vn=null,P.length>0){t.dim.noFormat(" ");let Pt=3;for(let Ke=0;Ke<P.length;Ke++){let ut=P[Ke];Ke>0&&(t.dim.noFormat(" \xB7 "),Pt+=3),ut.kind==="host"?(vn={start:Pt,end:Pt+ut.text.length-1},dr?t.noFormat(ut.text):t.dim.noFormat(ut.text)):t.dim.noFormat(ut.text),Pt+=ut.text.length}}t.dim(" ".repeat(Nt)),Cs?t.noFormat(Y):t.dim.noFormat(Y),Jt={start:st-fe-oe+1,end:st-fe}}})})},Ie=R=>Pn+1+R,tr=()=>Pn+sn+1,$t=()=>Pn+sn+3,Wt=R=>$t()+1+(R-p),dn=()=>$t()+1+Be,Ft=()=>{let R=Xs-bs;if(R<0||R>=sn)return;let P=3+lo;t.moveTo(P,Ie(R))},k=()=>gt?f===0?"f":mt?"h":"u":"x",ho=()=>`ct|${k()}|${on()}|${co}`,ba=()=>`cb|${k()}|${on()}`,ks=R=>`cbb|${k()}|${on()}|${Vr(R)}`,Yr=()=>`h|${Wr}`,nr=R=>{let P=a[R],N=P&&P.priority&&P.priority>0?"* ":" ",Y=Te[R]??"";return`sr|${f===R+1&&!mt&&gt?"1":"0"}|${N}${Y}`},Ue=()=>{Oe(()=>{t.hideCursor(),fo(),rn(),Pn=1,ye.ensureSize(st,ys),ye.paintRow(Pn,ho(),()=>{Jr()});for(let R=0;R<sn;R++){let P=bs+R;ye.paintRow(Ie(R),ks(P),()=>{bn(P)})}ye.paintRow(tr(),ba(),()=>{vs()}),ye.paintRow(tr()+1,"blank",()=>{}),ye.paintRow($t(),Yr(),()=>{t.dim.noFormat(` ${Wr}`)});for(let R=0;R<Be;R++){let P=p+R,N=$t()+1+R;P<a.length?ye.paintRow(N,nr(P),()=>{er(P)}):ye.paintRow(N,"blank",()=>{})}me();for(let R=dn()+1;R<=ys;R++)ye.paintRow(R,"blank",()=>{});f===0&&(Ft(),t.hideCursor(!1))})},Vn=()=>{ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Ue()},mo=()=>{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=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")(`
164
209
 
165
- `);for(let R of y0){if(R===null){t(`
166
- `);continue}let[P,N]=R;t.brightCyan.noFormat(` ${P.padEnd(g0)}`),t.noFormat(N)(`
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)(`
167
212
  `)}t(`
168
213
  `),t.dim.noFormat(" press any key to dismiss")(`
169
- `)})},zt=()=>bt+4,Mc=2,rt=0,Ot=()=>{ys=Nr(t);let R=Math.max(2,ys-(bt+3)-Mc);return Math.max(1,Math.floor(R/2))},go=()=>{let R=Ot();H<rt?rt=H:H>=rt+R&&(rt=H-R+1),rt+R>j.length&&(rt=Math.max(0,j.length-R)),rt<0&&(rt=0)},va=R=>{st=En(t);let P=Math.max(2,st-3),N="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,P-N.length));R?t.brightBlue.noFormat(`\u256D${N}${Y}\u256E`):t.dim.noFormat(`\u256D${N}${Y}\u256E`),t.styleReset()},sr=()=>{st=En(t),wa=Math.max(10,st-rb);let R=F.state();Zs=ms(R.buffer,wa);let P=Ys(Zs,R,m0);bt=P.rendered,Mn=P.windowStart,uo=P.cursorVisualRow,zr=P.cursorVisualCol},yo=(R,P)=>{st=En(t);let N=Math.max(2,st-3),Y=Zs[R],oe="";Y&&(oe=(F.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.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()},Sa=R=>{st=En(t);let P=Math.max(2,st-3),N="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${N}\u256F`):t.dim.noFormat(`\u2570${N}\u256F`),t.styleReset()},rr=()=>3+zr,ir=()=>2+(uo-Mn),Lt=()=>{let R=$==="input";Oe(()=>{R&&t.hideCursor(),t.moveTo(1,1),va(R);for(let P=0;P<bt;P++)t.moveTo(1,2+P),yo(Mn+P,R);t.moveTo(1,2+bt),Sa(R),R&&(t.moveTo(rr(),ir()),t.hideCursor(!1))})},St=()=>{Oe(()=>{t.hideCursor();for(let R=0;R<bt;R++)t.moveTo(1,2+R),yo(Mn+R,!0);t.moveTo(rr(),ir()),t.hideCursor(!1)})},_c={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},wo=(R,P)=>{let N=j[R];if(!N)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=En(t),oe=Math.max(20,Y-xf),fe=nt(N.sessionId),Fe=N.title??Ge(N.cwd),Nt=P&&N.snippets.length>1?` [${L+1}/${N.snippets.length}]`:P&&N.totalMatches>N.snippets.length?` [${N.snippets.length} of ${N.totalMatches}]`:"",Pt=`${fe} ${N.status==="live"?"live":"cold"}`,Ke=Math.max(5,oe-Pt.length-Nt.length-2),ut=ea(Fe,Ke),ln=`${Pt} ${ut}${Nt}`.padEnd(oe),yt=N.snippets[P?L:0],je=yt?_c[yt.kind]??yt.kind:"",Sn=yt?.toolName?`${je} \xB7 ${yt.toolName}`:je,ti=Math.max(10,oe-Sn.length-6),kn=yt?ea(yt.text,ti):"",cr=yt?` ${Sn} ${kn}`:" (no snippet)";return{rowBudget:oe,line1:ln,line2:cr.padEnd(oe+xf),focusedRow:P}},or=(R,P)=>{let{line1:N,focusedRow:Y}=wo(R,P);Y?t.brightWhite.bgBlue.noFormat(`\u276F ${N}`):t.noFormat(` ${N}`),t.styleReset()},Yn=(R,P)=>{let{line2:N}=wo(R,P);t.dim.noFormat(N),t.styleReset()},Is=()=>{if(X)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()}},Qn=()=>{sr();let R=$==="input",P=F.state().buffer.join(`
170
- `);Oe(()=>{t.hideCursor(),ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),va(R);for(let Y=0;Y<bt;Y++)t.moveTo(1,2+Y),yo(Mn+Y,R);t.moveTo(1,2+bt),Sa(R);let N=j.length;if(N===0)t.moveTo(1,zt()),X||(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,zt()+1),Is();else{go();let Y=Ot(),oe=$!=="input";for(let fe=0;fe<Y;fe++){let Fe=rt+fe;t.moveTo(1,zt()+fe*2),Fe<N?or(Fe,oe&&Fe===H):t.eraseLineAfter(),t.moveTo(1,zt()+fe*2+1),Fe<N?Yn(Fe,oe&&Fe===H):t.eraseLineAfter()}t.moveTo(1,zt()+Y*2),Is()}R&&(t.moveTo(rr(),ir()),t.hideCursor(!1))})},xs=(R,P)=>{let N=R-rt;N<0||N>=Ot()||Oe(()=>{t.moveTo(1,zt()+N*2),or(R,P),t.moveTo(1,zt()+N*2+1),Yn(R,P)})},ar=()=>{Oe(()=>{t.moveTo(1,zt()+Ot()*2),Is()})},Qr=()=>{Oe(()=>{let R=Ot(),P=j.length,N=$!=="input";for(let Y=0;Y<R;Y++){let oe=rt+Y;t.moveTo(1,zt()+Y*2),oe<P?or(oe,N&&oe===H):t.eraseLineAfter(),t.moveTo(1,zt()+Y*2+1),oe<P?Yn(oe,N&&oe===H):t.eraseLineAfter()}t.moveTo(1,zt()+R*2),Is()})},bo=()=>F.state().buffer.join(`
171
- `),$c=R=>{let P=bt;F.feed({type:"paste",text:R}),sr(),bt!==P?Qn():St()},Fc=async()=>{let R=bo().trim();if(R.length!==0){if(a.length===0){D="no sessions in view to search",Qn();return}X=!0,D=null,Qn();try{let P=await Sg(e.target,R,{sessionIds:a.map(N=>N.sessionId)});j=P.results,K=P.truncated,H=0,L=0,rt=0,$=P.results.length>0?"results":"input",sr()}catch(P){D=`search failed: ${P.message}`}finally{X=!1,Qn()}}},Gn=()=>{},Bt=()=>{Oe(()=>{let R=f===0;R&&t.hideCursor(),ye.paintRow(Pn,ho(),()=>{Jr()}),ye.paintRow(tr(),ba(),()=>{vs()});for(let P=0;P<sn;P++){let N=bs+P;ye.paintRow(Ie(P),ks(N),()=>{bn(N)})}R&&(Ft(),t.hideCursor(!1))})},cn=()=>{Oe(()=>{let R=Se.state();Tt=ms(R.buffer,ws);let P=Ys(Tt,R,Rc);bs=P.windowStart,Xs=P.cursorVisualRow,lo=P.cursorVisualCol;let N=f===0;N&&t.hideCursor();for(let Y=0;Y<sn;Y++){let oe=bs+Y;ye.paintRow(Ie(Y),ks(oe),()=>{bn(oe)})}N&&(Ft(),t.hideCursor(!1))})},Gr=R=>{R<p||R>=p+Be||Oe(()=>{ye.paintRow(Wt(R),nr(R),()=>{er(R)})})},Et=()=>{Oe(()=>{for(let R=0;R<Be;R++){let P=$t()+1+R,N=p+R;N<a.length?ye.paintRow(P,nr(N),()=>{er(N)}):ye.paintRow(P,"blank",()=>{})}me()})},_n=()=>{Oe(()=>{ye.paintRow($t(),Yr(),()=>{t.dim.noFormat(` ${Wr}`)});for(let R=0;R<Be;R++){let P=$t()+1+R,N=p+R;N<a.length?ye.paintRow(P,nr(N),()=>{er(N)}):ye.paintRow(P,"blank",()=>{})}me(),f===0&&(Ft(),t.hideCursor(!1))})},Kt=!1,Xn="",Xr=0,ka=200,Zn=null,Zr=!1,Jt=null,Cs=!1,vn=null,dr=!1,Vt=null,vo=null,Ia=null,ei=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let Y=P.indexOf("\x1B[I"),oe=P.indexOf("\x1B[O"),fe=Y===-1?oe:oe===-1?Y:Math.min(Y,oe);if(fe===-1)break;let Fe=gt;gt=fe===Y,gt&&(Xr=Date.now()),Fe!==gt&&!lt&&Kr.length<=1&&Oe(()=>{Bt(),Et()}),P=P.slice(0,fe)+P.slice(fe+"\x1B[I".length)}if(P.length===0)return}if(!Kt&&P===""&&vo){vo();return}if(!Kt&&(P===""||P==="\x1B_"||P==="\x1B")){Ia?.(P);return}if(Kt){let Y=P.indexOf(sa);if(Y===-1){Xn+=P;return}Xn+=P.slice(0,Y),Kt=!1;let oe=Buffer.from(Xn,"binary").toString("utf-8").replace(/\r\n?/g,`
172
- `);Xn="";let fe=P.slice(Y+sa.length);if(T)$==="input"&&!X&&$c(oe);else if(f===0&&!h){Se.feed({type:"paste",text:oe});let Fe=Se.state(),Nt=ms(Fe.buffer,ws);Ys(Nt,Fe,Rc).rendered!==sn?Ue():cn()}fe.length>0&&Vt&&Vt(Buffer.from(fe,"binary"));return}let N=P.indexOf(Qi);if(N===-1){Vt?.(R);return}N>0&&Vt?.(Buffer.from(P.slice(0,N),"binary")),P=P.slice(N+Qi.length),Kt=!0,P.length>0&&ei(Buffer.from(P,"binary"))};return Ue(),await new Promise(R=>{let P=null,N=!1,Y=null,oe=!1,fe=Kr,Fe=E=>{fe.push(E)},Nt=()=>{fe.pop(),lt||fe[fe.length-1]?.onResize()},Pt={push:Fe,pop:Nt},Ke=()=>({kind:"new",cwd:r}),ut=async()=>{Rs(),ye.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Fe({onKey:()=>{},onResize:()=>{}});let U;try{U=await jr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Nt(),$n()}U.kind==="ok"&&U.path!==r&&(r=U.path,i=Tc(i,r),tt()),lt||Ue()};Gn=()=>{F=new ps({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,rt=0,D=null,X=!1,$="input",T=!1,Nt()};let ln=(E,U,re)=>{ti(),fe[fe.length-1]?.onKey(E,U,re)},yt=()=>{lt||fe[fe.length-1]?.onResize()};Ia=E=>{lt||fe[fe.length-1]?.onKey(E,null,{})};let je=()=>{if(lt)return;lt=!0,fe.length=0,P&&(clearInterval(P),P=null),Y&&(Y.abort(),Y=null,N=!1),t.off("key",ln),t.off("mouse",ss),t.off("resize",yt),process.stdout.write(ls),process.stdout.write(ia);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",ei),E.stdin.on("data",Vt),Vt=null),Kt=!1,Xn="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,dn()+1),t(`
173
- `)},Sn=()=>{if(lt||fe.length>1||S!=="normal"||h||oe)return;N&&Y&&(Y.abort(),Y=null,N=!1);let E=f>0?a[f-1]?.sessionId:void 0;N=!0;let U=new AbortController;Y=U,As(E,{silent:!0,signal:U.signal}).finally(()=>{Y===U&&(Y=null),N=!1})},ti=()=>{lt||(P&&clearInterval(P),P=setInterval(Sn,3e3))},kn=()=>(je(),R({kind:V?"exit":"abort"}),!0),cr=()=>{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(`
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(`
174
219
  `);return`${f}:${p}:${Le??""}
175
- ${E}`},As=async(E,U={})=>{try{let re=U.silent?cr():"",W=u,te=await qn(e.target,{includeNonInteractive:!0,signal:U.signal}),se=E??(f>0?a[f-1]?.sessionId:void 0);if(i=Tc(te,r),tt(),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)),rn(),U.silent&&cr()===re)return;u===W?_n():Ue()}catch(re){if(U.silent)return;Le=`refresh failed: ${re.message}`,Ue()}},xa=async E=>{if(!x)return;let U=x;S="busy",me();try{await wg(e.target,U.sessionId,E),S="normal",x=null,Q="",await As(U.sessionId)}catch(re){S="normal",x=null,Q="",Le=`rename failed: ${re.message}`,me()}},So=async E=>{try{await vg(e.target,E.sessionId),Le="title regen queued (press r to refresh)",me()}catch(U){Le=`regen failed: ${U.message}`,me()}},ft=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=Tc(i,r),tt(),ct(te),Ue(),Le=W>0?"priority: high":"priority: normal",me();try{await bg(e.target,E.sessionId,re)}catch(se){Le=`priority failed: ${se.message}`,me()}},es=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 yg(e.target);await As(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}},ts=async E=>{if(!x)return;let U=x;S="busy",me();try{E==="kill"?await Wn(e.target,U.sessionId):await kg(e.target,U.sessionId),S="normal",x=null,U.sessionId===e.currentSessionId&&(V=!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 As(re)}catch(re){S="normal",x=null,Le=`${E} failed: ${re.message}`,me()}},In=(E,U)=>{E===0!=(U===0)&&(Bt(),U===0?(t.hideCursor(!1),Ft()):t.hideCursor())},it=E=>{let U=Math.min(u-1,Math.max(0,f+E));if(U===f)return;let re=f;f=U,rn(),Oe(()=>{Et(),In(re,f)})},lr=()=>Le===null?!1:(Le=null,me(),!0),xn=()=>{mo(),Fe({onKey:E=>{if(E==="CTRL_C"){je(),R({kind:"abort"});return}Nt()},onResize:()=>mo()})},ns=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 ${nt(E.sessionId)}`)(`
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)}`)(`
176
221
 
177
222
  `),W)t.dim.noFormat(" loading\u2026")(`
178
223
  `);else if(re!==null)t.brightRed.noFormat(` ${re}`)(`
179
224
  `);else if(U!==null)for(let qe of U)t.noFormat(` ${qe}`)(`
180
225
  `);t(`
181
226
  `),t.dim.noFormat(" Esc / ^C to return")(`
182
- `)})};te();let se=new AbortController,ve={onKey:qe=>{if(qe==="ESCAPE"||qe==="CTRL_C"){se.abort(),Nt();return}},onResize:()=>te()};Fe(ve),(async()=>{try{let qe=await tn(`${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 Qe=await qe.json(),ot=Tn(Qe),xe=Lu(ot,E.status);U=Zd(xe,!1).replace(/\n$/,"").split(`
183
- `)}catch(qe){if(se.signal.aborted)return;re=`failed to load info: ${qe.message}`}finally{W=!1,!lt&&fe[fe.length-1]===ve&&te()}})()},ur=()=>{if(a.length===0){Le="no sessions to search",me();return}F=new ps({history:[],collapsePastes:!1}),j=[],K=!1,H=0,L=0,rt=0,D=null,X=!1,$="input",T=!0,sr(),Qn(),Fe({onKey:(U,re,W)=>{if($==="input"){if(X)return;if(U==="ESCAPE"||U==="CTRL_C"){Gn();return}if(U==="ENTER"||U==="KP_ENTER"){if(bo().trim().length===0)return;Fc();return}if((U==="DOWN"||U==="TAB"||U==="CTRL_N")&&j.length>0){$="results",H=0,L=0,Oe(()=>{Lt(),xs(0,!0),ar(),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 ot=xc(U);ot!==null&&(se={type:"key",name:ot})}if(se===null){t.moveTo(rr(),ir());return}F.feed(se);let ve=F.state();if(te.buffer.length===ve.buffer.length&&te.buffer.every((ot,xe)=>ot===ve.buffer[xe])&&te.row===ve.row&&te.col===ve.col){t.moveTo(rr(),ir());return}let Qe=bt;sr(),bt!==Qe?Qn():St();return}if($==="results"){if(U==="ESCAPE"||U==="CTRL_C"){Gn();return}if(U==="CTRL_F"){$="input",Qr(),ar(),Lt();return}if(U==="ENTER"||U==="KP_ENTER"){let se=j[H];if(!se)return;let ve=a.find(Qe=>Qe.sessionId===se.sessionId);if(!!ve?.importedFromMachine&&!ve.upstreamSessionId){je();let Qe={kind:"attach",sessionId:se.sessionId};ve.agentId!==void 0&&(Qe.agentId=ve.agentId),R(Qe);return}(async()=>{let Qe=await tb(t,{sessionId:se.sessionId,title:se.title,cwd:se.cwd},Pt);if(Qe==="cancel"){je(),R({kind:"abort"});return}if(Qe==="back")return;je();let ot={kind:"attach",sessionId:se.sessionId,readonly:Qe==="view"};ve?.agentId!==void 0&&(ot.agentId=ve.agentId),R(ot)})();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,xs(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,xs(H,!0);return}let te=se=>{if(se<0&&H===0){$="input",Oe(()=>{xs(0,!1),ar(),Lt()});return}let ve=Math.min(j.length-1,Math.max(0,H+se));if(ve===H)return;let qe=H,Qe=rt;H=ve,L=0,go(),rt!==Qe?Qr():(Oe(()=>{xs(qe,!1),xs(H,!0)}),ar())};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(-Ot());return;case"PAGE_DOWN":te(Ot());return;case"HOME":te(-H);return;case"END":te(j.length);return}return}},onResize:()=>Qn()})},ni=(E,U,re)=>{if(S!=="busy"){if(E==="CTRL_O"){ut();return}if(E==="CTRL_L"){Vn();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let W=Q.trim();if(W.length===0){S="normal",x=null,Q="",me();return}xa(W);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",x=null,Q="",gs(),me();return}if(E==="BACKSPACE"){Q.length>0&&(de(),Q=Q.slice(0,-1),me());return}if(E==="CTRL_U"){Q.length>0&&(de(),Q="",me());return}if(E==="CTRL_W"){let W=Q.replace(/\s+$/,""),te=W.lastIndexOf(" "),se=te>=0?W.slice(0,te):"";se!==Q&&(de(),Q=se,me());return}if(E===""){ze(),me();return}if(E==="\x1B_"||E==="\x1B"){Gs(),me();return}if(re?.isCharacter){de(),Q+=E,me();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(re?.isCharacter&&(E==="y"||E==="Y")){ts(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(lr(),E==="CTRL_F"&&f!==0){ur();return}if(f===0&&!h){if(E==="ESCAPE"){kn();return}if(E==="ENTER"||E==="KP_ENTER"){je();let xe=Se.expandedText(),kt=Ke();xe.trim().length>0&&(kt.prompt=xe),R(kt);return}if(E==="UP"&&b){let xe=Date.now(),kt=xe-v;if(v=xe,kt<y){Ft();return}b=!1}if(E==="DOWN"){let xe=Se.state(),kt=xe.historyIndex!==-1||xe.queueIndex!==-1,Dt=Tt.length===0||Xs===Tt.length-1;if(!kt&&Dt&&a.length>0){it(1);return}}if(E==="PAGE_DOWN"&&(Tt.length===0||Xs===Tt.length-1)&&a.length>0){it(1);return}if(E==="CTRL_P"){a.length>0&&it(1);return}b=!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=xc(E);xe!==null&&(te={type:"key",name:xe})}if(te===null){Ft();return}let se=Se.feed(te),ve=Se.state(),qe=W.buffer.length===ve.buffer.length&&W.buffer.every((xe,kt)=>xe===ve.buffer[kt])&&W.row===ve.row&&W.col===ve.col;if(se.some(xe=>xe.type==="exit")){kn();return}if(qe){Ft();return}let Qe=ms(ve.buffer,ws);if(Ys(Qe,ve,Rc).rendered!==sn){Ue();return}cn();return}if(!h&&re?.isCharacter&&E==="?"){xn();return}if(h){if(re?.isCharacter){m+=E,tt(),Ue();return}if(E==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),tt(),Ue()):(h=!1,tt(),Ue());return}if(E==="ESCAPE"||E==="CTRL_C"){h=!1,m="",tt(),Ue();return}}if(re?.isCharacter){if(E==="/"){h=!0,m="",tt(),Ue();return}if(E==="n"||E==="N"){it(1);return}if(E==="p"||E==="P"){it(-1);return}if(E==="c"||E==="C"){let W=f>0?a[f-1]:void 0,te=Ke();W?.cwd&&(te.cwd=W.cwd),je(),R(te);return}if(E==="q"||E==="Q"){kn();return}if(E==="o"||E==="O"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,tt(),ct(W),Ue();return}if(E==="h"||E==="H"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=ib(s.filters.hostFilter,i),tt(),ct(W),Ue();return}if(E==="i"&&f>0){let W=a[f-1];if(!W)return;ns(W);return}if(E==="I"){let W=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,tt(),ct(W),Ue();return}if(E==="r"||E==="R"){let W=f>0?a[f-1]?.sessionId:void 0;As(W);return}if(E==="s"||E==="S"){es();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},Q=W.title??"",S="rename",me();return}if(E==="T"&&f>0){let W=a[f-1];if(!W)return;So({sessionId:W.sessionId});return}if(E==="*"&&f>0){let W=a[f-1];if(!W)return;ft(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}mt=!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&&(b=!0),v=Date.now()),it(-1);return;case"DOWN":case"TAB":case"CTRL_N":it(1);return;case"PAGE_UP":it(-Be);return;case"PAGE_DOWN":it(Be);return;case"HOME":it(1-f);return;case"END":it(u);return;case"ENTER":case"KP_ENTER":{if(mt){je();let se=Se.expandedText(),ve=Ke();se.trim().length>0&&(ve.prompt=se),R(ve);return}if(je(),f===0){R(Ke());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":kn();return}}};Fe({onKey:(E,U,re)=>ni(E,U,re),onResize:()=>{lt||Ue()}});let ss=(E,U)=>{if(lt||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=gt&&Date.now()-Xr<ka,Qe=!gt||qe;if(W){Zn={x:U?.x??-1,y:U?.y??-1},Zr=Qe;return}if(re&&Qe)return;let ot=te&&Zn!==null&&U?.x===Zn.x&&U?.y===Zn.y,xe=ot&&!Zr,kt=ot&&Zr;if(te&&(Zn=null,Zr=!1,!ot))return;if(se||ve){if(a.length===0)return;let Ee=se?-3:3,rs=Math.max(0,a.length-Be),Es=Math.min(rs,Math.max(0,p+Ee));if(Es===p)return;if(p=Es,f>0){let Ht=f-1;Ht<p?f=p+1:Ht>=p+Be&&(f=p+Be)}Et();return}if(!re&&!xe)return;let Dt=U?.y;if(typeof Dt!="number")return;{let Ee=U?.x,rs=Jt!==null&&Dt===dn()&&typeof Ee=="number"&&Ee>=Jt.start&&Ee<=Jt.end,Es=vn!==null&&Dt===dn()&&typeof Ee=="number"&&Ee>=vn.start&&Ee<=vn.end;(rs!==Cs||Es!==dr)&&(Cs=rs,dr=Es,me(),f===0?(Ft(),t.hideCursor(!1)):t.hideCursor(!0))}if(xe&&Jt!==null&&Dt===dn()){let Ee=U?.x;if(typeof Ee=="number"&&Ee>=Jt.start&&Ee<=Jt.end){kn();return}}if(xe&&vn!==null&&Dt===dn()){let Ee=U?.x;if(typeof Ee=="number"&&Ee>=vn.start&&Ee<=vn.end){let rs=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=ib(s.filters.hostFilter,i),tt(),ct(rs),Ue();return}}if(Dt>=Pn&&Dt<=tr()){if((xe||kt)&&f!==0){mt=!1;let Ee=f;f=0,Oe(()=>{Et(),In(Ee,f)});return}re&&!mt&&f!==0&&(mt=!0,Oe(()=>{Bt(),Et()}));return}mt&&(mt=!1,Oe(()=>{Bt(),Et()}));let un=$t()+1,Ts=un+Be-1;if(Dt<un||Dt>Ts)return;let fn=p+(Dt-un);if(fn<0||fn>=a.length)return;let fr=a[fn];if(!fr)return;let pr=fn+1;if(re&&f===0)return;let Oc=f===0,Lc=f===pr;if(kt&&f!==pr){let Ee=f;f=pr,rn(),Oe(()=>{Et(),In(Ee,f)});return}if(kt)return;if(f!==pr){let Ee=f;f=pr,rn(),Oe(()=>{Et(),In(Ee,f)})}if(!xe||Oc||!Lc)return;je();let Ca={kind:"attach",sessionId:fr.sessionId};fr.agentId!==void 0&&(Ca.agentId=fr.agentId),R(Ca)},$n=()=>{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",ei),process.stdout.write(nc),process.stdout.write(ic)),t.on("key",ln),t.on("mouse",ss),t.on("resize",yt)},Rs=()=>{process.stdout.write(ls),process.stdout.write(ia);let E=t;E.stdin&&Vt&&(E.stdin.removeListener("data",ei),E.stdin.on("data",Vt),Vt=null),Kt=!1,Xn="",t.off("key",ln),t.off("mouse",ss),t.off("resize",yt),t.grabInput(!1),t.hideCursor(!1)};if($n(),process.platform!=="win32"){let E=!1,U=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),$n(),lt||Vn())};vo=()=>{E||lt||(E=!0,Rs(),t.fullscreen(!1),process.stdout.write(`${ra}${sc}
184
- `),process.once("SIGCONT",U),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(Sn,3e3)})}function w0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+ea(Ge(t),s)}function Tc(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="live",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 b0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function ib(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function v0(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[nt(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ge(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var xf,Rc,m0,rb,g0,y0,ob=J(()=>{"use strict";Vd();he();Nn();Zo();dd();tf();Sf();kf();If();to();nf();cf();oa();Ar();Bu();xf=2,Rc=4,m0=4,rb=4,g0=20,y0=[["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 live 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 x0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Rf(t,e,n,s){us();let r=x0(e,n??S0),i=0,o=()=>{let u=Nr(t)-8;return Math.max(1,Math.min(k0,e.length,u))},a=()=>{let u=o();r<i?i=r:r>=i+u&&(i=r-u+1);let f=Math.max(0,e.length-u);i>f&&(i=f),i<0&&(i=0)},c=()=>{a();let u=o(),f=u+4,p=Math.min(I0,Math.max(40,En(t)-8)),h=fs(t,{contentHeight:f,contentWidth:p,title:s?.title??"Select agent"}),m=h.contentW,y=0;t.moveTo(h.contentX,h.contentY+y),t.noFormat(` ${s?.intro??"Which agent should this session use?"}`),y+=2;let b=Math.min(e.length,i+u);for(let S=i;S<b;S++){let 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(oc(dt(j,m),m))}else{t.noFormat(F);let j=m-F.length-2;j>1&&t.dim.noFormat(` ${dt($,j)}`)}y++}y++,t.moveTo(h.contentX,h.contentY+y);let v=e.length>u?` (${r+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${v}`),h},d=()=>{r<e.length-1&&(r++,c())},l=()=>{r>0&&(r--,c())};return zs({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 S0,k0,I0,ab=J(()=>{"use strict";to();S0="opencode",k0=20,I0=88});import*as cb from"fs";import*as lb from"os";import*as Ec from"path";function ub(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 C0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function A0(t){return t.replace(/\\ /g," ")}function db(t){return t.replace(/ /g,"\\ ")}function R0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function T0(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=lb.homedir()+n.slice(1)),Ec.isAbsolute(n)?n:Ec.resolve(e,n)}function E0(t){let e;try{e=cb.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function fb(t,e,n=E0){if(!C0(t))return null;let s=A0(t),{dirPrefix:r,base:i}=R0(s),o=T0(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:db(r+p),candidates:l}}let u=ya(d.map(f=>f.name));return{replacement:db(r+u),candidates:l}}var pb=J(()=>{"use strict";Ac()});function hb(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 mb(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function gb(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 yb=J(()=>{"use strict"});import{appendFileSync as P0,readFileSync as M0,statSync as _0,renameSync as $0}from"fs";import{nanoid as wb}from"nanoid";import F0 from"terminal-kit";import Tf from"fs/promises";import qr from"path";function O0(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function L0(t){let e=Pc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function B0(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 Pc(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 N0(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function D0(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=Pc(o.representative),d=e[a]??0,l=n[a]?Pf:c[d]??c[0]??"";return{label:N0(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 H0(t,e,n){return t===Pf?{type:"dismiss",method:vw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:bw,params:{sessionId:n,questionId:e.id,answer:t}}}function U0(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]?Pf:Pc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=H0(c,l,r);u!==null&&i.push(u)}}return i}function j0(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=Pc(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:U0(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function bb(t){if(!Array.isArray(t))return;let e=Un({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Ef(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 z0(t,e){e.has(t)?e.delete(t):e.add(t)}async function kb(t){let e=await we(),n=t.target??await Ut(e);Ab=e.tui.logMaxBytes,n.isLocal&&!t.target&&await Hs(e);let s=F0.terminal;Xw(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Jf(e),defaultEnterAction:e.tui.defaultEnterAction},o=Cf(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
185
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await J0(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await da();if(f&&process.stderr.write(`\u2728 ${ca(f)}
186
- `),process.stdout.isTTY){let p=await Er(e);if(p?.version!==void 0){let h=p.version!==pe,m=Ls(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let b=h?`daemon ${p.version} \u2260 cli ${pe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Fn()} daemon restart\` to apply.`)+`
187
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=nt(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Fn()} --session ${p}${h}
188
- `)}}function K0(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 X=e[D];if(X===void 0)continue;let Q=n.get(X);Q&&!Mu(Q.status)&&L.push(X)}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",b=y?`amended \xB7 ${zn(h)}`:`stopped (${m}) \xB7 ${zn(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${zn(h)}`:`thought \xB7 ${zn(h)}`;else{let K=c===1?"tool":"tools",H=m!==null?b:f?zn(h):`took ${zn(h)}`,L=[`${c} ${K}`,H];f&&d&&u>0&&L.push(`${u} hidden`),v=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:v,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=na(H,p);for(let D of L)D.hoverSubKey=K;if(F.push(...L),j.push(...L.map(()=>K)),o?.has(K)){let D=qg(H);for(let X of D)X.hoverSubKey=K;F.push(...D),j.push(...D.map(()=>K))}}}return{lines:F,rowOwners:j}}async function J0(t,e,n,s,r,i,o){let a=await V0(t,e,n,s,o);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=Q0(t,c);d.write(c);let l=n.isLocal?async()=>(await Ut(await we())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,h=new no({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>nn({src:"resilient-ws",line:g})}),m=new jt(h);await h.start(),m.onNotification(Ja,g=>{let w=Xp.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,x=(g,w)=>{g&&(b?b(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,X=!1,Q,be=null,G=null,de=null,ze=null,Gs=()=>setInterval(()=>{if(be===null||V===null)return;let g=ze===null?0:Date.now()-ze;V.setBanner({elapsedMs:Date.now()-be,stalled:g>=q0}),Ht()},1e3),gs=!1,Le=g=>{let w=L;L=Math.max(0,L+g);let I=typeof V<"u"&&V!==null;w===0&&L>0?(X=!1,be=Date.now(),ze=Date.now(),Se?.setTurnRunning(!0),I&&V.setBanner({status:"busy",elapsedMs:0,stalled:!1}),G===null&&I&&(G=Gs())):w>0&&L===0?(X=!1,be=null,ze=null,Se?.setTurnRunning(!1),G!==null&&(clearInterval(G),G=null),I&&V.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&X&&(X=!1,I&&V.setBanner({status:"busy",stalled:!1}))},V=null,Se=null,Jn,ye=null,ys=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"]),st=g=>{let{update:w}=g??{},I=Un(w,{cwd:ct});Y0(w,I),ze=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!ys.has(C)){let A=w??{};typeof A.messageId=="string"&&(Jn=A.messageId)}if(C==="prompt_received"?Le(1):I?.kind==="turn-complete"&&(Le(-1),K=!0),C==="permission_resolved"){Wr(w);return}if(C==="hydra_compaction"){bs(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),wa(w))};m.onNotification("session/update",g=>{if(!v){if(ye!==null){ye.push(g);return}st(g)}}),m.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&Le(-L),typeof V<"u"&&V!==null&&V.setBanner({status:"cold",elapsedMs:void 0})});let Be=new Map,co=200,ws=0,Tt=!1,sn=4e3;m.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,M=setTimeout(()=>{v||(Be.delete(C),Ke.set(C,Pt(C,A)),V&&Se&&Sn())},co);Be.set(C,M)}else Ke.set(w.messageId,Pt(w.messageId,w.prompt)),V&&Se&&Sn();if(on!==void 0&&w.originator?.clientId===on){let C=ut.shift();C&&(C.messageId=w.messageId,ln.set(w.messageId,C))}}),m.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!Ke.has(w.messageId))return;Ke.set(w.messageId,Pt(w.messageId,w.prompt));let I=ln.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}V&&Se&&Sn()}),m.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(Q=w.messageId);let I=Be.get(w.messageId);I!==void 0&&(clearTimeout(I),Be.delete(w.messageId)),Ke.delete(w.messageId)&&V&&Se&&Sn();let A=ln.get(w.messageId);A&&(ln.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(v)return;let w=g??{};if(!(typeof V<"u"&&V!==null))return;ws=Date.now(),Tt=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),m.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let I=w.cancelledMessageId;yt.add(I),je!==null&&je.messageId!==void 0&&je.messageId===I&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),je=null,yt.delete(I))});let bs=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)}},Xs=()=>{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))},lo=()=>{de!==null&&(clearInterval(de),de=null)},Wr=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}),Pn(I,C?{outcome:C}:void 0)},Te=null,Pn=(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"}})},wa=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"||Pn(w.toolCallId,void 0))},Zs=()=>{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})},bt=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(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Dr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(Z=>({optionId:Z.optionId,name:Ae(Z.name??""),...Z.kind!==void 0?{kind:Z.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",M=Ae(A),B=Ae(Yy(Vy(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(Z=>{Te={title:M,detail:B,options:C,selectedIndex:0,resolve:Z,toolCallId:O},Zs()})}),m.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let Mn,uo,zr=!0,fo=!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}});uo=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(zr=!1),fo=Gt(g?._meta??void 0).prompt?.amending===!0}catch{}let ke=a.sessionId,tt=a.agentId,ct=a.cwd,rn,on,mt,gt,lt,Kr,Jr,vs,Vr,bn,er=!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:{[Ct]:g}}:{}},I=await Dy({request:()=>m.request("session/new",w),showBanner:(M,B,O)=>Hy(t,M,B,O,{authenticate:Z=>m.request("authenticate",{methodId:Z})}),resolveOnboarding:async M=>{if(M)try{return(await qd(n)).find(Z=>Z.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId});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=Gt(C._meta??void 0);A.clientId&&(on=A.clientId),Mn=A.upstreamSessionId,A.agentId&&(tt=A.agentId),A.cwd&&(ct=A.cwd),A.title&&(rn=A.title),mt=A.currentModel,gt=A.currentMode,Vr=A.currentUsage,bn=A.turnStartedAt,A.availableCommands&&(lt=xd(A.availableCommands)),A.availableModes&&(Kr=A.availableModes),Jr=bb(C.configOptions),vs=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:{[Ct]:g}}:{}});ke=w.sessionId,w.clientId&&(on=w.clientId),r.sessionId=ke,r.readonly=s.readonly===!0;let I=Gt(w._meta??void 0);er=I.resurrected===!0,Mn=I.upstreamSessionId,I.agentId&&(tt=I.agentId),I.cwd&&(ct=I.cwd),I.title&&(rn=I.title),mt=I.currentModel,gt=I.currentMode,Vr=I.currentUsage,bn=I.turnStartedAt,I.availableCommands&&(lt=xd(I.availableCommands)),I.availableModes&&(Kr=I.availableModes),Jr=bb(w.configOptions),vs=I.queue}let Ss=_.tuiHistoryFile(ke),po=_.globalTuiHistoryFile(),vt=await No(Ss).catch(()=>[]),an=await No(po).catch(()=>[]);an.length>e.tui.promptHistoryMaxEntries&&(an=an.slice(an.length-e.tui.promptHistoryMaxEntries));let me=[...vt],Ie=new ps({history:ad(an,me)});Se=Ie;let tr=!1,$t=(g,w)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Do(vt,I),M=A!==vt;vt=A,me=Do(me,C);let B=Do(an,I,e.tui.promptHistoryMaxEntries),O=B!==an;an=B,Ie.setHistory(ad(an,me)),M&&Cr(Ss,vt).catch(()=>{}),O&&Yh(po,I).catch(()=>{})};L>0&&Ie.setTurnRunning(!0);let Wt=null,dn=null;Yw(Qw(e.tui.ambiguousWidth,process.env)),zg(e.tui.diffContextLines);let Ft=!1,k,ho=()=>{Ft&&(Ft=!1,k.start())},ba=()=>{Ft||(Ft=!0,k.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",ho);let ks=null,Yr=null;k=new Ic({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"?ba:void 0,onBlockClick:(g,w)=>{Wb(g,w)},onBlockDoubleClick:(g,w)=>qb(g,w),onBlockVisible:g=>{Hb(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=Rs.get(g);if(w!==void 0&&w.length>0)return new Set(w);let I=k.contiguousRun(g,new Set($n.keys()));return I.length>0?new Set(I):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){ks=k.bannerHitAt(g.x,g.y),Yr=ks?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let I=Yr,C=ks;if(Yr=null,ks=null,C!==null&&I!==null&&I.x===g.x&&I.y===g.y&&k.bannerHitAt(g.x,g.y)===C){if(C==="mode"){As(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Ef(A))return;oe(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&Ef(w)||oe(w)},onKey:g=>{for(let w of g){if(D&&$c(w)||Te&&rr(w)||Fc(w)||Ia(w)||vo(w)||Sa(w)||va(w)||yo(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&&Ef(C)||oe(C)}go(),k.setBannerSearchIndicator(Ie.state().historySearchQuery),k.setAttachments(Ie.state().attachments),k.refreshPrompt()}}),V=k,k.setStickyBottomKey("plan");let nr=[{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=lt??[],Vn=Kr??[],mo=Jr??[],zt=()=>mo.find(g=>g.id==="agent"),Mc=()=>{let g=new Set,w=[];for(let I of[...nr,...Ue])g.has(I.name)||(g.add(I.name),w.push(I));return w},rt=()=>{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=Mc().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Ot=[],go=()=>{let g=rt();if(g.length>0){Ot=[],k.setCompletions(g);return}k.setCompletions(Ot)},va=g=>{if(g.type!=="key"||g.name!=="tab")return Ot.length>0&&(Ot=[]),!1;let w=rt();if(k.isOverlayOpen()&&w.length===0)return k.toggleFocusedPane(),!0;if(w.length>0){Ot=[];let I=Ie.state().buffer[0]??"",C=nb({matches:w.map(A=>A.name),firstLine:I});return C===null||Ie.replaceFirstLine(C),!0}return sr()},sr=()=>{let g=Ie.state(),w=g.buffer[g.row]??"",I=ub(w,g.col);if(I===null)return!1;let C=fb(I.token,ct);return C===null?!1:(C.replacement!==I.token&&Ie.replaceRangeOnCurrentLine(I.start,g.col,C.replacement),Ot=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},yo=g=>!k.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(F&&(F.cancel(),F=null,j=null),k.closeBtwOverlay(),!0),Sa=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},rr=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),Zs(),!0;case"down":return Te.selectedIndex=Math.min(w.length-1,Te.selectedIndex+1),Zs(),!0;case"enter":{let I=w[Te.selectedIndex];return I&&bt(I.optionId),!0}case"escape":case"ctrl-c":return bt(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&&bt(C.optionId),!0}return!0},ir=tt||uo||"?",Lt={...Vr??{}};d.finalize(),k.start({skipFullscreen:!0}),k.setHideThoughts(!i.showThoughts),k.setSessionbar({agent:ir,cwd:ct,sessionId:ke,title:rn,model:mt,usage:{...Lt}}),gt&&k.setBanner({currentMode:gt}),da().then(g=>{g&&k.notify(`\u2728 ${ca(g)}`,3e4)}).catch(()=>{});let St=null,_c=new Promise(g=>{St=g}),wo=()=>{m.notify("session/cancel",{sessionId:ke}).catch(()=>{})},or=()=>{V!==null&&L===1&&(X=!0,V.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Yn=()=>{if(Wt){Wt.cancel(),or();return}if(L>0){wo(),or();return}Is()},Is=()=>{R(0)},Qn=()=>{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]],...W0]},xs=()=>{if(k.isHelpPromptActive()){k.setHelpPrompt(null);return}k.setHelpPrompt({title:"Hotkeys",entries:Qn(),hint:"any key dismisses \xB7 /help lists commands"})},ar=()=>{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(()=>{})},Qr=()=>{D=!1,k.setCompactionPrompt(null)},bo=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})},$c=g=>{if(!D)return!1;if(g.type==="key"){if(g.name==="escape")return Qr(),!0;if(g.name==="up")return bo(-1),!0;if(g.name==="down")return bo(1),!0;if(g.name==="enter"){let w=k.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?ar():Qr(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return ar(),!0;if(w==="n"||w==="2")return Qr(),!0}return!0},Fc=g=>k.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",k.setHelpPrompt(null),!0):!1,Gn=["tools","plan","thoughts","diffs","mouse","enter"],Bt=0,cn=null,Gr=[],Et=[],_n=[],Kt=0,Xn=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}},Xr=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"}},ka=()=>({title:"Session options",options:Gn.map(g=>({label:Xr(g),value:Xn(g)})),selectedIndex:Bt}),Zn=()=>{k.isOptionsPromptActive()&&cn===null&&k.setOptionsPrompt(ka())},Zr=()=>{if(k.isOptionsPromptActive()){k.setOptionsPrompt(null);return}Bt=0,k.setOptionsPrompt(ka())},Jt=()=>{if(cn===null)return;let g=D0(cn,Gr,_n,Kt);k.setOptionsPrompt(g)},Cs=()=>{cn=null,Gr=[],Et=[],_n=[],Kt=0,k.setOptionsPrompt(null)},vn=async()=>{if(cn!==null){Cs();return}try{let w=await m.request(ww,{sessionId:ke}),I=O0(w.questions??[]);if(I.length===0){k.notify("no open questions");return}let C=B0(I);cn=C,Kt=0,Gr=C.map(A=>L0(A.representative)),Et=C.map(()=>!1),_n=C.map(()=>!1),Jt()}catch(g){k.notify("clarifier unavailable"),nn({src:"questions",step:"list_failed",error:g.message})}},dr=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,ur.clear(),ni.clear(),Lb();break;case"plan":i.planExpanded=!i.planExpanded,te=null,Qe();break;case"thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",ts.clear(),Ub();break;case"mouse":{let w=!k.isMouseEnabled();k.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Zn()},Vt=g=>{(async()=>{try{switch(g){case"tools":case"plan":k.notify(`${Xr(g)} is session-only \u2014 not saved`);return;case"thoughts":await Io("showThoughts",i.showThoughts);break;case"diffs":await Io("showFileUpdates",i.showFileUpdates);break;case"mouse":await Io("mouse",i.mouseEnabled);break;case"enter":await Io("defaultEnterAction",i.defaultEnterAction);break}k.notify(`saved default: ${Xr(g)} ${Xn(g)}`)}catch(w){k.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},vo=g=>{if(cn!==null||!k.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Bt=Math.max(0,Bt-1),Zn(),!0;case"down":return Bt=Math.min(Gn.length-1,Bt+1),Zn(),!0;case"enter":{let w=Gn[Bt];return w&&dr(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=Gn[w];return I&&(Bt=w,dr(I)),!0}if(g.ch==="s"||g.ch==="S"){let w=Gn[Bt];return w&&Vt(w),!0}}return!0},Ia=g=>{if(cn===null)return!1;let w=j0(g,!0,cn,Gr,Et,_n,Kt,ke);switch(w.type){case"noop":return!0;case"row":return Kt=w.selectedRow,Jt(),!0;case"cycle":return Gr[w.selectedRow]=w.newValueIndex,Et[w.selectedRow]=!0,_n[w.selectedRow]=!1,Jt(),!0;case"dismiss-toggle":{let I=w.selectedRow;return _n[I]?(_n[I]=!1,Et[I]=!1):(_n[I]=!0,Et[I]=!0),Jt(),!0}case"discard":return Cs(),!0;case"save":{let I=w.dispatches;return Cs(),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(Z){M++,nn({src:"questions",step:"dispatch_failed",method:O.method,error:Z.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},ei=()=>{v=!0,F?(F.cancel(),F=null,j=null):j!==null&&(Wn(n,j).catch(()=>{}),j=null),process.off("SIGINT",Yn),process.platform!=="win32"&&process.off("SIGCONT",ho),G!==null&&(clearInterval(G),G=null),de!==null&&(clearInterval(de),de=null);for(let g of Be.values())clearTimeout(g);Be.clear(),k.clearWindowTitle(),k.stop({keepFullscreen:!0}),Cr(Ss,vt).catch(()=>{}),h.close().catch(()=>{})},R=(g=0)=>{ei(),St&&(St(null),St=null),g!==0&&process.exit(g)},P=async()=>{if(!St)return;F?(F.cancel(),F=null,j=null):j!==null&&(Wn(n,j).catch(()=>{}),j=null),lo(),k.setSynthesisIndicator(null);let g=Ie.state().buffer.join(`
189
- `);g.replace(/\s+$/,"").length>0&&$t(g),k.pauseRepaint(),k.stop({keepFullscreen:!0}),Cr(Ss,vt).catch(()=>{});let w=null,I=null;for(;w===null;){let B=await qn(n,{includeNonInteractive:!0}),O=await Af(t,{cwd:ct,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 Cb(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 Z=B.find(ue=>ue.sessionId===O.sessionId);if(!(Z!==void 0&&!!Z.importedFromMachine&&!Z.upstreamSessionId&&O.readonly!==!0)){if(n.isLocal&&Z&&!Z.importedFromMachine&&O.readonly!==!0&&!(await ua(Z.cwd)).ok){let Ne=await jr(t,Z,{defaultCwd:Xe(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Ne.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(Ne.kind==="back")continue;w={choice:O,sessions:B},I={readonly:!1,cwd:Ne.path,resumeHint:{agentId:O.agentId??Z.agentId??"",cwd:Ne.path,upstreamSessionId:""}};break}w={choice:O,sessions:B};break}let Pe={...s,readonly:!1},le=await Ib(t,n,Z,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=St;if(St=null,process.off("SIGINT",Yn),h.close().catch(()=>{}),C.kind==="new"){let{sessionId:B,...O}=s,Z={...O,cwd:C.cwd??ct,forceNew:!0,readonly:!1};C.prompt!==void 0&&(Z.initialPrompt=C.prompt),A(Z);return}if(C.kind!=="attach")return;let M={...s,sessionId:C.sessionId,cwd:I?.cwd??ct,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(!St)return;let I=(await qn(n)).filter(Pe=>Pe.status==="live");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],Z=St;St=null,process.off("SIGINT",Yn),h.close().catch(()=>{});let De={...s,sessionId:O.sessionId,cwd:ct,readonly:!1};O.agentId!==void 0&&(De.agentId=O.agentId),Z(De)},Y=async g=>{if(!St)return;let w=await qn(n,{includeNonInteractive:!0}),I=g.trim();if(!I){k.notify("usage: /session <id|next|prev>");return}let C=I.startsWith(mn)?[I]:[I,mn+I],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(Z=>C.some(De=>Z.sessionId.startsWith(De)));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=St;St=null,process.off("SIGINT",Yn),h.close().catch(()=>{});let B={...s,sessionId:A.sessionId,cwd:A.cwd??ct,readonly:A.status!=="live"};A.agentId!==void 0&&(B.agentId=A.agentId),delete B.resumeHint,M(B)},oe=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?cr(g.text,g.attachments,g.displayText):kn(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?kn(g.text,g.attachments,g.displayText):cr(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=ti(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=ti(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&&Wt){let w=Ke.size===0,I=Ie.state().buffer.every(C=>C==="");w&&I&&(dn={text:Wt.text,attachments:Wt.attachments})}Wt?Wt.cancel():L>0&&wo(),or();return}case"exit":Is();return;case"plan-toggle":As(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":Zr();return;case"toggle-questions":vn();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":xs();return;case"escalate-search":k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Fe(g.source);return}},fe=async g=>{if(!zr){k.notify("agent does not accept image attachments");return}let w=0;for(let I of g){if(I.startsWith("data:")){let A=sf(I);if(!A){k.notify("unsupported data: URI");continue}if(A.sizeBytes>Kn){k.notify(`image too large (${wn(A.sizeBytes)}, max ${wn(Kn)})`);continue}Ie.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=fa(I);if(!C){k.notify(`unsupported image type: ${qr.basename(I)}`);continue}try{let A=await Tf.readFile(I);if(A.length>Kn){k.notify(`image too large (${wn(A.length)}, max ${wn(Kn)})`);continue}Ie.addAttachment({mimeType:C,data:A.toString("base64"),name:qr.basename(I),sizeBytes:A.length}),w++}catch(A){k.notify(`cannot read ${qr.basename(I)}: ${A.message}`)}}w>0&&(k.setAttachments(Ie.state().attachments),k.refreshPrompt())},Fe=async(g="clipboard")=>{let w=g==="primary"?await $w():await _w();if(!w.ok){k.notify(w.reason);return}if(w.kind==="image"){if(!zr){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()},Nt=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Pt=(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}},Ke=new Map,ut=[],ln=new Map,yt=new Set,je=null,Sn=()=>{let g=[...Ke.values()],w=g.map(Nt);k.setQueuedPrompts(w),k.setBanner({queued:g.length}),Ie.setQueue(g.map(I=>I.text))},ti=g=>[...Ke.values()][g]?.messageId;if(vs&&vs.length>0){for(let g of vs){if(g.position===0){Q=g.messageId;continue}Ke.set(g.messageId,Pt(g.messageId,g.prompt))}Ke.size>0&&Sn()}let kn=(g,w,I)=>{k.scrollToBottom(),!xa(g)&&($t(g,I),So(g,w,I))},cr=(g,w,I)=>{if(k.scrollToBottom(),xa(g))return;if($t(g,I),!fo||Q===void 0){So(g,w,I);return}let C=Q,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};ut.push(M);let B=()=>{let O=ut.indexOf(M);O>=0&&ut.splice(O,1),M.messageId!==void 0&&ln.delete(M.messageId)};m.request("hydra-acp/prompt/amend",{sessionId:ke,targetMessageId:C,prompt:A}).then(O=>{let Z=O;if(Z.amended&&Z.reason==="ok"){Le(1);return}if(B(),Z.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(Z.reason==="target_cancelled"){k.notify("amend skipped \u2014 previous turn was cancelled"),Ie.setBuffer(g,w),k.refreshPrompt();return}if(Z.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()})},As=async g=>{if(Vn.length===0){k.notify("no modes advertised by agent");return}let w=k.currentModeId(),I=Vn.findIndex(M=>M.id===w),C=I===-1?0:(I+1)%Vn.length,A=Vn[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}`)}}},xa=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
190
- `))return!1;let I=w.indexOf(" ");switch(I===-1?w:w.slice(0,I)){case"/quit":case"/exit":return Is(),!0;case"/clear":return ft.clear(),In.clear(),it.length=0,E=null,U=null,re=null,es.clear(),ts.clear(),ns.clear(),ur.clear(),$n.clear(),Rs.clear(),k.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of nr)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=zt();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 Z=O.value===M.currentValue?"* ":" ";B.push({prefix:" ",body:`${Z}${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):(Y(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 $t(w,w),So(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&&(Wn(n,j).catch(()=>{}),j=null),K=!1,k.openBtwOverlay(),k.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new mc({getMaxWidth:()=>{let le=k.width();return le>0?le:void 0}});O.on("changed",()=>{k.setBtwOverlayContent(O.getLines())});let Z={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let De=le=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:le}})},Pe={};return B!==null&&(Pe.reuseSessionId=B),kw(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 Ne=Un(ue.update);if(Ne&&Ne.kind==="usage-update"){let hr=!1;Ne.used!==void 0&&Z.used!==Ne.used&&(Z.used=Ne.used,hr=!0),Ne.size!==void 0&&Z.size!==Ne.size&&(Z.size=Ne.size,hr=!0),Ne.costAmount!==void 0&&Z.costAmount!==Ne.costAmount&&(Z.costAmount=Ne.costAmount,hr=!0),Ne.costCurrency!==void 0&&Z.costCurrency!==Ne.costCurrency&&(Z.costCurrency=Ne.costCurrency,hr=!0),hr&&k.setBtwOverlayMeta({usage:{...Z}})}}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"}),De(`btw errored: ${ue.error.message}`),j!==null&&Wn(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"}),De(`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(),Z=new Date().toISOString().replace(/[:.]/g,"-"),De=`hydra-${nt(M)}-${Z}.md`,Pe=A.length>0?Xe(A):De,le=qr.resolve(Pe);await Tf.mkdir(qr.dirname(le),{recursive:!0}),await Tf.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}},So=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};ut.push(A),Tt=!1;let M=!1,B=null,O=Pe=>{typeof V<"u"&&V!==null&&V.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},Z=!1;Wt={text:g,attachments:w,cancel:()=>{if(Tt){Tt=!1,Z=!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(()=>{Wt!==null&&(ws>=Pe||(Tt=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},sn)}};let De;try{let Pe=await m.request("session/prompt",{sessionId:ke,prompt:C});Pe&&typeof Pe.stopReason=="string"&&(De=Pe.stopReason)}catch(Pe){let le=ut.indexOf(A);le>=0&&ut.splice(le,1),A.messageId!==void 0&&ln.delete(A.messageId),Z?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(Wt=null,B!==null&&(clearTimeout(B),B=null),Le(-1),A.flushed&&je===A){let Pe=A.messageId!==void 0&&yt.has(A.messageId);Pe&&A.messageId!==void 0&&yt.delete(A.messageId);let le={kind:"turn-complete"};De!==void 0&&(le.stopReason=De),Pe&&(le.amended=!0),x(le),je=null}if(dn!==null){let{text:Pe,attachments:le}=dn;dn=null,Ie.state().buffer.every(Ne=>Ne==="")&&(Ie.setBuffer(Pe,le),k.refreshPrompt())}}},ft=new Map,es=new Map,ts=new Map,In=new Map,it=[],lr=0,xn=`tools:${lr}`,ns=new Map,ur=new Map,ni=new Set,ss=new Map,$n=new Map,Rs=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}),Qe=()=>{if(W===null)return;let g=qs(W,qe());g.length>0&&k.upsertLines("plan",[{body:""},...g])},ot="",xe=null,kt=0,Dt=()=>{if(xe===null)return;let g=k.width(),w=Ws(ot,g>0?{maxWidth:g}:void 0);w.length!==0&&k.upsertLines(xe,w)},Ff=g=>{g.length!==0&&(xe===null&&(k.ensureSeparator(),xe=`agent:${kt}`,kt+=1,ot=""),ot+=g,Dt())},un=()=>{xe=null,ot=""},Ts="",fn=null,fr=0,pr=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),Oc=()=>{if(fn===null||Ts.length===0)return;let g=Ji(Ts);g.length!==0&&k.upsertLines(fn,g)},Lc=g=>{let w=$n.get(g);if(w===void 0)return[];let I=Ji(w.text);return w.workerTaskId&&I.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),I},Ca=(g,w)=>{g.length!==0&&(fn===null&&(k.ensureSeparator("thought"),fn=`thought:${fr}`,fr+=1,Ts=""),Ts+=g,$n.set(fn,{text:Ts,workerTaskId:w}),Oc())},Ee=()=>{fn=null,Ts=""},rs=g=>K0({...g,collapsedLimit:se}),Es=g=>ur.get(g)??i.toolsExpanded,Ht=()=>{if(E===null)return;let{lines:g,rowOwners:w}=rs({order:it,states:ft,startedAt:E,endedAt:U,stopReason:re,expanded:Es(xn),perToolExpanded:ni});k.upsertLines(xn,g),ss.set(xn,w)},Aa=g=>{let w=ns.get(g);if(!w)return;let{lines:I,rowOwners:C}=rs({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:Es(g),perToolExpanded:ni});k.upsertLines(g,I),ss.set(g,C)},Lb=()=>{E!==null&&!ns.has(xn)&&Ht();for(let g of ns.keys())Aa(g)},Bc=()=>{E!==null&&ns.set(xn,{order:[...it],states:new Map(ft),startedAt:E,endedAt:U??Date.now(),stopReason:re,rowOwners:ss.get(xn)??[]})},Of=()=>{lr+=1,xn=`tools:${lr}`,E=Date.now(),U=null,re=null,Ht()};function Bb(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:at(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 Lf=(g,w)=>{let I=w.map(M=>"text"in M?M.text:"").join(`
191
- `);if(I.length===0)return;let{text:C,truncated:A}=jg(I);g.resultText=C,g.resultTruncated=A},Ra=new Set,Nb=(g,w)=>{!w.some(C=>"hash"in C)||Ra.has(g)||(Ra.add(g),(async()=>{let C=await Promise.all(w.map(async M=>"text"in M?M:{text:await Nc(M.hash)??""}));Ra.delete(g);let A=ft.get(g);if(!A)for(let M of ns.values()){let B=M.states.get(g);if(B){A=B;break}}if(A){Lf(A,C),ft.has(g)&&Ht();for(let[M,B]of ns)B.states.has(g)&&Aa(M);k.repaintNow()}})().catch(()=>{Ra.delete(g)}))},Bf=(g,w,I,C,A,M,B,O,Z,De)=>{let Pe=!ft.has(g),le=ft.get(g),ue=le??{initialTitle:w??"tool",latestTitle:w??"tool",status:I??"pending",startedAt:Date.now()};if(!le&&Z!==void 0&&(ue.workerTaskId=Z),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&&Mu(ue.status)&&(ue.endedAt=Date.now()),C!==void 0&&(ue.errorText=C),A!==void 0&&(ue.editDiff=A),De!==void 0){let Ne=Bb(De);Ne!==null&&(Lf(ue,Ne),Ne.some(hr=>"hash"in hr)&&Nb(g,Ne))}ft.set(g,ue),Pe&&(E===null&&(lr+=1,xn=`tools:${lr}`,E=Date.now(),U=null,re=null),it.push(g))},Nc=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}},Ta=new Set,Db=(g,w)=>{Ta.has(g)||w.oldRef===void 0&&w.newRef===void 0||(Ta.add(g),(async()=>{let[I,C]=await Promise.all([w.oldRef?Nc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Nc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&I===null||w.newRef!==void 0&&C===null){Ta.delete(g);let De=Eu(w,"diff",{deferredStatus:"error"});De.length>0&&(k.upsertLines(`editdiff:${g}`,De),k.repaintNow());return}let M={...w.path!==void 0?{path:w.path}:{},oldText:I??"",newText:C??""};es.set(g,M);let B=ft.get(g);B?.editDiff&&(B.editDiff=M),Ta.delete(g);let O=ts.get(g),Z=O===void 0?i.showFileUpdates:O?"diff":"edit";Z!=="none"&&(Ea(g,M,Z==="diff"?"diff":"edit"),k.repaintNow())})())},Ea=(g,w,I)=>{let C=`editdiff:${g}`,A=Eu(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)},Hb=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),I=es.get(w);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&Db(w,I)},Nf=g=>{let w=`editdiff:${g}`,I=i.showFileUpdates,C=ft.get(g),A;if(I==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let B=ts.get(g);A=B!==void 0?B?"diff":"edit":I==="diff"?"diff":"edit"}if(A===null){k.removeKey(w);return}let M=C.editDiff;es.set(g,M),Ea(g,M,A)},Ub=()=>{let g=i.showFileUpdates;for(let[w,I]of es){let C=`editdiff:${w}`,A=ts.get(w),M=A===void 0?g:A?"diff":"edit";if(M==="none"){k.removeKey(C);continue}Ea(w,I,M==="diff"?"diff":"edit")}},jb=g=>{if(!g.path)return null;let w=at(g.oldText).split(`
192
- `),I=at(g.newText).split(`
193
- `),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=qr.isAbsolute(g.path)?g.path:qr.resolve(ct,g.path),O;try{O=M0(B,"utf8")}catch{return null}let Z=O.split(`
194
- `);for(let De=0;De<Z.length;De++)if(Z[De]===M)return De+1;return null},qb=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=es.get(I),M=ft.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=jb(C));let Z=O===null?"":`:${O}`;return k.tryOpenPathString(B+Z)}if(g.startsWith("tools:")){if(w===0)return!1;let I=ss.get(g),C=I?I[w]:void 0;if(!C)return!1;let A=ft.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},Wb=(g,w)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=es.get(I);if(!C)return;let A=ts.get(I)??i.showFileUpdates==="diff";ts.set(I,!A),Ea(I,C,A?"edit":"diff"),k.repaintNow();return}if(g==="plan"){if(W===null)return;te=!(te??i.planExpanded),Qe(),k.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=ur.get(g)??i.toolsExpanded;ur.set(g,!A),g===xn&&E!==null?Ht():Aa(g),k.repaintNow();return}let I=ss.get(g);if(!I)return;let C=I[w];if(!C)return;z0(C,ni),Aa(g),k.repaintNow();return}if(g.startsWith("thought:")){if(!$n.has(g))return;let I=Rs.get(g);if(I!==void 0){Rs.delete(g),k.setRunCollapsed(I,!1,Lc(g)),k.repaintNow();return}let C=k.contiguousRun(g,new Set($n.keys()));if(C.length===0)return;let A=C[0];Rs.set(A,C),k.setRunCollapsed(C,!0,[pr()]),k.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){Ue=g.commands,go();return}if(g.kind==="available-modes"){Vn=g.modes;return}if(g.kind==="config-options"){mo=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==tt&&(tt=C.currentValue,k.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(Vn=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!==tt&&(tt=g.agentId,k.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Lt.used!==g.used&&(Lt.used=g.used,C=!0),g.size!==void 0&&Lt.size!==g.size&&(Lt.size=g.size,C=!0),g.costAmount!==void 0&&Lt.costAmount!==g.costAmount&&(Lt.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Lt.costCurrency!==g.costCurrency&&(Lt.costCurrency=g.costCurrency,C=!0),C&&k.setSessionbar({usage:{...Lt}});return}if(g.kind==="user-text"){tr&&$t(g.text),un(),Ee(),E!==null&&(U=Date.now(),Ht()),je=null,k.ensureSeparator();let C=qs(g);C.length>0&&k.appendLines(C),Bc(),k.clearKey("plan"),W=null,te=null,ft.clear(),In.clear(),it.length=0,U=null,Of(),k.redraw();return}if(g.kind==="agent-text"){Ee(),xe===null&&$(g.workerTaskId),Ff(g.text);return}if(g.kind==="agent-thought"){un(),fn===null&&$(g.workerTaskId),Ca(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){un(),Ee();let C=In.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(In.set(g.toolCallId,A),A.plan.length===0)return;let M=Vg(A);M.length>0&&k.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){un(),Ee(),ft.has(g.toolCallId)||$(g.workerTaskId),Bf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),Ht(),Nf(g.toolCallId);return}if(g.kind==="plan"){un(),Ee(),W=g;let C=qs(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"){un(),Ee(),Bf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(gs=!0),Ht(),Nf(g.toolCallId);return}g.kind==="model-changed"&&k.setSessionbar({model:g.model});let I=qs(g);if(I.length>0&&k.appendLines(I),g.kind==="turn-complete"){Q=void 0,un(),Ee();let C=g.amended?"amended":g.stopReason;if(!g.amended&&gs&&(C===void 0||C==="end_turn")&&(C="error"),W!==null&&C!==void 0&&C!=="end_turn"){let A=qs({...W,stopped:!0,amended:g.amended===!0},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,Ht(),Bc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),ft.clear(),In.clear(),it.length=0,E=null,U=null,re=null,gs=!1,k.ensureSeparator(),mb({pendingTurns:L,queueSize:Ke.size,ownTurnInFlight:Wt!==null,hasInFlightHead:Q!==void 0,replayDraining:S,amended:g.amended===!0})&&Le(-L)}};let Df=y;y=[];let Pa=[];for(let{event:g}of Df)g.kind==="user-text"&&typeof g.text=="string"&&Pa.push(g.text);k.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of Df)b(g,w)}finally{S=!1,k.resumeRepaint()}if(Pa.length>0){let g=Vl(vt,Pa);g!==vt&&(vt=g,me=Vl(me,Pa),Ie.setHistory(ad(an,me)),Cr(Ss,vt).catch(()=>{}))}tr=!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)"),!er||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"),Xs()):w.forkSynthesisState==="failed"&&(k.setSynthesisIndicator("\u26A0 synthesis failed"),k.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),bn!==void 0&&L>0?(be=bn,k.setBanner({status:"busy",elapsedMs:Date.now()-bn}),G===null&&(G=Gs()),E===null&&Of(),E=bn,Ht()):bn===void 0&&L>0&&Le(-L);let zb=()=>{if(Te){let g=Te.resolve;Te=null,k.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}un(),Ee()},Hf=()=>{E!==null&&(U=Date.now(),re="reconnect-recovery-failed",Ht(),Bc(),ft.clear(),In.clear(),it.length=0,E=null,U=null,re=null)};return p=g=>{nn({src:"reconnect",step:"disconnect",message:g?.message}),k.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{nn({src:"reconnect",step:"begin",sessionId:ke}),zb();let g={jsonrpc:"2.0",id:`tui-reinit-${wb()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}}};nn({src:"reconnect",step:"initialize-send"});try{await h.request(g),nn({src:"reconnect",step:"initialize-ok"})}catch(O){nn({src:"reconnect",step:"initialize-fail",message:O.message})}let w=Jn!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${wb()}`,method:"session/attach",params:{sessionId:ke,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Jn}:{},clientInfo:{name:"hydra-acp-tui",version:pe},...(()=>{let O={};return Mn!==void 0&&(O.resume={upstreamSessionId:Mn,agentId:tt,cwd:ct}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[Ct]:O}}:{}})()}};ye=[];let C,A,M;nn({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:Jn});try{let O=await h.request(I);if(nn({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);M=hb(O.result),C=M.appliedPolicy,M.clientId!==void 0&&(on=M.clientId)}catch(O){A=O,nn({src:"reconnect",step:"attach-fail",message:A.message})}let B=ye??[];if(ye=null,A)Hf(),k.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")Hf(),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)st(O)}finally{S=!1}}if(M){let O=gb({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}),G===null&&(G=Gs())):k.setBanner({status:"ready",elapsedMs:void 0})}else k.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});nn({src:"reconnect",step:"end"})},m.onClose(g=>{g&&t.red(`
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(`
232
+ uncaught: ${t(e)}
233
+ `),process.exit(1)}),process.on("unhandledRejection",e=>{st({src:"unhandledRejection",stack:t(e)}),jr(),process.stderr.write(`
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(`
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(`
195
246
  connection lost: ${g.message}
196
- `),R(g?1:0)}),process.on("SIGINT",Yn),s.initialPrompt&&a.sessionId==="__new__"&&kn(s.initialPrompt,[]),await _c}async function V0(t,e,n,s,r){let i=s.cwd??process.cwd();if(s.sessionId){let o={sessionId:s.sessionId,agentId:s.agentId??"",cwd:i};return s.resumeHint!==void 0&&(o.resumeHint=s.resumeHint),o}if(s.forceNew)return await Sb(t,n,s)!=="ok"?null:vb(s,i,e);if(s.resume){let o=await qn(n,{cwd:i,all:!0}),a=zd(o,i);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}:(t.yellow(`No sessions found for ${i}.
197
- `),null)}for(;;){let o=await qn(n,{includeNonInteractive:!0}),a=await Af(t,{cwd:i,sessions:o,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt),a.cwd!==void 0&&(i=a.cwd,s.cwd=a.cwd);let l=await Sb(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return vb(s,i,e)}if(a.kind==="fork"){let l=await Cb(t,n,a,o);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let c=o.find(l=>l.sessionId===a.sessionId);if(c!==void 0&&!!c.importedFromMachine&&!c.upstreamSessionId&&!s.readonly){let l=await Ib(t,n,c,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&c&&!c.importedFromMachine&&!s.readonly&&!(await ua(c.cwd)).ok){let u=await jr(t,c,{defaultCwd:Xe(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(u.kind==="cancel")return null;if(u.kind==="back")continue;let f=a.agentId??c.agentId??"";return{sessionId:a.sessionId,agentId:f,cwd:u.path,resumeHint:{agentId:f,cwd:u.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Ib(t,e,n,s,r){for(;;){let i=await Zw(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 xb(t,e,s.agentId??n.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await jr(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 xb(t,e,n){if(!n)return{kind:"ok",agentId:n,changed:!1};let s;try{s=await qd(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 Rf(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 Cb(t,e,n,s){let r=s.find(u=>u.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd,a=await xb(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 jr(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 Wd(e,n.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return t.red(`
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(`
198
249
  fork failed: ${u.message}
199
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function vb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Sb(t,e,n){if(n.agentId||await Zf())return"ok";let s;try{s=await qd(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await we(),i=await Rf(t,s,r.defaultAgent);if(i.kind==="cancel")return"cancel";if(i.kind==="back")return"back";if(n.agentId=i.agentId,i.persist)try{await $a(i.agentId)}catch{}return"ok"}function Y0(t,e){nn({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function nn(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{G0(n);let s=JSON.stringify({t:new Date().toISOString(),...t});P0(n,`${s}
200
- `)}catch{}}function Q0(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(`
201
- `))}}}function G0(t){try{if(_0(t).size<Ab)return;$0(t,`${t}.0`)}catch{}}var Pf,q0,W0,Ab,Rb=J(()=>{"use strict";kr();At();Ku();Je();Gu();vr();Pr();Jo();Co();Sw();Nn();he();Xt();lc();Yu();dd();Zo();Iw();xw();ob();If();kf();ab();zu();Sf();ou();tf();wc();df();Ac();pb();yb();Bs();Vi();Pf="dismiss";q0=12e4;W0=[["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 live 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"]];Ab=5*1024*1024});var Tb={};Uf(Tb,{runTui:()=>kb});var Eb=J(()=>{"use strict";Rb()});import{readFileSync as X0}from"fs";import{fileURLToPath as Z0}from"url";import{dirname as eT,resolve as tT}from"path";var jf=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"]),Jb=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function qf(t){for(let e of Object.keys(t))if(!jf.has(e)&&!Jb.has(e))return e}function Dc(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(jf.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 Vb(t,e){let n=t[e];if(typeof n=="string")return n}function si(t,e){return t[e]===!0||t[e]==="true"}var Yb="HYDRA_ACP_";function Qb(t){return Yb+t.toUpperCase().replace(/-/g,"_")}function pt(t,e){let n=Vb(t,e);return n!==void 0?n:process.env[Qb(e)]}Je();vr();async function gp(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=zc(n);return{target:await hp(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await we();return{target:await Ut(s),sessionId:n,fromUrl:!1}}function nl(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}he();Je();is();import*as yp from"fs/promises";async function wp(t){if(await yp.mkdir(_.home(),{recursive:!0}),await _a(),!await oi()){let n=ii();await ai(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 _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()}
202
252
  Service token: ${n}
203
- `);return}if(si(t,"rotate-token")){let n=ii();await ai(n),process.stdout.write(`Rotated token in ${_.authToken()}
253
+ `);return}if(ii(t,"rotate-token")){let n=ai();await ci(n),process.stdout.write(`Rotated token in ${_.authToken()}
204
254
  New token: ${n}
205
255
  `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
206
256
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
207
- `)}he();ci();Je();is();import{setTimeout as Hx}from"timers/promises";import lg from"chalk";import*as rg from"fs";import*as Oi from"fs/promises";import*as ig from"net";import*as og from"tls";import Ex from"fastify";import Px from"@fastify/websocket";var bp="acp.v1";function vp(t,e){return t.has(bp)?bp:!1}Je();import sg from"pino";import Mx from"pino-roll";he();import*as xt from"fs/promises";import{createHash as Mv}from"crypto";import{gzip as _v,gunzip as $v}from"zlib";import{promisify as Sp}from"util";var kp=Sp(_v),Fv=Sp($v),Ip=/^[A-Za-z0-9_-]+$/,Ov=/^[a-f0-9]{64}$/,sl=!0;function xp(t){sl=t}function Na(t,e){return Ip.test(t)?e===void 0||Ov.test(e):!1}function Da(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function rl(t,e){if(!Na(t))return null;let n=Mv("sha256").update(e,"utf8").digest("hex"),s=Da(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await xt.access(a),n}catch{}await xt.mkdir(_.toolsDir(t),{recursive:!0});let i=sl?s:r,o=sl?await kp(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await xt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Ha(t,e){if(!Na(t,e))return null;try{let n=await xt.readFile(Da(t,e));return(await Fv(n)).toString("utf8")}catch{}try{return await xt.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Cp(t,e){if(!Na(t,e))return null;try{return await xt.readFile(Da(t,e))}catch{}try{let n=await xt.readFile(_.toolBlobFile(t,e));return await kp(n)}catch{return null}}async function Ap(t,e,n){if(!Na(t,e))return;let s=Da(t,e);try{await xt.access(s);return}catch{}await xt.mkdir(_.toolsDir(t),{recursive:!0}),await xt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Rp(t){Ip.test(t)&&await xt.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();Je();gr();import*as Np from"fs/promises";import*as ja from"path";import{z as ie}from"zod";he();import*as Ep from"fs";import*as Mt from"fs/promises";import*as Ms from"path";import{spawn as Pp}from"child_process";import{Readable as Lv}from"stream";function On(){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 al(t,e=On()){if(e)return t[e]}var li=t=>{process.stderr.write(t+`
208
- `)};function dl(t){li=t??(e=>process.stderr.write(e+`
209
- `))}async function Mp(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${On()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=On();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=Ms.resolve(n,t.target.cmd);if(await ol(s))return s;if(await Bv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await ol(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await Mt.chmod(s,493).catch(()=>{}),s}async function Bv(t){await Mt.mkdir(Ms.dirname(t.installDir),{recursive:!0});let e=await Mt.mkdtemp(`${t.installDir}.partial-`);try{li(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await Nv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});li(`hydra-acp: extracting ${t.agentId}`),ui(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await Hv(n,e),await Mt.unlink(n).catch(()=>{});try{await Mt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await ol(t.installDir)){await Mt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),ui(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}li(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),ui(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Mt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function ui(t,e){if(t)try{t(e)}catch{}}async function Nv(t){let e=Dv(t.url),n=Ms.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=Ep.createWriteStream(n),o=Lv.fromWeb(s.body);ui(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,ui(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,li(Tp(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),li(Tp(t.agentId,a,r,!0)),ui(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Tp(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 Dv(t){let e=new URL(t);return Ms.posix.basename(e.pathname)||"archive"}async function Hv(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await il("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await Uv("unzip")){await il("unzip",["-q",t,"-d",e]);return}await il("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function il(t,e){return new Promise((n,s)=>{let r=Pp(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 Uv(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Pp(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function ol(t){try{return await Mt.access(t),!0}catch{return!1}}he();import*as Qt from"fs/promises";import*as Ln from"path";import{spawn as jv}from"child_process";var ll=t=>{process.stderr.write(t+`
210
- `)};function ul(t){ll=t??(e=>process.stderr.write(e+`
211
- `))}async function $p(t){let e=On();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=Jv(t.packageSpec),r=Vv(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Ln.join(n,"node_modules",".bin",t.bin);if(await Sr(o))return o;if(await Sr(n)){let u=await _p(i);if(u)return u.binPath}await qv({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await _p(i);if(a)return a.binPath;let c=await Op(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 qv(t){await Qt.mkdir(Ln.dirname(t.installDir),{recursive:!0});let e=await Qt.mkdtemp(`${t.installDir}.partial-`);try{ll(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),cl(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await Kv({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Qt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Sr(t.installDir)){await Qt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),cl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}ll(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),cl(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Qt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function cl(t,e){if(t)try{t(e)}catch{}}var Wv=5,zv=25;function Kv(t){return Fp(t,0)}async function Fp(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=jv("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})
212
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<Wv)return await new Promise(r=>setTimeout(r,zv*(e+1))),Fp(t,e+1);throw n}}function Jv(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 Vv(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function Op(t,e){let n=Ln.join(t,"node_modules",e,"package.json");try{let s=await Qt.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 _p(t){let e=Ln.join(t.installDir,"node_modules",".bin"),n=Ln.join(e,t.hint);if(await Sr(n))return{binName:t.hint,binPath:n};let s=await Op(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Ln.join(e,i);if(await Sr(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=Ln.join(e,i);if(await Sr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Ln.join(e,t.basename);if(await Sr(r))return{binName:t.basename,binPath:r}}}async function Sr(t){try{return await Qt.access(t),!0}catch{return!1}}var Yv=ie.object({package:ie.string(),bin:ie.string().optional(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),fi=ie.object({archive:ie.string().url().optional(),cmd:ie.string().optional(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),Qv=ie.object({"darwin-aarch64":fi.optional(),"darwin-x86_64":fi.optional(),"linux-aarch64":fi.optional(),"linux-x86_64":fi.optional(),"windows-x86_64":fi.optional(),"windows-aarch64":fi.optional()}),Gv=ie.object({package:ie.string(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),Xv=ie.object({command:ie.string(),args:ie.array(ie.string()).optional(),env:ie.record(ie.string()).optional()}),Zv=ie.object({command:ie.string().optional(),url:ie.string().optional(),description:ie.string().optional()}),eS=ie.object({npx:Yv.optional(),binary:Qv.optional(),uvx:Gv.optional(),exec:Xv.optional()}),tS=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:eS,onboarding:Zv.optional(),requiredEnv:ie.array(ie.string().min(1)).optional()}),Lp=ie.object({version:ie.string(),agents:ie.array(tS),extensions:ie.array(ie.unknown()).optional()}),Ua=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(o=>o.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>fl(o)===e);return i?this.applyOverride(i):void 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:Xe(n.command??e),args:n.args?.map(Xe),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:nS(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=Lp.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 pn(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=Lp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Yt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function nS(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 fl(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 pi(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 pl(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function pl(t){let e=On();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=al(t.distribution.binary,e);if(s?.cmd){let r=ja.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await Bp(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??fl(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=ja.join(i,"node_modules",".bin",r);if(await Bp(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function Bp(t){try{return await Np.access(t),!0}catch{return!1}}async function hn(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??fl(t)??r.package,a=n.onInstallProgress;return{command:await $p({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=al(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${On()??"this platform"}.`);let i=n.onInstallProgress,o=await Mp({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 aS}from"child_process";import*as Ya from"fs";import*as eh from"path";At();function Va(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();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(`
213
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(`
214
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)+`
215
- `;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()}}}kr();he();var dS=4096,$s=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??dS,this.killEscalationMs=e.killEscalationMs??cS,this.logger=e.logger,this.fileLog=lS(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()} ---
216
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=Va(n.stdout,n.stdin);this.connection=new jt(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()}}}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()} ---
217
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()} ---
218
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}
219
- stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=aS(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=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()} ---
220
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()} ---
221
- `),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)})}},cS=2e3;function lS(t){try{let e=_.agentLogFile(t);Ya.mkdirSync(eh.dirname(e),{recursive:!0});let n=Ya.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Rr from"fs/promises";import*as ud from"os";import*as qo from"path";import{customAlphabet as bk}from"nanoid";wl();Nn();Nl();he();gr();import*as ds from"fs/promises";import{z as Dn}from"zod";var sk=Dn.object({version:Dn.literal(1),agentId:Dn.string(),upstreamSessionId:Dn.string(),deletedAt:Dn.string(),upstreamUpdatedAt:Dn.string().optional(),cwd:Dn.string().optional(),title:Dn.string().optional(),reason:Dn.enum(["user","expired"]).optional(),interactive:Dn.boolean().optional()}),nd=class{async add(e){let n={version:1,...e};await Yt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await ds.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await pn(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 sk.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await ds.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await ds.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 ds.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 ds.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 Th(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as Uh from"fs/promises";At();Xt();ed();Za();var ok=12e4;async function Ph(t,e,n){let s=t.timeoutMs??ok,r,i,o=!1;try{let a=(async()=>{r=$s.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=dk(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=ak(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 rd(t){let e=bi(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)})}},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}
222
272
 
223
273
  ${e}
224
274
 
225
- ${Pl}`:`${n}
275
+ ${Ll}`:`${n}
226
276
 
227
- ${Pl}`;return Ph(t,s,Ch)}async function Mh(t){let e=bi(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
+ ${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}
228
278
 
229
279
  ${e}
230
280
 
231
- ${Ml}`:`${n}
281
+ ${Bl}`:`${n}
232
282
 
233
- ${Ml}`;return Ph(t,s,Ah)}function ak(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 dk(t){let e=new Set;Eh(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Eh(e,n.availableModels),e}function Eh(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)}}}Ul();he();var ck=2,id=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??ck}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 hn(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 Uh.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,b,v=Date.now();await this.opts.onCompactionStateChange?.(e,{status:"requested",requestedAt:v}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"started",requestedAt:v});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 Mh({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:v,iter:p,worker:{upstreamSessionId:$,pid:F??0}})},onFailure:$=>{b=$}});if(x){let $=Nh(x.synopsis,S);$&&Dh($)&&(await this.opts.persistSynopsis(e,$,S.length),m=$,y=S.length,b=void 0,await this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,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=${Hh($)}`))}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}: ${b??"no reason captured"}`);let S=b??(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:v,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:v,iter:p,lastError:x}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:x})}}else{let f=await rd({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=Nh(f.synopsis,r);p&&Dh(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=${Hh(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 Nh(t,e){let n=Oh(e),s=Fh(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 Dh(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 Hh(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 jh(t){return t==="summary"?"summary":"inline"}var jl=256;function qh(t,e){return e!=="summary"?t:t.map(lk)}function lk(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(Wh));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 uk(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Wh(t){if(uk(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=Wh(e.content)),n}function ql(t){if(typeof t=="string"&&t.length>jl){let e=t.length-jl;return`${t.slice(0,jl)}\u2026[+${e} chars omitted from summary export]`}return t}var fk=2048;function zh(t){let e=new Set,n=s=>{if(Kh(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 Kh(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function pk(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 Kl(t,e){if(!pk(t))return t;let n=t.params,s=n.update,r=await Wl(s,e);return{...t,params:{...n,update:r}}}async function Wl(t,e){if(typeof t=="string"){if(t.length<=fk)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 Wl(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Wl(r,e);return n}return t}async function Jh(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await zl(n,e);return s===n?t:{...t,params:s}}async function zl(t,e){if(Kh(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await zl(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 zl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Lo=/^[A-Za-z0-9_-]+$/,hk=1e3,od=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??hk}async append(e,n){if(Lo.test(e))return this.enqueue(e,async()=>{await _t.mkdir(_.sessionDir(e),{recursive:!0});let s=await Kl(n,i=>rl(e,i)),r=JSON.stringify(s)+`
234
- `;await _t.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Lo.test(e))return this.enqueue(e,async()=>{await _t.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Kl(i,o=>rl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
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(`
235
285
  `)+`
236
- `;await _t.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Lo.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(`
237
- `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await _t.writeFile(_.historyFile(e),i.join(`
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(`
238
288
  `)+`
239
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Lo.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(`
240
- `)){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 Ha(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await Jh(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Lo.test(e))return this.enqueue(e,async()=>{try{await _t.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Rp(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();Je();dd();Ar();Xa();At();At();Xt();Cl();var Qh=900*1e3,Gh=5e3,Xh=3,vk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cd=bk(vk,16),ld=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>$s.spawn(a)),this.store=s??new td,this.tombstones=r.tombstones??new nd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new od({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 id({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>Xh){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)},Gh).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>Xh){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)},Gh).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 pi(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.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 r={...n.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${cd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}n.agentCapabilities=r}let s=new ki({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:r.mcpServers??[]}),loadExistingAgentSession:(r,i)=>this.bootstrapAgentLoad(r,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.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(s.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(s.sessionId),getCompactionState:()=>this.getCompactionState(s.sessionId),uncompactHook:()=>this.performUncompact(s.sessionId),onCompactionSwapHook:r=>{this.mutateRecord(s.sessionId,{rollbackBreadcrumb:r}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(s.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(s),s}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 hn(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:hi,clientInfo:{name:"hydra",version:pe}});o=m.agentCapabilities,i.authMethods=Uo(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Fs(m,i)}let a;try{let m=Zh(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(()=>{}),Fs(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
241
- `),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=Zl(a??{}),d=e.agentModes??Ql(Xl(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 mi({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=Yl(a??{}),f=Ql(Gl(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 gi({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 ki({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 mi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await gi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new ki({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 Rr.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:Xe(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 hn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:ud.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:hi,clientInfo:{name:"hydra",version:pe}})}catch(p){throw await r.kill().catch(()=>{}),Fs(p,r)}if(r.authMethods=Uo(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(Sk(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Th(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=`${mn}${cd()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:Fo(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let x=Bl(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 hn(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:hi,clientInfo:{name:"hydra",version:pe}}),o=i.agentCapabilities;r.authMethods=Uo(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=Yl(a),l=Gl(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=wi(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Xl(a),p=Zl(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(()=>{}),Fs(i,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 hn(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:hi,clientInfo:{name:"hydra",version:pe}}),a=o.agentCapabilities;i.authMethods=Uo(o.authMethods);let c=Zh(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=Yl(d),u=Ql(Gl(d)),f=Xl(d),p=Zl(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(()=>{}),Fs(o,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 hn(r,[],{npmRegistry:this.npmRegistry}),o=n??Xe(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:hi,clientInfo:{name:"hydra",version:pe}});a.authMethods=Uo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Fs(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 hn(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=Ai({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:tm(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=kk(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Ha(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:Ik(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=vi(r.update.prompt),o=El(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(mn))return;let n=mn+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:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await jo(n.sessionId),c=Ai({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:"live",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await jo(s.sessionId),i=Ai(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>jo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Ai({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:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>jo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Ai(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=Fo(),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 em(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of zh(o)){let l=await Cp(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=`${mn}${cd()}`;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=Tl(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=Ck(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 em(e),m=d==="synthesis",y={...s,lineageId:Fo(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},...m?{summarizedThroughEntry:o.length}:{},...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},b=Ho({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:pe,machine:ud.hostname()}),v=`${mn}${cd()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await hn(f,[],{npmRegistry:this.npmRegistry}),x=await rd({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(v,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Ap(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Rr.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Cr(_.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await jo(e),i=Ai(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 uh(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<Qh),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${Qh/1e3}s)`),await Mo(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 Mo(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 Sk(t,e){if(typeof t!="string"||t.length===0)return!1;let n=qo.resolve(t),s=qo.resolve(e);return n===s||n.startsWith(s+qo.sep)}function kk(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return Bl({sessionId:t.sessionId,lineageId:e?.lineageId??Fo(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:tm(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function tm(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ik(t){return t?{...t}:void 0}function Zh(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function fd(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=xk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Yl(t){return fd(t,{nestedKey:"models",configId:"model",fromObject:e=>Hn(e.currentModelId)??Hn(e.currentModel)??Hn(e.modelId)??Hn(e.model),fromConfig:e=>Hn(e.currentValue)})}function Fs(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 Uo(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 Hn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function xk(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function Ql(t){return t.length>0?t:void 0}function Gl(t){return fd(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=Si(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=Si(e.options);return n.length>0?n:void 0}})??[]}function Xl(t){return fd(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 Zl(t){return fd(t,{nestedKey:"modes",configId:"mode",fromObject:e=>Hn(e.currentModeId)??Hn(e.currentMode)??Hn(e.modeId)??Hn(e.mode),fromConfig:e=>Hn(e.currentValue)})}function Ck(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 em(t){try{let e=await Rr.readFile(_.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
242
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function jo(t){try{let e=await Rr.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ai(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===xr?!1:e?!0:void 0}import{spawn as Ak}from"child_process";import*as Ti from"fs";import*as Os from"fs/promises";import*as nm from"path";var pd=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_}};Je();var Rk=1e3,Tk=6e4,eu=3e3,Ri=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??Rk,this.restartCapMs=r.restartCapMs??Tk;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 Os.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()},eu);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 Wo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Wo(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 Wo(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 Wo(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 Wo(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{}},eu);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 pd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Os.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=nm.join(this.adapter.paths.dir(),n),r;try{let i=await Os.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&tu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+eu;for(;Date.now()<i&&tu(r);)await new Promise(o=>setTimeout(o,50));if(tu(r))try{process.kill(r,"SIGKILL")}catch{}}await Os.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=Ti.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(!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})
243
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
244
- `),o.end();return}let u=Xe(d),f=[...l,...r.args].map(Xe),p;try{p=Ak(u,f,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){o.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
245
- `),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{Ti.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
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}
246
297
  `,{encoding:"utf8",mode:384})}catch(h){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
247
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}
248
- `)}),p.on("exit",(h,m)=>{try{Ti.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${m??"null"}
249
- `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let y=e.exitWaiters.splice(0);for(let v of y)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof b=="object"){e.failureReason=b.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${b.tripped}
250
- `);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 tu(t){try{return process.kill(t,0),!0}catch{return!1}}function Wo(t,e){return t.code=e,t}he();var Ek={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},hd=class extends Ri{constructor(e,n,s={}){super(e,Ek,n,s)}};he();var Pk={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},md=class extends Ri{connected=new Map;constructor(e,n,s={}){super(e,Pk,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 gd=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();ci();he();import*as Ko from"fs/promises";import*as yd from"path";var zo=t=>{process.stderr.write(t+`
251
- `)};function nu(t){zo=t??(e=>process.stderr.write(e+`
252
- `))}async function sm(t,e){let n=On();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=yd.join(_.agentsDir(),n),a;try{a=await Ko.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;zo(`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=yd.join(o,d),p;try{p=await Ko.readdir(f,{withFileTypes:!0})}catch(h){zo(`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=yd.join(f,m);try{await Ko.rm(y,{recursive:!0,force:!0}),zo(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){zo(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function rm(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 pl(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 su(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 ${Mk(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 im(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await su({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 Mk(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`}Xt();Jo();he();gr();import*as dm from"path";import{createHash as $k,randomBytes as Fk,timingSafeEqual as Ok}from"crypto";var cm="hydra_session_",Lk=3600*24*30,om=12,Bk=32,Nk=50;function Dk(){return dm.join(_.home(),"session-tokens.json")}function am(t){return $k("sha256").update(t).digest("hex")}function lm(t){return Fk(t).toString("hex")}function Hk(){return lm(om).slice(0,om*2)}function Uk(){return`${cm}${lm(Bk)}`}var wd=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=Dk(),s=await pn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(jk));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=Uk(),s=am(n),r=Hk(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Lk,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=am(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||!Ok(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(()=>{})},Nk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Yt(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 jk(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")}is();var um="Bearer ",bd=class{constructor(e){this.token=e}token;async validate(e){return qk(e,this.token)?"service":void 0}},vd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Sd=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 fm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(um)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(um.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function pm(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 kd=class{tokens=new Map;mint(e,n){let s=ii();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 qk(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 Id=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();Je();ou();Ar();Ad();import*as lu from"fs";import*as Qo from"os";import*as _m from"path";import*as uu from"readline";Bs();Nn();function Rd(t){let e=yI(t),n=wI(e),s=[];bI(s,t),vI(s,e,n);let r=s.join(`
299
+ `)}),p.on("exit",(h,m)=>{try{Pi.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${m??"null"}
300
+ `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let y=e.exitWaiters.splice(0);for(let b of y)b();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let v=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof v=="object"){e.failureReason=v.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${v.tripped}
301
+ `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function au(t){try{return process.kill(t,0),!0}catch{return!1}}function zo(t,e){return t.code=e,t}he();var Wk={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},gd=class extends Ei{constructor(e,n,s={}){super(e,Wk,n,s)}};he();var zk={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},yd=class extends Ei{connected=new Map;constructor(e,n,s={}){super(e,zk,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var wd=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};he();ui();he();import*as Jo from"fs/promises";import*as bd from"path";var Ko=t=>{process.stderr.write(t+`
302
+ `)};function du(t){Ko=t??(e=>process.stderr.write(e+`
303
+ `))}async function bm(t,e){let n=Bn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=bd.join(_.agentsDir(),n),a;try{a=await Jo.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;Ko(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=bd.join(o,d),p;try{p=await Jo.readdir(f,{withFileTypes:!0})}catch(h){Ko(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=bd.join(f,m);try{await Jo.rm(y,{recursive:!0,force:!0}),Ko(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(v){Ko(`hydra-acp: prune: failed to remove ${y}: ${v.message}`)}}}}function vm(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let u of l.agents)await bl(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function cu(t){let e=t.maxDeletions??200,n=(p,h)=>{t.logger&&t.logger[p](`session-gc: ${h}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(t.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,n("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${Kk(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function Sm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await cu({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function Kk(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}Zt();Yo();he();yr();import*as xm from"path";import{createHash as Yk,randomBytes as Vk,timingSafeEqual as Qk}from"crypto";var Cm="hydra_session_",Gk=3600*24*30,km=12,Xk=32,Zk=50;function eI(){return xm.join(_.home(),"session-tokens.json")}function Im(t){return Yk("sha256").update(t).digest("hex")}function Am(t){return Vk(t).toString("hex")}function tI(){return Am(km).slice(0,km*2)}function nI(){return`${Cm}${Am(Xk)}`}var vd=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=eI(),s=await hn(n);s&&Array.isArray(s.records)&&(e=s.records.filter(sI));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=nI(),s=Im(n),r=tI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Gk,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Cm))return;let n=Im(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!Qk(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},Zk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Qt(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function sI(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}ds();var Rm="Bearer ",Sd=class{constructor(e){this.token=e}token;async validate(e){return rI(e,this.token)?"service":void 0}},kd=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Id=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Tm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Rm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Rm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Em(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var xd=class{tokens=new Map;mint(e,n){let s=ai();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function rI(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var Cd=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};he();Ye();fu();Rr();Td();import*as gu from"fs";import*as Go from"os";import*as Ym from"path";import*as yu from"readline";Ds();Hn();function Ed(t){let e=_I(t),n=$I(e),s=[];FI(s,t),OI(s,e,n);let r=s.join(`
253
304
  `);return r.endsWith(`
254
305
  `)||(r+=`
255
- `),r}function yI(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=Un(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function wI(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 bI(t,e){let n=e.session,s=nt(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Tr(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?`${du(a.size)}`:void 0;c.push(d?`${du(a.used)} / ${d} tokens`:`${du(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(`
256
- `)),t.push("")}function vI(t,e,n){if(!e.some(d=>SI(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(`
257
- `))t.push(`> ${Tr(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(`
258
- `);for(let u of l)t.push(`> _${Tr(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(`- ${II(l.status)} ${kI(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${Tr(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Tr(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Tr(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function SI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function kI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Tr(t.title)}${n}`}function II(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 Tr(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function du(t){return t.toLocaleString("en-US")}At();Xt();xo();Bs();function xI(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>CI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function CI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:xm(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:xm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function xm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function AI(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var RI=5,TI=200,Cm=30;async function Tm(t,e,n={}){let s=xI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??RI,i=n.maxSessions??TI,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=EI(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 EI(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=PI(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 PI(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=MI(a).filter(d=>AI(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:LI(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 MI(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=Td(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?at(s.text):Td(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(FI(s))return[];let i=Td(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=OI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return _I(s);default:return[]}}function _I(t){let e=Am(t,"name"),n=Am(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=Rm(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=Rm(i);if(a.length>0){let c={kind:"tool-input",text:Ae(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=$I(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function $I(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 FI(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 Td(t){if(typeof t=="string")return at(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?at(e.text):""}function OI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Td(n);s.length>0&&e.push(s)}return e.join("")}function Am(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Rm(t){try{return JSON.stringify(t)}catch{return""}}function LI(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-Cm),c=Math.min(s.length,o+i.length+Cm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Pm}from"crypto";function Em(t){let e=Pm(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 cu(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(Em({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Em({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Mi(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Mi(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=Pm(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 Ed=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Mm(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!yr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function $m(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 Tm(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=Xe(u.cwd??n.cwd),p=u.agentId??n.agentId,h=Mi(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 su({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=>_m.join(Qo.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),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":jh(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=Ho({record:m.record,history:h==="summary"?qh(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:pe,machine:Qo.hostname(),hydraHost:Mm(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,b=Ei(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:Pi(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=Ho({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:pe,machine:Qo.hostname(),hydraHost:Mm(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(Rd(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=Xe(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=Tn(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===z.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&n.compaction){let T=h??0,$=x.length,j=x.slice(T).reduce((D,X)=>D+JSON.stringify(X.params).length,0);v=iu(j);let K=p?.currentModel,H=x.at(-1).recordedAt,L=p?.currentUsage;b=hm({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:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,x=[];if(m){p&&(b=m.onBroadcast($=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify($)+`
259
- `):(x.push($),x.length>S&&x.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch($){throw b?.(),$}}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($)+`
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($)+`
260
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)+`
261
- `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||u!==void 0&&h.recordedAt<u||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let b=m.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=uu.createInterface({input:lu.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(!Ed.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...Ed].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),b=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of b)try{let x=_.historyFile(S.sessionId),T=await a(S.sessionId,x,h,m);T.exhausted||v.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,x=1/0;for(let $=0;$<v.length;$++){let F=v[$];F.current!==null&&F.current.ts<x&&(x=F.current.ts,S=$)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
262
- `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let x of v)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(!Ed.has($))return l.code(400).send({error:`kind "${$}" is not queryable; allowed kinds: ${[...Ed].join(", ")}`}),l;let b=new Set(y),v;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;v=$.getTime()}let S=_.historyFile(p),x=lu.createReadStream(S),T=uu.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"||!b.has(D)||v!==void 0&&K.recordedAt<v)continue;let X={ts:new Date(K.recordedAt).toISOString(),kind:D,update:L};L.messageId!==void 0&&L.messageId!==null&&(X.messageId=L.messageId),l.raw.write(JSON.stringify(X)+`
263
- `)}}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 b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let $=Array.from(b.listAttentionFlags()).map(F=>`${F.source}::${F.reason}`);for(let F of $)b.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 v=e.store,S=await v.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 v.write({...S,attentionFlags:T}),l.code(204).send()})}At();function Fm(t,e,n,s={}){t.get("/v1/agents",async()=>pi(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 hn(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 Om(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var BI=/^[A-Za-z0-9._-]+$/;function Pd(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=NI(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){Go(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){Go(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){Go(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){Go(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){Go(o,c)}})}function Go(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 NI(t){let e=t.name;if(typeof e!="string"||!BI.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 Lm(t,e){Pd(t,"extension",e)}function Bm(t,e){Pd(t,"transformer",e)}function Nm(t,e){t.get("/v1/config",async()=>e)}import{z as _i}from"zod";he();import*as Ns from"fs/promises";import*as jm from"path";import{randomBytes as DI,scrypt as HI,timingSafeEqual as UI}from"crypto";import{promisify as jI}from"util";var qm=jI(HI);function fu(){return jm.join(_.home(),"password-hash")}var Dm=32768,Hm=8,Um=1,qI=64,WI=16,Wm=128*1024*1024;async function zm(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=DI(WI),n=await qm(t,e,qI,{N:Dm,r:Hm,p:Um,maxmem:Wm}),s=`scrypt$${Dm}$${Hm}$${Um}$${e.toString("hex")}$${n.toString("hex")}
264
- `;await Ns.mkdir(_.home(),{recursive:!0}),await Ns.writeFile(fu(),s,{encoding:"utf8",mode:384})}async function Md(){try{return(await Ns.readFile(fu(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _d(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Ns.readFile(fu(),"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 qm(t,o,a.length,{N:s,r,p:i,maxmem:Wm});return c.length!==a.length?!1:UI(c,a)}var zI=_i.object({password:_i.string().min(1),label:_i.string().min(1).max(256).optional(),ttlSec:_i.number().int().positive().optional()}),KI=_i.object({id:_i.string().optional()}).optional();function Km(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=JI(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=zI.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Md())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await _d(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=KI.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 JI(t){return t.ip||"unknown"}kr();$i();import{nanoid as yu}from"nanoid";Xa();At();Xt();import{randomBytes as Vm}from"crypto";import*as Ym from"os";import*as Qm from"path";function ce(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function XI(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 Zt(t,e,n){let s=t.get(e);if(!s)throw ce(z.SessionNotFound,n??`session ${e} not found`);return s}async function pu(t,e){let n=Mi(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Vm(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=cu({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return ox(d,t),d}function Gm(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=pm({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=jn(n),a=new jt(o),c={clientId:`hydra_client_${yu(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=Dp.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)),ix()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},h=typeof p.instructions=="string"?p.instructions:void 0,m=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,h,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(h=>typeof h=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let h=e.transformers.resolveChain([i.name])[0];if(h)for(let m of e.manager.liveSessions())m.addTransformer(h)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.method=="string"?f.method:void 0,m=f.envelope,y=f.route;if(!p)throw ce(-32602,"emit_message requires sessionId");if(!h&&y!=="client_broadcast")throw ce(-32602,"emit_message requires method");let b=Zt(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,m),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,h,m)};if(y==="client_broadcast"){if(!m||typeof m!="object")throw ce(-32602,"client_broadcast requires an envelope object");return b.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 Zt(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>tx(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,h=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!h&&m){let $=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:v,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=Zt(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],$=0,F=!1,j,K,H=!1,L=()=>{H||(H=!0,clearTimeout(D),j?.(),K?.(),b(F?{entries:x,truncated:!0}:{entries:x}))};j=y.onBroadcast(X=>{let Q=XI(X);for(x.push(X),T.push(Q),$+=Q;x.length>0&&(x.length>1e3||$>1048576);)x.shift(),$-=T.shift()??0,F=!0;h==="turn_complete"&&X.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=>nx(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>sx(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=>ZI(u,e)),a.onRequest("session/new",async u=>{let f=Hp.parse(u),p=Gt(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,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Vm(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let X={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],X]}let S,x,T=Mi(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let $=cu({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:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Jm(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...$?{mintMcpServersForSwap:$}:{}})}catch(D){throw b!==void 0&&b.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&&b!==void 0&&e.mcpTokenRegistry!==void 0){let D=y,X=e.mcpTokenRegistry;b.complete(F),F.onClose(()=>{X.unbind(D)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let D=S,X=e.mcpTokenRegistry;x.complete(F),F.onClose(()=>{X.unbind(D)})}T!==void 0&&T.bindToSession(F);let j,K;try{j=$d(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=hu(F),L=mu(F);return{sessionId:F.sessionId,...H?{modes:H}:{},...L?{models:L}:{},configOptions:F.buildConfigOptions(),_meta:gu(e.manager,F,{clientId:j.clientId})}}),a.onRequest("session/attach",async u=>{let f=jp.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=Gt(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw ce(z.SessionNotFound,`session ${f.sessionId} not found`);let D=await e.manager.loadHistory(v),X=f.clientId??`cli_${yu(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:X,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${X} attachedCount=${c.attached.size} replayed=${D.length}`);for(let Q of D)await a.notify(Q.method,Q.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:X,connectedClients:[X],historyPolicy:"full",replayed:D.length,_meta:rx(L)}}let x=!S;if(!S){let L=await e.manager.loadFromDisk(v),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 X=D.originatingClient?D:{...D,originatingClient:c.clientInfo},Q=b!==void 0?{...X,forwardedEnv:b}:X;S=await pu(e,{...Q,onInstallProgress:Jm(a)})}let T=$d(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}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${j} replayed=${F.length} readonly=${y}${$?" replayMode=drip":""}`),$){let L=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,D=750;(async()=>{let X=null;for(let Q of F){let be=typeof Q.recordedAt=="number"?Q.recordedAt:null;if(X!==null&&be!==null){let G=Math.min(D,Math.max(0,(be-X)/L));G>0&&await new Promise(de=>setTimeout(de,G))}be!==null&&(X=be);try{await a.notify(Q.method,Q.params)}catch{return}}})()}else for(let L=0;L<F.length&&!a.isClosed();L++){let D=F[L],X=a.notify(D.method,D.params).catch(()=>{});(L+1)%200===0&&await X}S.replayPendingPermissions(T);let K=hu(S),H=mu(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:gu(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=qp.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:{[Ct]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Wp.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==xr).map(zp)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw ce(z.InternalError,"agent registry unavailable");return pi(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=Kp.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 pu(e,m);let y=$d(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=Ka.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=Ka.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Vp.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),Zt(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Ka.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),Zt(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Yp.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),Zt(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Qp.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 Zt(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 pu(e,x)}let y=$d(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let v=hu(m),S=mu(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:gu(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=ex(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=Zt(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>ce(z.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=Zt(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw 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),Zt(e.manager,y).forwardRequest(f,u)})})}async function ZI(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&&Qm.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 b={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(b[S]=x);Object.assign(b,h.env);let v=Ym.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Fs(p,a)}}function Jm(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(Ja,n).catch(()=>{})}}function hu(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function mu(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function ex(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=wi(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 tx(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 Zt(n.manager,r).addTransformer(i),{ok:!0}}async function nx(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 Zt(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function sx(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 Zt(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function rx(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{[Ct]:Wa(e,n)}}function gu(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 Eo(e.agentMeta,Wa(s,r))}function ix(){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:Eo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function ox(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function $d(t,e,n,s,r){return{clientId:r??`cli_${yu(8)}`,connection:t,clientInfo:s}}var Fd=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 ax}from"crypto";import{McpServer as dx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as cx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Rt}from"zod";function*wu(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 en(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var Xm="Bearer ";function Fi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(Xm))return;let n=e.slice(Xm.length).trim();return n.length>0?n:void 0}function lx(t){let e=new dx({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:Rt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return en(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:Rt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return en(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:Rt.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:Rt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Rt.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 en(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:Rt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Rt.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 en({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:Rt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Rt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Rt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Rt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Rt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Rt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Rt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Rt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Rt.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 en(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 en(n)}),e}var ux=1e4;function Zm(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=lx(a),l=new cx({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=Fi(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),ux)}),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)})}Za();import{randomUUID as fx}from"crypto";import{McpServer as px}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as hx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ds}from"zod";function mx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function gx(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 yx(t){let e=new px({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:Ds.string().min(1).describe("Case-insensitive substring to search for."),limit:Ds.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ds.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 en({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 wu(o)){if(u==="tool_call"&&!r)continue;let f=bi([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let h=mx(u),m=gx(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 en({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:Ds.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ds.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 en({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=bi(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:Ds.string().optional(),file_path:Ds.string().optional(),limit:Ds.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 en({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 wu(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))v.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];for(let p of d){let h=l.get(p);if(n!==void 0&&h.toolName.toLowerCase()!==n.toLowerCase())continue;if(a){let y=s.toLowerCase(),b=["file_path","filePath","path"],v=!1;for(let S of b){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return en({calls:u,truncated:f})}),e}var wx=1e4;function eg(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=yx(a),l=new hx({sessionIdGenerator:()=>fx()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=Fi(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),wx)}),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 Od=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 Ax}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Rx}from"crypto";import{Server as bx}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as vx,ListToolsRequestSchema as Sx}from"@modelcontextprotocol/sdk/types.js";function tg(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new bx({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(Sx,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(vx,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Ld(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=Ix(d,a.sendNotification);try{let u=await s(),f=await xx(e.connection,t,c,o.params.arguments??{},u);return Cx(f,c)}catch(u){return Ld(u instanceof Error?u.message:String(u))}finally{l()}}),r}var kx=15e3;function Ix(t,e,n=kx){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function xx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function Cx(t,e){if(t===null||typeof t!="object")return Ld(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Ld(`extension ${e} omitted content array`)}function Ld(t){return{content:[{type:"text",text:t}],isError:!0}}var Tx=1e4;function ng(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let m=tg(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),Tx)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId}),y=new Ax({sessionIdGenerator:()=>Rx()});return await m.connect(y),u.set(l,{server:m,transport:y}),y}async function a(d,l){let u=Fi(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 ag(t,e){Fx(t);let n=t.daemon.tls?await Oi.readFile(Xe(t.daemon.tls.key)):void 0,s=t.daemon.tls?await Oi.readFile(Xe(t.daemon.tls.cert)):void 0;await Oi.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await _x(t.daemon.logLevel),o=Ex({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(Px,{options:{handleProtocols:vp}}),dl(V=>{o.log.info(V)}),ul(V=>{o.log.info(V)});let a=await wd.load(),c=new Id,d=new kd,l=new Sd([new bd(e),new vd(a),d]),u=fm({validator:l});o.addHook("onRequest",async(V,Se)=>{V.routeOptions.config?.skipAuth||V.url==="/acp"||V.url?.startsWith("/acp?")||await u(V,Se)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new Ua(t,{onFetched:()=>{sm(h,v)}});nu(V=>o.log.info(V));let m={info:V=>o.log.info(V),warn:V=>o.log.warn(V)},y=V=>$s.spawn({...V,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:m});xp(t.compressToolContent);let b=new gd,v=new ld(h,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new hd(Vf(t),void 0,{tokenRegistry:d}),x=new md(Yf(t),void 0,{tokenRegistry:d});Om(o,pe,Ls(t));let T=new Fd,$=new Od,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};$m(o,v,{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}),Fm(o,h,v,{npmRegistry:t.npmRegistry}),Lm(o,S),Bm(o,x),Nm(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]}),Km(o,{store:a,rateLimiter:c}),Zm(o,T),eg(o,T),ng(o,T,$),Gm(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(V,Se)=>S.reportVersion(V,Se),onTransformerVersion:(V,Se)=>x.reportVersion(V,Se),transformers:x,extensionCommands:b,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,X=t.daemon.host,Q=L;if(K&&n&&s){D=$x({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=D.address();V&&typeof V=="object"&&(Q=V.port)}await Oi.mkdir(_.home(),{recursive:!0}),await sp({pid:process.pid,host:X,port:Q,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 v.reconcilePermissionFlags()}catch(V){o.log.warn(`permission flag reconcile failed: ${V.message}`)}v.resurrectPendingQueues().catch(V=>{o.log.warn(`queue replay scan failed: ${V.message}`)}),v.resumePendingCompactions().catch(V=>{o.log.warn(`compaction resume scan failed: ${V.message}`)});let G=t.daemon.agentSyncIntervalMinutes*60*1e3,de=G>0?rm({registry:h,manager:v,intervalMs:G,logger:m}):void 0,ze=t.daemon.sessionGcIntervalMinutes*60*1e3,Gs=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,gs=ze>0?im({manager:v,intervalMs:ze,maxAgeMs:Gs,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:$,processRegistry:d,shutdown:async()=>{gs&&gs(),de&&de(),clearInterval(f),clearInterval(p);let V=async(Se,Jn)=>{try{await Jn()}catch(ye){o.log.warn(`shutdown step ${Se} failed: ${ye instanceof Error?ye.message:String(ye)}`)}};await V("sessionTokenStore.flush",()=>a.flush()),await V("extensions.stop",()=>S.stop()),await V("transformers.stop",()=>x.stop()),await V("manager.closeAll",()=>v.closeAll()),await V("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await V("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await V("manager.flushMetaWrites",()=>v.flushMetaWrites()),await V("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),dl(null),ul(null),nu(null),D&&await V("tlsTerminator.close",()=>new Promise(Se=>D.close(()=>Se()))),await V("app.close",()=>o.close());try{rg.unlinkSync(_.pidFile())}catch{}await V("fileStream.flushSync",()=>i.flushSync())}}}async function _x(t){let e=await Mx({file:_.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=sg.destination(2);return{stream:sg.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function $x(t){let e=og.createServer(t.tlsOptions,n=>{let s=ig.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 Fx(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.`)}Pr();Xt();Jo();import*as cg from"fs";import*as Li from"fs/promises";async function Bi(t,e,n){let s=Dx(e),r;try{r=await Li.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
265
- `),process.exit(1);return}throw c}let i=await Nx(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
266
- `);let o=!1,a=cg.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Li.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Li.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 Nx(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Li.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(`
267
- `).slice(-n-1);process.stdout.write(d.join(`
268
- `)),o.endsWith(`
269
- `)||process.stdout.write(`
270
- `)}finally{await r.close()}return e}function Hd(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 Dx(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}
271
- `),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}
272
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function ug(t={}){let e=await we(),n=await ko();if(await Bd(e)){let r=await Ni();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
273
- `);return}if(si(t,"foreground")){process.title="hydra-daemon";let r=await ag(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
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}
274
317
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
275
318
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
276
319
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
277
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)}
278
- `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Nd(),await Dd(e);let s=await Ni();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
279
- `)}async function fg(){let t=await Ni();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}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.
280
323
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
281
324
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
282
- `)}}async function pg(){let t=await we();await ko();let e=await Ni();if(e&&Rn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
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}...
283
326
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
284
- `),process.exit(1)}await Ux(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
327
+ `),process.exit(1)}await nC(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
285
328
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
286
- `);if(Nd(),await Dd(t),await Bd(t)){let n=await Ni();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
287
- `)}}async function Ux(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!Rn(t))return!0;await Hx(50)}return!1}async function hg(t){await Bi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function mg(){let t=await Ni();if(!t){process.stdout.write(`Daemon: not running
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
288
331
  `),process.stdout.write(`CLI version: ${pe}
289
- `);return}let e=Rn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
290
- `);let n,s;if(e)try{let o=await we();n=await Er(o),s=Ls(o)}catch{}if(!n||n.version===void 0){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}
291
334
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
292
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}
293
336
  `);return}process.stdout.write(`CLI version: ${pe}
294
337
  `),process.stdout.write(`Daemon version: ${n.version}
295
- `),r||process.stdout.write(lg.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(lg.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function Ni(){return as()}Je();is();Us();vr();xo();Nn();Zo();Ar();import*as gn from"fs/promises";import*as Tg from"os";import*as yn from"path";Vd();async function Eg(t={}){let e=await we(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await $e(`/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(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)+`
296
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.
297
340
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
298
341
  `);return}process.stdout.write(`No active sessions.
299
- `);return}let c=a.slice().sort((y,b)=>{let v=(b.status==="live"?1:0)-(y.status==="live"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(x=>x.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(y,y+b),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>Wi(y,u)),p={columns:t.columns??e.tui.sessionColumns??ji,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=zi(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(js(qi,h,m,p)+`
300
- `);for(let y of f)process.stdout.write(js(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(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)+`
301
344
  `);l>0&&process.stdout.write(`
302
345
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
303
- `)}async function Pg(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
304
- `),process.exit(2));let e=await $e(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
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}
305
348
  `),process.exit(1)),process.stdout.write(`Killed ${t}
306
- `)}async function Mg(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
307
- `),process.exit(2));let e=await $e(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
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}
308
351
  `),process.exit(1)),process.stdout.write(`Removed ${t}
309
- `)}async function _g(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 $e("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
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)}
310
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.
311
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${Hi(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
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}.
312
355
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
313
356
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
314
- `)}async function $g(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
315
- `),process.exit(2));let s=await mr(),r=await Di(),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 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}
316
359
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
317
360
  `)||process.stdout.write(`
318
- `);return}let c=e==="."?iC(o,t):e;await gn.mkdir(yn.dirname(yn.resolve(c)),{recursive:!0}),await gn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
319
- `)}async function Fg(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
320
- `),process.exit(2));let n,s,r=await eC(t);if(r!==null){let o=tC(r.raw);n=Rd(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${yn.basename(t,yn.extname(t))}-${a}.md`}else{let o=await mr(),a=await Di(),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==="."?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}
321
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(`
322
365
  `)||process.stdout.write(`
323
- `);return}let i=e==="."?s:e;await gn.mkdir(yn.dirname(yn.resolve(i)),{recursive:!0}),await gn.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
324
- `)}async function eC(t){try{if(!(await gn.stat(t)).isFile())return null}catch{return null}let e=await gn.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
325
- `),process.exit(1)}}function tC(t){try{return Tn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
326
- `),process.exit(1)}}async function Og(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
327
- `),process.exit(2));let n;if(e.cwd!==void 0){let a=yn.resolve(e.cwd);try{(await gn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
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
328
371
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
329
- `),process.exit(1)}n=a}let s;t==="-"?s=await rC():s=await gn.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
330
- `),process.exit(1)}if(e.info===!0){let a=await we();sC(r,a.tui.cwdColumnMaxWidth);return}let i=await $e("/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 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.
331
374
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
332
375
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
333
376
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
334
- `)}function nC(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 sC(t,e){let n;try{n=Tn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
335
- `),process.exit(1)}let s=nC(n),r=Wi(s),i={columns:Jd,cwdMaxWidth:e},o=zi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(js(qi,o,a,i)+`
336
- `),process.stdout.write(js(r,o,a,i)+`
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)+`
337
380
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
338
381
  lineage: ${n.session.lineageId}
339
382
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -341,108 +384,75 @@ origin session: ${n.session.sessionId}
341
384
  origin upstream: ${c}
342
385
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
343
386
  `:`
344
- `))}async function rC(){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 iC(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 Lg(t,e={}){let n=await we(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Ut(n),l=e.cwd?yn.resolve(e.cwd):process.cwd(),u=await qn(d,{cwd:l,all:!0}),f=zd(u,l);f||(process.stderr.write(`No sessions found for ${l}.
345
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=oC(e.host,n),a=nt(s),c=ep({host:r,port:i,sessionId:a});process.stdout.write(c+`
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+`
346
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.
347
- `)}function oC(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Rg(t,An);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Rg(e.daemon.publicHost,An);return{host:n,port:s,isFallback:!1}}return aC(e.daemon.host)?{host:dC(),port:e.daemon.port,isFallback:!1}:yr(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 aC(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function dC(){let t=Tg.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Rg(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}}Bu();Vd();$u();Je();he();Us();var WC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function ec(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Yi(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function tc(t){let e=WC[t],n=`/v1/${e.plural}`;async function s(){let u=(await $e(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
348
- `);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?Hi(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:Yi(p.name,f.map(y=>y.name)),status:Yi(p.status,f.map(y=>y.status)),version:Yi(p.version,f.map(y=>y.version)),pid:Yi(p.pid,f.map(y=>y.pid)),restarts:Yi(p.restarts,f.map(y=>y.restarts)),started:Yi(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 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)+`
349
392
  `);for(let y of f)process.stdout.write(m(y)+`
350
393
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
351
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]
352
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._-]+
353
- `),process.exit(2);return}await we();let u=await Ui(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${Xg(e.singular)} '${d}' already exists in config.
354
- `),process.exit(1);return}let h=jd(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 vu(u),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
355
- `);let b={name:d,...y};try{let v=await $e(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,x=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${x}
356
- `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${ec(v.body)}). Restart the daemon to apply.
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.
357
400
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
358
- `),process.exit(2);return}await we();let l=await Ui(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${Xg(e.singular)} '${d}' not found in config.
359
- `),process.exit(1);return}delete f[d],u[e.plural]=f,await vu(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
360
- `);try{let p=await $e(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
361
- `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${ec(p.body)}).
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)}).
362
405
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
363
406
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
364
- `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await $e(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${ec(u.body)}
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)}
365
408
  `),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${d}: ${f.status}${p}
366
- `)}async function a(d){let p=((await $e(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}.
367
- `);return}let h=0;for(let m of p)try{let y=await $e(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${ec(y.body)}
368
- `),h+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${m.name}: ${b.status}${v}
409
+ `)}async function a(d){let p=((await Me(n,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
410
+ `);return}let h=0;for(let m of p)try{let y=await Me(`${n}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${nc(y.body)}
411
+ `),h+=1;continue}let v=y.body,b=v.pid!=null?` pid=${v.pid}`:"";process.stdout.write(`${m.name}: ${v.status}${b}
369
412
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
370
- `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Hd(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
371
- `),process.exit(2);return}let f=e.logFile(l);await Bi(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 Xg(t){return t.charAt(0).toUpperCase()+t.slice(1)}var _r=tc("extension"),Zg=_r.list,ey=_r.add,ty=_r.remove,ny=_r.start,sy=_r.stop,ry=_r.restart,iy=_r.logs;var $r=tc("transformer"),oy=$r.list,ay=$r.add,dy=$r.remove,cy=$r.start,ly=$r.stop,uy=$r.restart,fy=$r.logs;Je();he();Us();async function my(){let e=(await $e("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
372
- `);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:cs(s.id,n.map(a=>a.id)),name:cs(s.name,n.map(a=>a.name)),version:cs(s.version,n.map(a=>a.version)),source:cs(s.source,n.map(a=>a.source)),distributions:cs(s.distributions,n.map(a=>a.distributions)),installed:cs(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)+`
373
- `);for(let a of n)process.stdout.write(i(a)+`
374
- `);let o=e.fetchedAt!==void 0?` (synced ${Hi(e.fetchedAt)})`:"";process.stdout.write(`
375
- Registry version: ${e.version}${o}
376
- `)}async function Du(t){if((await we()).agents[t]!==void 0)return;let n;try{let s=await $e("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;n=s.body.agents.map(i=>i.id)}catch{return}n.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
377
- `),process.exit(2))}async function gy(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
378
- `),process.exit(2);return}process.stdout.write(`Installing ${t}\u2026
379
- `);let n=(await $e(`/v1/agents/${encodeURIComponent(t)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!n.installed){process.stdout.write(`${n.agentId} (${n.version}, ${n.distribution}): ${n.message??"nothing to install"}
380
- `);return}process.stdout.write(`Installed ${n.agentId} (${n.version}, ${n.distribution})
381
- `),n.command&&process.stdout.write(` \u2192 ${n.command}
382
- `)}async function yy(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
383
- `),process.exit(2);return}let n=(await $e(`/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(n.synced.length===0){process.stdout.write(`Nothing new to sync (${n.skipped} already tracked).
384
- `);return}let s=n.synced.map(a=>({id:a.sessionId,upstream:a.upstreamSessionId,cwd:a.cwd,title:a.title??"-"})),r={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},i={id:cs(r.id,s.map(a=>a.id)),upstream:cs(r.upstream,s.map(a=>a.upstream)),cwd:cs(r.cwd,s.map(a=>a.cwd))},o=a=>[a.id.padEnd(i.id),a.upstream.padEnd(i.upstream),a.cwd.padEnd(i.cwd),a.title].join(" ");process.stdout.write(o(r)+`
385
- `);for(let a of s)process.stdout.write(o(a)+`
386
- `);process.stdout.write(`
387
- Synced ${n.synced.length} session(s); skipped ${n.skipped} already tracked.
388
- `)}async function wy(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
389
- `),process.exit(2);return}let n=_.agentLogFile(t);await Bi(n,e,"No log file (agent never ran?)")}async function by(t,e){let n=await we();if(!t){let c=await hy()??Nu(await Ui());process.stdout.write(`${py(c)}
390
- `);return}let s;try{let a=await $e("/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)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
391
- `),process.exit(1);return}e!==void 0?await Qf(t,e):await $a(t);let i=Nu(await Ui());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
392
- `),process.stdout.write(`${py(i)}
393
- `);let o=await hy();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${vy(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
394
- `))}function py(t){return`Default agent is ${vy(t)}`}function vy(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function Nu(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 hy(){try{let t=await $e("/v1/config",{rethrowNetworkError:!0});return t.ok?Nu(t.body):void 0}catch{return}}async function Hu(){let e=(await $e("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
395
- `)}async function Sy(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
396
- `),process.exit(2);return}await Gf(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
397
- `):process.stdout.write(`Pinned ${t} to ${e}.
398
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function ky(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
399
- `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
400
- `),process.exit(2);return}let n=jd(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(" "):""}
401
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Iy(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
402
- `),process.exit(2);return}await qc(t,void 0),process.stdout.write(`Removed local agent ${t}.
403
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Uu(t){await Xf(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.
404
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function cs(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Xo();$i();kr();Je();vr();Pr();At();Xt();qa();zu();import aA from"os";import{spawn as dA}from"child_process";async function cA({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 lA(c,s),u=await Wu(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}=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
405
415
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
406
416
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
407
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await t.request("session/new",{cwd:aA.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
408
- `),{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 lA(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: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}
409
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:
410
420
  ${s.join(`
411
421
  `)}
412
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}
413
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})
414
- `),process.exit(2)}async function Uy(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
415
- `),process.exit(2));let n=await we(),s=await Ut(n);await Hs(n);let r=["acp.v1",`hydra-acp-token.${s.token}`],i=await Mr(s.wsUrl,r),o=jn(i),a=new jt(o);try{await a.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:pe}})}catch{}let c;try{c=await cA({conn:a,agentId:t,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:dA})}finally{i.close()}process.exit(c.exitCode)}Vc();Us();async function jy(t){let e=si(t,"force");if(await Md()&&!e){let r=await di("Current password: ");await _d(r)||(process.stderr.write(`Wrong password.
416
- `),process.exit(1))}let n=await di("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
- `),process.exit(2));let s=await di("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
- `),process.exit(1)),await zm(n),process.stdout.write(`Password set.
419
- `)}async function qy(){let e=(await $e("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
420
- `);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:ac(n.id,s.map(o=>o.id)),label:ac(n.label,s.map(o=>o.label)),createdAt:ac(n.createdAt,s.map(o=>o.createdAt)),expiresAt:ac(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 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)+`
421
431
  `);for(let o of s)process.stdout.write(i(o)+`
422
- `)}async function Wy(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
423
- `),process.exit(2));let e=await $e(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
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}
424
434
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
425
435
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
426
- `),process.exit(1)}function ac(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Ks from"fs";Je();vr();Pr();Ku();At();var dc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Vu(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(Ju(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(!Ju(e)&&!Vu(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(Ju(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(!Vu(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=Gt(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 Ju(t){return"method"in t&&"id"in t&&t.id!==void 0}function Vu(t){return!("method"in t)&&"id"in t}lc();Xt();he();Co();import{writeFileSync as gA}from"fs";var yA=t=>{gA("/proc/self/comm",t)};function so(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??yA;try{s(e.commName??Fn())}catch{}}function ro(t,e=Fn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function fc(t){so(ro(process.argv.slice(2)),{commName:"hydra-shim"});let e=await we(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Hs(e);let s=new dc,r=Va(process.stdin,process.stdout),i=n.isLocal?async()=>(await Ut(await we())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new no({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await IA(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
427
- `);for(let l of d)await xA(a,l,s.lastMessageId(l.sessionId))}}});wA({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
428
- `),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 wA({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(Gy("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&TA(i)){e.send({jsonrpc:"2.0",id:i.id,result:Dr(i.params)});return}bA(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(Gy("client\u2192daemon",i),s.observeFromClient(i),AA(i)){e.send(RA(i));return}if(CA(i)){if(t.sessionId){e.send(EA(i,t.sessionId));return}let o=i;t.agentId&&(o=uc(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=uc(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=uc(o,{title:r.name}),r.used=!0),t.model&&(o=uc(o,{model:t.model})),e.send(o);return}e.send(i)})}function bA(t,e,n){let s=vA(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=kA(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function vA(t){if(!SA(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function SA(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function kA(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function IA(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
429
- `);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 xA(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 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}
430
440
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
431
- `)}}function CA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function AA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function RA(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 TA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function EA(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var PA=25*1024*1024,Qy=!1,Hr=null;function Gy(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Qy){Qy=!0;try{Hr=_.shimWireLogFile(),Ks.mkdirSync(_.home(),{recursive:!0});let n=Ks.statSync(Hr,{throwIfNoEntry:!1});n&&n.size>PA&&Ks.renameSync(Hr,`${Hr}.1`)}catch{Hr=null}}if(Hr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
432
- `;Ks.appendFile(Hr,n,()=>{})}catch{}}}function uc(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}kr();$i();Xo();Je();vr();Pr();Bs();At();Xt();lc();import{mkdtempSync as UA,rmSync as jA}from"fs";import{tmpdir as qA}from"os";import{join as WA}from"path";function Xy(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())}}}Vi();import MA from"chalk";import _A from"strip-ansi";var pc=new MA.Instance({level:3});function Zy(t,e){if(t.length===0)return"";let n=Ws(t);if(n.length===0)return"";let s=[];for(let i of n)s.push($A(i,e));let r=s.join(`
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(`
433
443
  `);return r.endsWith(`
434
444
  `)||(r+=`
435
- `),r}function $A(t,e){let n=DA(t.body,e);return e==="ansi"?n=HA(n,t.bodyStyle):n=_A(n),n}var FA="\x1B[1m",OA="\x1B[96m",LA="\x1B[93m",BA="\x1B[0m",NA="\0";function DA(t,e){let n=t.replace(/\^\^/g,NA);return e==="ansi"&&(n=n.replace(/\^\+/g,FA).replace(/\^C/g,OA).replace(/\^Y/g,LA).replace(/\^:/g,BA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function HA(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return pc.bold.yellowBright(t);case"heading-2":return pc.bold.cyanBright(t);case"heading-3":return pc.bold(t);case"dim":return pc.dim(t);default:return t}}var zA=1*1024*1024,ew="mcp__hydra-acp-stdin__";function tw(t,e){return{sessionId:t,prompt:e,_meta:{[Ct]:{ancillary:!0}}}}function KA(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 JA(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(ew))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(ew))}async function nw(t){if(so(ro(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.
436
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=UA(WA(qA(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{jA(c,{recursive:!0,force:!0})}catch{}})}let e=await we(),n=t.target??await Ut(e);n.isLocal&&!t.target&&await Hs(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await Mr(n.wsUrl,s),i=jn(r),o=new jt(i),a=await YA({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:VA(n.baseUrl,n.token)});process.exit(a.exitCode)}function VA(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 YA(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 G=>n.dangerouslySkipPermissions?Dr(G):JA(G)?Dr(G):Jy(G));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:xr,version:pe}})}catch{}let u=await XA(e,n,l),f=!1,p=!0,h="",m=0,y=G=>{G.length!==0&&(o(G),p=G.charCodeAt(G.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let G=Zy(h,c);if(h="",G.length===0)return;let de=m>0?`
437
- `:"";y(de+G),m+=1},v=()=>{b(),f&&!p&&y(`
438
- `),f=!1};e.onNotification("session/update",G=>{let de=G?.update,ze=Un(de,{cwd:n.cwd});if(ze){if(ze.kind==="agent-text"){d?y(ze.text):h+=ze.text;return}if(ze.kind==="turn-complete"){v();return}switch(ze.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,x=async G=>{let de=[];if(n.prompt&&!S&&de.push({type:"text",text:n.prompt}),G.length>0&&de.push({type:"text",text:G}),de.length!==0){try{await e.request("session/prompt",tw(u,de)),S=!0}catch(ze){a(`hydra-acp cat: prompt failed: ${ze.message}
439
- `);return}v()}},T=0,$,F=new Promise(G=>{$=G}),j=!1,K=async G=>{j||(j=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(ze=>setTimeout(ze,500))]),await e.close().catch(()=>{}),$({exitCode:G}))};e.onClose(G=>{G&&(a(`hydra-acp cat: ${G.message}
440
- `),T=1),j||(j=!0,v(),$({exitCode:T}))});let H=[],L=!1,D=!1,X=async()=>{if(!L){L=!0;try{for(;H.length>0;){let G=H.shift();if(G===void 0)break;await x(G)}}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"),QA({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:G=>{a(`hydra-acp cat: stdin error: ${G.message}
441
- `),T=1,D=!0,!L&&H.length===0&&K(T)},onPromptFailed:G=>{a(`hydra-acp cat: ${G.message}
442
- `),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 G=Xy({scheduleFlushCheck:de=>{let ze=setImmediate(de);return()=>clearImmediate(ze)},onChunk:de=>{H.push(de),X()}});return s.on("data",de=>{G.feed(typeof de=="string"?de:de.toString("utf8"))}),s.on("end",()=>{G.eof(),D=!0,!L&&H.length===0&&K(T)}),s.on("error",de=>{a(`hydra-acp cat: stdin error: ${de.message}
443
- `),T=1,D=!0,!L&&H.length===0&&K(T)}),F}let be="";return s.on("data",G=>{be+=typeof G=="string"?G:G.toString("utf8")}),s.on("end",()=>{D=!0,be.length>0&&H.push(be),X()}),s.on("error",G=>{a(`hydra-acp cat: stdin error: ${G.message}
444
- `),T=1,D=!0,!L&&H.length===0&&K(T)}),F}function QA(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??zA,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let x=v.toString("base64");h=h.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
445
- `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=GA(r.prompt,v.capacityBytes);e.request("session/prompt",tw(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function GA(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 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:
446
456
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
447
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.
448
458
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -457,49 +467,49 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
457
467
  User's question:
458
468
  ${t}`:`${s}
459
469
 
460
- 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 XA(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:xr,version:pe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=KA(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={[Ct]:s});let o=await t.request("session/new",i);return Gt(o._meta),o.sessionId}Je();he();function hc(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function sw(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function ZA(t){try{return JSON.parse(t)}catch{return t}}function rw(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function iw(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
461
- `),process.exit(2));let e=hc(t),n=await we(),s=sw(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
462
- `),process.exit(1)),process.stdout.write(`${rw(s)}
463
- `)}async function ow(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
464
- `),process.exit(2));let n=hc(t),s=ZA(e);try{await os(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}
465
- `),process.exit(1)}process.stdout.write(`set ${t} = ${rw(s)}
466
- `)}async function aw(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
467
- `),process.exit(2));let e=hc(t);try{await os(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 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}
468
478
  `),process.exit(1)}process.stdout.write(`unset ${t}
469
- `)}async function dw(t){let e=await we(),n=t?sw(e,hc(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
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
470
480
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
471
- `)}function cw(){process.stdout.write(`${_.config()}
472
- `)}Je();is();Pr();Xt();Us();async function fw(t={}){let{report:e,configLoaded:n}=await eR();if(t.json){process.stdout.write(JSON.stringify(e,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)+`
473
483
  `);return}process.stdout.write(`CLI: ${e.cli}
474
484
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
475
- `),e.daemonReachable&&(lw("Extensions",e.extensions),lw("Transformers",e.transformers)))}function lw(t,e){if(process.stdout.write(`
485
+ `),e.daemonReachable&&(bw("Extensions",e.extensions),bw("Transformers",e.transformers)))}function bw(t,e){if(process.stdout.write(`
476
486
  ${t}:
477
487
  `),e.length===0){process.stdout.write(` (none)
478
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}
479
- `)}}async function eR(){let t={cli:pe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await we()}catch{return{report:t,configLoaded:!1}}let n=await Er(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 mr()}catch{return{report:t,configLoaded:!0}}let r=await Di(),i={Authorization:`Bearer ${s}`};return t.extensions=await uw(`${r}/v1/extensions`,i,"extensions"),t.transformers=await uw(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function uw(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 tR}from"child_process";import{accessSync as nR,constants as sR,statSync as rR}from"fs";import{delimiter as iR,join as oR}from"path";var aR=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function dR(t){return aR.has(t)}function cR(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function lR(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 uR(t){try{if(!rR(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return nR(t,sR.X_OK),!0}catch{return!1}}function fR(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(iR).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=oR(o,r+a);if(uR(c))return c}}function pR(t,e){let n=tR(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
480
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function pw(t){let e=cR(t);if(e===void 0||dR(e))return!1;let n=fR(e);if(n===void 0)return!1;pR(n,lR(t))}Yu();var Qs=!1,Pb=!1;function Mb(t){!t||Pb||(Pb=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
481
- `))}async function nT(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(To(),cp));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],x=v.slice(1),{flags:T}=Dc(b);if($b(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.
482
- `),process.exit(2);return}let $=S??pt(T,"agent");if(!$){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
483
- `),process.exit(2);return}let F=await Fb(nl(T),{allowPrompt:!1}),j=pt(T,"name"),K=pt(T,"model");Qs=!0;let H=T["dangerously-skip-permissions"]===!0;Mb(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 fc(L);return}Mf(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&pw(e);let{positional:s,flags:r}=Dc(e);if($b(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${sT()}
484
- `);return}if(r.help===!0){$f();return}let i=Mf(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=pt(r,"name"),d=pt(r,"agent"),l=pt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Mb(u);let f=nl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Fb(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.
485
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){Qs=!0,await _b(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}Qs=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await fc(b);return}switch(a){case"shim":{Qs=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await fc(b);return}case"cat":{let b=Mf(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=pt(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 $=_f(r,"stream-threshold");$!==void 0&&(T.streamThreshold=$);let F=_f(r,"stream-bytes");F!==void 0&&(T.streamBufferBytes=F),d!==void 0&&await Du(d),Qs=!0,await nw(T);return}case"version":{Qs=!0,await fw({json:r.json===!0});return}case"init":await wp(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await mg();return}if(S==="start"){await ug(r);return}if(S==="stop"){await fg();return}if(S==="restart"){await pg();return}if(S==="log"||S==="logs"){await hg(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
486
- `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=pt(r,"columns"),S;if(v!==void 0)try{S=Ag(v)}catch(x){process.stderr.write(`${x.message}
487
- `),process.exit(2);return}await Eg({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(b==="info"){await Gg(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(b==="diff"){await Qg(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(b==="kill"){await Pg(s[2]);return}if(b==="remove"){await Mg(s[2]);return}if(b==="collect"){let v=pt(r,"max-age-days"),S=pt(r,"limit"),x={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
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
488
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
489
- `),process.exit(2);return}x.limit=T}await _g(x);return}if(b==="export"){let v=pt(r,"out"),S=pt(r,"tools");await $g(s[2],v,S);return}if(b==="transcript"){let v=pt(r,"out");await Fg(s[2],v);return}if(b==="import"){let v=pt(r,"cwd");await Og(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=pt(r,"host"),S=pt(r,"cwd");await Lg(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
490
- `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Zg();return}if(S==="add"){await ey(x,T);return}if(S==="remove"){await ty(x);return}if(S==="start"){await ny(x);return}if(S==="stop"){await sy(x);return}if(S==="restart"){await ry(x);return}if(S==="log"||S==="logs"){await iy(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
491
- `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await oy();return}if(S==="add"){await ay(x,T);return}if(S==="remove"){await dy(x);return}if(S==="start"){await cy(x);return}if(S==="stop"){await ly(x);return}if(S==="restart"){await uy(x);return}if(S==="log"||S==="logs"){await fy(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
492
- `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await my();return}if(b==="refresh"){await Hu();return}if(b==="install"){await gy(s[2]);return}if(b==="sync"){await yy(s[2]);return}if(b==="set"){await by(s[2],s[3]);return}if(b==="pin"){await Sy(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await ky(S[1],S.slice(2));return}if(b==="remove"){await Iy(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=Hd(S);await wy(x,T);return}if(b==="auth"){await Uy(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
493
- `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await Hu();return}if(b==="pin"){await Uu(!0);return}if(b==="unpin"){await Uu(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
494
- `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await jy(r);return}process.stderr.write(`Unknown auth password action: ${v}
495
- `),process.exit(2);return}if(b===void 0||b==="list"){await qy();return}if(b==="revoke"){await Wy(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
496
- `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await dw(s[2]);return}if(b==="get"){await iw(s[2]);return}if(b==="set"){await ow(s[2],s[3]);return}if(b==="unset"){await aw(s[2]);return}if(b==="path"){cw();return}process.stderr.write(`Unknown config subcommand: ${b}
497
- `),process.exit(2);return}case"tui":Qs=!0,await _b(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
498
- `),$f(),process.exit(2)}}async function _b(t,e){let n=pt(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 Du(e.agentId),so(ro(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Eb(),Tb)),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.
499
- `),process.exit(2)),a.drip=!0;let c=_f(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function _f(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 $b(t){let e=qf(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
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}
500
510
 
501
- `),$f(),process.exit(2))}function Mf(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 Fb(t,e){try{return await gp(t,e)}catch(n){process.stderr.write(`${n.message}
502
- `),process.exit(1)}}function sT(){try{let t=eT(Z0(import.meta.url));return JSON.parse(X0(tT(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function $f(){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 live 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(`
503
- `))}async function Ob(){if(!Qs)try{let t=await da();t&&process.stderr.write(`\u2728 ${ca(t)}
504
- `)}catch{}}nT().then(Ob).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
505
- `),await Ob(),process.exit(1)});
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)});