@hydra-acp/cli 0.1.89 → 0.1.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +295 -292
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- var mb=Object.defineProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var af=(t,e)=>{for(var n in e)mb(t,n,{get:e[n],enumerable:!0})};import*as ge from"path";import*as ic from"os";function qe(t){let e=ic.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function vb(){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 ve(){let t=process.env[bb];if(t&&t.length>0)return ge.resolve(t);let e=vb();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(ic.homedir(),".hydra-acp")}var bb,_,me=J(()=>{"use strict";bb="HYDRA_ACP_HOME";_={home:ve,config:()=>ge.join(ve(),"config.json"),authToken:()=>ge.join(ve(),"auth-token"),remotes:()=>ge.join(ve(),"remotes.json"),pidFile:()=>ge.join(ve(),"daemon.pid"),logFile:()=>ge.join(ve(),"daemon.log"),currentLogFile:()=>ge.join(ve(),"current.log"),registryCache:()=>ge.join(ve(),"registry.json"),agentsDir:()=>ge.join(ve(),"agents"),agentLogFile:t=>ge.join(ve(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ge.join(ve(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ge.join(ve(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ge.join(ve(),"sessions"),sessionDir:t=>ge.join(ve(),"sessions",t),sessionFile:t=>ge.join(ve(),"sessions",t,"meta.json"),historyFile:t=>ge.join(ve(),"sessions",t,"history.jsonl"),toolsDir:t=>ge.join(ve(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ge.join(ve(),"sessions",t,"tools",e),queueFile:t=>ge.join(ve(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ge.join(ve(),"sessions",".tombstones"),tombstoneAgentDir:t=>ge.join(ve(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ge.join(ve(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ge.join(ve(),"extensions"),extensionLogFile:t=>ge.join(ve(),"extensions",`${t}.log`),extensionPidFile:t=>ge.join(ve(),"extensions",`${t}.pid`),transformersDir:()=>ge.join(ve(),"transformers"),transformerLogFile:t=>ge.join(ve(),"transformers",`${t}.log`),transformerPidFile:t=>ge.join(ve(),"transformers",`${t}.pid`),transformerState:(t,e)=>ge.join(ve(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ge.join(ve(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ge.join(ve(),"prompt-history"),tuiLogFile:()=>ge.join(ve(),"tui.log"),shimWireLogFile:()=>ge.join(ve(),"shim-wire.log")}});import*as Tr from"fs/promises";function Er(){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 Pr(){try{let e=(await Tr.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function Ds(){let t=await Pr();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Mr(t){await Tr.mkdir(_.home(),{recursive:!0}),await Tr.writeFile(_.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function qi(){let t=await Pr();if(t)return t;let e=Er();return await Mr(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
- `),e}var $n=J(()=>{"use strict";me()});import*as ut from"fs/promises";import*as lf from"fs";import*as Zt from"path";import{randomBytes as Sb}from"crypto";async function Bt(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await kb(t,r,n)}async function kb(t,e,n={}){let s=await Ib(t),r=xb(s);await ut.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Cb()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await ut.writeFile(i,e,o),await ut.rename(i,s)}catch(o){throw await ut.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{lf.chmodSync(s,n.mode)}catch{}}async function Ib(t){let e;try{e=await ut.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await ut.readlink(t),s=Zt.isAbsolute(n)?n:Zt.resolve(Zt.dirname(t),n);try{let r=await ut.realpath(Zt.dirname(s));return Zt.join(r,Zt.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function zt(t){let e;try{e=await ut.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 xb(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function Cb(){return Sb(4).toString("hex")}var Hs=J(()=>{"use strict"});import*as ss from"fs/promises";import{homedir as oc}from"os";import{z as B}from"zod";function pf(t){return t.tui.inAppSelection??t.tui.mouse}function mf(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function hf(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function ea(){return await Ob(),await zt(_.config())??{}}async function Ob(){let t;try{t=await ss.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await ss.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await ss.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 ta(){let t=await ea(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await ss.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 Mr(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Bt(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
- `)}async function ye(){return await ta(),ac.parse(await ea())}async function On(t){await ta();let e=await ea();t(e),ac.parse(e),await Bt(_.config(),e,{mode:384})}async function Wi(t,e){await On(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function na(t){await On(e=>{e.defaultAgent=t})}async function gf(t,e){await On(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function yf(t,e){await On(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 dc(t,e){await On(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 wf(t){await On(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function bf(){let t=await ea();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function We(t){return t==="~"||t==="$HOME"?oc():t.startsWith("~/")?oc()+t.slice(1):t.startsWith("$HOME/")?oc()+t.slice(5):t}var ff,Ab,en,Rb,Tb,Eb,Pb,Mb,uf,_b,$b,ac,He=J(()=>{"use strict";me();$n();Hs();ff="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Ab=B.object({cert:B.string(),key:B.string()}),en=55514,Rb=B.object({host:B.string().default("127.0.0.1"),port:B.number().int().positive().default(en),logLevel:B.enum(["debug","info","warn","error"]).default("info"),tls:Ab.optional(),sessionIdleTimeoutSeconds:B.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:B.number().int().positive().default(1e4),agentStderrTailBytes:B.number().int().positive().default(4096),publicHost:B.string().optional(),agentSyncIntervalMinutes:B.number().nonnegative().default(60),sessionGcIntervalMinutes:B.number().nonnegative().default(60),sessionGcMaxAgeDays:B.number().positive().default(2)}),Tb=B.object({url:B.string().url().default(ff),ttlHours:B.number().positive().default(24),pinned:B.boolean().default(!1)}),Eb=B.object({name:B.string().optional(),description:B.string().optional(),command:B.string().optional(),args:B.array(B.string()).optional(),env:B.record(B.string()).optional()}),Pb=B.object({packageSpec:B.string().optional()}),Mb=B.object({repaintThrottleMs:B.number().int().nonnegative().default(1e3),maxScrollbackLines:B.number().int().positive().default(1e4),mouse:B.boolean().default(!0),inAppSelection:B.boolean().optional(),selectionClipboard:B.enum(["primary","clipboard","both"]).default("both"),openFileCommand:B.union([B.string(),B.array(B.string())]).optional(),logMaxBytes:B.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:B.number().int().positive().default(32),progressIndicator:B.boolean().default(!0),defaultEnterAction:B.enum(["enqueue","amend"]).default("amend"),showThoughts:B.boolean().default(!0),ambiguousWidth:B.enum(["auto","narrow","wide"]).default("auto"),toolContent:B.enum(["inline","references"]).default("references"),diffContextLines:B.number().int().min(0).default(3),promptHistoryMaxEntries:B.number().int().positive().default(2e3),maxToolItems:B.number().int().nonnegative().default(5),maxPlanItems:B.number().int().nonnegative().default(5),showFileUpdates:B.enum(["none","edit","diff"]).default("edit"),sessionColumns:B.array(B.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),uf=B.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),_b=B.object({command:B.array(B.string()).default([]),args:B.array(B.string()).default([]),env:B.record(B.string()).default({}),enabled:B.boolean().default(!0)}),$b=B.object({command:B.array(B.string()).default([]),args:B.array(B.string()).default([]),env:B.record(B.string()).default({}),enabled:B.boolean().default(!0)}),ac=B.object({daemon:Rb.default({}),registry:Tb.default({url:ff,ttlHours:24,pinned:!1}),agents:B.record(B.string(),Eb).default({}),agentOverrides:B.record(B.string(),Pb).default({}),defaultAgent:B.string().default("opencode"),defaultModels:B.record(B.string(),B.string()).default({}),synopsisAgent:B.string().optional(),synopsisModel:B.string().optional(),compaction:B.object({agent:B.string().optional(),model:B.string().optional(),tailK:B.number().int().nonnegative().default(20),maxIterations:B.number().int().positive().default(3),contextFraction:B.number().min(0).max(1).default(.5),hardCeilingFraction:B.number().min(0).max(1).default(.85),absoluteFallback:B.number().int().positive().default(12e4),idleBeforePromptMs:B.number().int().nonnegative().default(3e5),modelContextWindows:B.record(B.string(),B.number().int().positive()).default({})}).default({}),defaultCwd:B.string().default("~"),compressToolContent:B.boolean().default(!0),sessionListColdLimit:B.number().int().nonnegative().default(20),extensions:B.record(uf,_b).default({}),transformers:B.record(uf,$b).default({}),defaultTransformers:B.array(B.string()).default([]),npmRegistry:B.string().url().optional(),tui:Mb.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 Us(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function cc(t){return{httpScheme:"https",wsScheme:"wss"}}function lc(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 ${sa(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${sa(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=Fb(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${sa(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${sa(t)}`);let i=Us(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=en;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function vf(t){let e=t.port!==void 0&&t.port!==en?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Fb(t){try{return new URL(t)}catch{return null}}function sa(t){return t.length>80?`${t.slice(0,77)}...`:t}var zi=J(()=>{"use strict";He()});function js(t,e){return`${t}:${e}`}function Sf(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Lb(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 Bb(){let t=await zt(_.remotes());return t===void 0?{version:1,entries:{}}:Nb(t)}function Nb(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 uc(t){await Bt(_.remotes(),t,{mode:384})}var ra,fc=J(()=>{"use strict";me();Hs();ra=class t{data;constructor(e){this.data=e}static async load(){let e=await Bb(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Sf(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await uc(i),new t(i)}get(e,n){let s=this.data.entries[js(e,n)];if(s&&!Sf(s,Date.now()))return s}async set(e,n,s){this.data.entries[js(e,n)]=s,await uc(this.data)}async delete(e,n){let s=js(e,n);return s in this.data.entries?(delete this.data.entries[s],await uc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Lb(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function _r(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)}):Db()}function Db(){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 pc=J(()=>{"use strict"});import*as kf from"path";function mn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=kf.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Ji=J(()=>{"use strict"});import*as ia from"fs/promises";async function Fn(){try{let t=await ia.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 If(t){await ia.writeFile(_.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function tn(t){try{return process.kill(t,0),!0}catch{return!1}}var $r=J(()=>{"use strict";me()});var Pf={};af(Pf,{_resetForTests:()=>Wb,clearPin:()=>qb,fetchPeerFingerprint:()=>yc,formatFingerprint:()=>oa,getPin:()=>hc,installGlobalTlsTrust:()=>bc,loadPinsFromStore:()=>gc,setPin:()=>Ki,sha256Hex:()=>wc,wsTlsOptions:()=>Yi});import{createHash as Hb}from"crypto";import*as Cf from"tls";import{Agent as Ub,buildConnector as xf,setGlobalDispatcher as jb}from"undici";function Ki(t,e,n){qs.set(js(t,e),Af(n))}function qb(t,e){qs.delete(js(t,e))}function hc(t,e){return qs.get(js(t,e))}function gc(t){qs.clear();for(let e of t.list())e.entry.pinnedFingerprint&&Ki(e.host,e.port,e.entry.pinnedFingerprint)}async function yc(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Cf.connect({host:t,port:e,servername:t,rejectUnauthorized:!1}),a=!1,c=(l,f)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):f&&r(f)}},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,wc(l.raw))}),o.once("error",l=>c(l))})}function wc(t){return Hb("sha256").update(t).digest("hex")}function oa(t){let e=Af(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Af(t){return t.replace(/:/g,"").toLowerCase()}function bc(){if(mc)return;mc=!0;let t=xf({}),e=xf({rejectUnauthorized:!1,checkServerIdentity:(n,s)=>Tf(n,s)});jb(new Ub({connect:(n,s)=>{let r=String(n.hostname??n.host??"");return(Rf(r)?e:t)(n,s)}}))}function Rf(t){for(let e of qs.keys())if(Ef(e)?.host===t)return!0;return!1}function Tf(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=wc(e.raw);for(let[s,r]of qs.entries()){let i=Ef(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${oa(n)})`)}function Ef(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 Yi(t){return Rf(t)?{rejectUnauthorized:!1,checkServerIdentity:(e,n)=>Tf(e,n)}:{}}function Wb(){qs.clear(),mc=!1}var qs,mc,Vi=J(()=>{"use strict";fc();qs=new Map,mc=!1});import*as Of from"os";async function Et(t){let e=await qi(),n=await Fn();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:Us(r)}}function Mf(t,e){let{httpScheme:n,wsScheme:s}=cc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Lf(t),isLocal:t.isLoopback}}async function Ff(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??_r,r=e.confirmImpl??Yb,i=e.tlsHandshakeImpl??zb,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await Pr();if(b)return Kb(t,b)}let c=e.store??await ra.load();gc(c),bc();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&Ki(t.host,t.port,d.pinnedFingerprint),Mf(t,d.token);if(!a)throw new vc(t.host,t.port);let l=Lf(t),{httpScheme:f}=cc(t.host),u;if(f==="https"&&hc(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
2
+ var pb=Object.defineProperty;var K=(t,e)=>()=>(t&&(e=t(t=0)),e);var cf=(t,e)=>{for(var n in e)pb(t,n,{get:e[n],enumerable:!0})};import*as he from"path";import*as cc from"os";function Ue(t){let e=cc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function bb(){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 ke(){let t=process.env[wb];if(t&&t.length>0)return he.resolve(t);let e=bb();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 he.join(cc.homedir(),".hydra-acp")}var wb,_,pe=K(()=>{"use strict";wb="HYDRA_ACP_HOME";_={home:ke,config:()=>he.join(ke(),"config.json"),authToken:()=>he.join(ke(),"auth-token"),remotes:()=>he.join(ke(),"remotes.json"),pidFile:()=>he.join(ke(),"daemon.pid"),logFile:()=>he.join(ke(),"daemon.log"),currentLogFile:()=>he.join(ke(),"current.log"),registryCache:()=>he.join(ke(),"registry.json"),agentsDir:()=>he.join(ke(),"agents"),agentLogFile:t=>he.join(ke(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>he.join(ke(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>he.join(ke(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>he.join(ke(),"sessions"),sessionDir:t=>he.join(ke(),"sessions",t),sessionFile:t=>he.join(ke(),"sessions",t,"meta.json"),historyFile:t=>he.join(ke(),"sessions",t,"history.jsonl"),toolsDir:t=>he.join(ke(),"sessions",t,"tools"),toolBlobFile:(t,e)=>he.join(ke(),"sessions",t,"tools",e),queueFile:t=>he.join(ke(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>he.join(ke(),"sessions",".tombstones"),tombstoneAgentDir:t=>he.join(ke(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>he.join(ke(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>he.join(ke(),"extensions"),extensionLogFile:t=>he.join(ke(),"extensions",`${t}.log`),extensionPidFile:t=>he.join(ke(),"extensions",`${t}.pid`),transformersDir:()=>he.join(ke(),"transformers"),transformerLogFile:t=>he.join(ke(),"transformers",`${t}.log`),transformerPidFile:t=>he.join(ke(),"transformers",`${t}.pid`),transformerState:(t,e)=>he.join(ke(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>he.join(ke(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>he.join(ke(),"prompt-history"),tuiLogFile:()=>he.join(ke(),"tui.log"),shimWireLogFile:()=>he.join(ke(),"shim-wire.log")}});import*as Nr from"fs/promises";function Dr(){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 Hr(){try{let e=(await Nr.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function Gs(){let t=await Hr();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Ur(t){await Nr.mkdir(_.home(),{recursive:!0}),await Nr.writeFile(_.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function Xi(){let t=await Hr();if(t)return t;let e=Dr();return await Ur(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
+ `),e}var qn=K(()=>{"use strict";pe()});import*as ft from"fs/promises";import*as ff from"fs";import*as on from"path";import{randomBytes as vb}from"crypto";async function Ft(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await Sb(t,r,n)}async function Sb(t,e,n={}){let s=await kb(t),r=Ib(s);await ft.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${xb()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await ft.writeFile(i,e,o),await ft.rename(i,s)}catch(o){throw await ft.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{ff.chmodSync(s,n.mode)}catch{}}async function kb(t){let e;try{e=await ft.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await ft.readlink(t),s=on.isAbsolute(n)?n:on.resolve(on.dirname(t),n);try{let r=await ft.realpath(on.dirname(s));return on.join(r,on.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function zt(t){let e;try{e=await ft.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 Ib(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function xb(){return vb(4).toString("hex")}var Qs=K(()=>{"use strict"});import*as ls from"fs/promises";import{homedir as lc}from"os";import{z as D}from"zod";function hf(t){return t.tui.inAppSelection??t.tui.mouse}function gf(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 oa(){return await $b(),await zt(_.config())??{}}async function $b(){let t;try{t=await ls.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await ls.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await ls.readlink(_.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${_.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function aa(){let t=await oa(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await ls.access(_.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${_.authToken()} and ${_.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ur(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Ft(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
+ `)}async function ye(){return await aa(),uc.parse(await oa())}async function Wn(t){await aa();let e=await oa();t(e),uc.parse(e),await Ft(_.config(),e,{mode:384})}async function Zi(t,e){await Wn(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function da(t){await Wn(e=>{e.defaultAgent=t})}async function wf(t,e){await Wn(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function bf(t,e){await Wn(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 fc(t,e){await Wn(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 vf(t){await Wn(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Sf(){let t=await oa();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function je(t){return t==="~"||t==="$HOME"?lc():t.startsWith("~/")?lc()+t.slice(1):t.startsWith("$HOME/")?lc()+t.slice(5):t}var mf,Cb,an,Ab,Rb,Tb,Eb,Pb,pf,Mb,_b,uc,Ne=K(()=>{"use strict";pe();qn();Qs();mf="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Cb=D.object({cert:D.string(),key:D.string()}),an=55514,Ab=D.object({host:D.string().default("127.0.0.1"),port:D.number().int().positive().default(an),logLevel:D.enum(["debug","info","warn","error"]).default("info"),tls:Cb.optional(),sessionIdleTimeoutSeconds:D.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:D.number().int().positive().default(1e4),agentStderrTailBytes:D.number().int().positive().default(4096),publicHost:D.string().optional(),agentSyncIntervalMinutes:D.number().nonnegative().default(60),sessionGcIntervalMinutes:D.number().nonnegative().default(60),sessionGcMaxAgeDays:D.number().positive().default(2)}),Rb=D.object({url:D.string().url().default(mf),ttlHours:D.number().positive().default(24),pinned:D.boolean().default(!1)}),Tb=D.object({name:D.string().optional(),description:D.string().optional(),command:D.string().optional(),args:D.array(D.string()).optional(),env:D.record(D.string()).optional()}),Eb=D.object({packageSpec:D.string().optional()}),Pb=D.object({repaintThrottleMs:D.number().int().nonnegative().default(1e3),maxScrollbackLines:D.number().int().positive().default(1e4),mouse:D.boolean().default(!0),inAppSelection:D.boolean().optional(),selectionClipboard:D.enum(["primary","clipboard","both"]).default("both"),openFileCommand:D.union([D.string(),D.array(D.string())]).optional(),logMaxBytes:D.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:D.number().int().positive().default(32),progressIndicator:D.boolean().default(!0),defaultEnterAction:D.enum(["enqueue","amend"]).default("amend"),showThoughts:D.boolean().default(!0),ambiguousWidth:D.enum(["auto","narrow","wide"]).default("auto"),toolContent:D.enum(["inline","references"]).default("references"),diffContextLines:D.number().int().min(0).default(3),promptHistoryMaxEntries:D.number().int().positive().default(2e3),maxToolItems:D.number().int().nonnegative().default(5),maxPlanItems:D.number().int().nonnegative().default(5),showFileUpdates:D.enum(["none","edit","diff"]).default("edit"),sessionColumns:D.array(D.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),pf=D.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Mb=D.object({command:D.array(D.string()).default([]),args:D.array(D.string()).default([]),env:D.record(D.string()).default({}),enabled:D.boolean().default(!0)}),_b=D.object({command:D.array(D.string()).default([]),args:D.array(D.string()).default([]),env:D.record(D.string()).default({}),enabled:D.boolean().default(!0)}),uc=D.object({daemon:Ab.default({}),registry:Rb.default({url:mf,ttlHours:24,pinned:!1}),agents:D.record(D.string(),Tb).default({}),agentOverrides:D.record(D.string(),Eb).default({}),defaultAgent:D.string().default("opencode"),defaultModels:D.record(D.string(),D.string()).default({}),synopsisAgent:D.string().optional(),synopsisModel:D.string().optional(),compaction:D.object({agent:D.string().optional(),model:D.string().optional(),tailK:D.number().int().nonnegative().default(20),maxIterations:D.number().int().positive().default(3),contextFraction:D.number().min(0).max(1).default(.5),hardCeilingFraction:D.number().min(0).max(1).default(.85),absoluteFallback:D.number().int().positive().default(12e4),idleBeforePromptMs:D.number().int().nonnegative().default(3e5),modelContextWindows:D.record(D.string(),D.number().int().positive()).default({})}).default({}),defaultCwd:D.string().default("~"),compressToolContent:D.boolean().default(!0),sessionListColdLimit:D.number().int().nonnegative().default(20),extensions:D.record(pf,Mb).default({}),transformers:D.record(pf,_b).default({}),defaultTransformers:D.array(D.string()).default([]),npmRegistry:D.string().url().optional(),tui:Pb.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 Xs(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function pc(t){return{httpScheme:"https",wsScheme:"wss"}}function mc(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 ${ca(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${ca(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=Ob(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${ca(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${ca(t)}`);let i=Xs(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 kf(t){let e=t.port!==void 0&&t.port!==an?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Ob(t){try{return new URL(t)}catch{return null}}function ca(t){return t.length>80?`${t.slice(0,77)}...`:t}var eo=K(()=>{"use strict";Ne()});function Zs(t,e){return`${t}:${e}`}function If(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Fb(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 Lb(){let t=await zt(_.remotes());return t===void 0?{version:1,entries:{}}:Bb(t)}function Bb(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 hc(t){await Ft(_.remotes(),t,{mode:384})}var la,gc=K(()=>{"use strict";pe();Qs();la=class t{data;constructor(e){this.data=e}static async load(){let e=await Lb(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(If(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await hc(i),new t(i)}get(e,n){let s=this.data.entries[Zs(e,n)];if(s&&!If(s,Date.now()))return s}async set(e,n,s){this.data.entries[Zs(e,n)]=s,await hc(this.data)}async delete(e,n){let s=Zs(e,n);return s in this.data.entries?(delete this.data.entries[s],await hc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Fb(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function jr(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)}):Nb()}function Nb(){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 yc=K(()=>{"use strict"});import*as xf from"path";function vn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=xf.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var to=K(()=>{"use strict"});import*as ua from"fs/promises";async function zn(){try{let t=await ua.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 Cf(t){await ua.writeFile(_.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function dn(t){try{return process.kill(t,0),!0}catch{return!1}}var qr=K(()=>{"use strict";pe()});var Mf={};cf(Mf,{_resetForTests:()=>Kb,clearPin:()=>zb,fetchPeerFingerprint:()=>Sc,formatFingerprint:()=>fa,getPin:()=>bc,installGlobalTlsTrust:()=>Ic,loadPinsFromStore:()=>vc,setPin:()=>no,sha256Hex:()=>kc,wsTlsOptions:()=>so});import{createHash as Db}from"crypto";import*as Af from"tls";import{Agent as Hb,Dispatcher as Ub,buildConnector as jb,getGlobalDispatcher as qb,setGlobalDispatcher as Wb}from"undici";function no(t,e,n){er.set(Zs(t,e),Rf(n))}function zb(t,e){er.delete(Zs(t,e))}function bc(t,e){return er.get(Zs(t,e))}function vc(t){er.clear();for(let e of t.list())e.entry.pinnedFingerprint&&no(e.host,e.port,e.entry.pinnedFingerprint)}async function Sc(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Af.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,f)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):f&&r(f)}},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,kc(l.raw))}),o.once("error",l=>c(l))})}function kc(t){return Db("sha256").update(t).digest("hex")}function fa(t){let e=Rf(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Rf(t){return t.replace(/:/g,"").toLowerCase()}function Ic(){if(wc)return;wc=!0;let t=qb(),e=new Hb({connect:jb({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Ef(s,r)})}),n=new Ub;n.dispatch=(s,r)=>{let i=Jb(s.origin);return(i&&Tf(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(()=>{})),Wb(n)}function Jb(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Tf(t){for(let e of er.keys())if(Pf(e)?.host===t)return!0;return!1}function Ef(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=kc(e.raw);for(let[s,r]of er.entries()){let i=Pf(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${fa(n)})`)}function Pf(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 so(t){return Tf(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Ef(e,n)}:{autoSelectFamily:!0}}function Kb(){er.clear(),wc=!1}var er,wc,ro=K(()=>{"use strict";gc();er=new Map,wc=!1});import*as Ff from"os";async function Et(t){let e=await Xi(),n=await zn();if(n&&dn(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:Xs(r)}}function _f(t,e){let{httpScheme:n,wsScheme:s}=pc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Bf(t),isLocal:t.isLoopback}}async function Lf(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??jr,r=e.confirmImpl??Qb,i=e.tlsHandshakeImpl??Yb,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await Hr();if(b)return Gb(t,b)}let c=e.store??await la.load();vc(c),Ic();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&no(t.host,t.port,d.pinnedFingerprint),_f(t,d.token);if(!a)throw new xc(t.host,t.port);let l=Bf(t),{httpScheme:f}=pc(t.host),u;if(f==="https"&&bc(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
10
  subject: ${b.subject??"(unknown)"}
11
11
  issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${oa(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Ki(t.host,t.port,b.fingerprint),u=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 m=`${f}://${t.host}:${t.port}`,h=await n(`${m}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:$f()})});if(h.status===401)throw new Error(`Wrong password for ${l}.`);if(h.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(h.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!h.ok)throw new Error(`Login to ${l} failed: HTTP ${h.status}`);let w=await h.json();if(!w.session_token||!w.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:w.session_token,expiresAt:w.expires_at,label:$f(),...u?{pinnedFingerprint:u,pinnedAt:new Date().toISOString()}:{}}),Mf(t,w.session_token)}async function zb(t,e){let n=await Jb(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await yc(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Jb(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}),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 u=a.getPeerCertificate(!1);o({kind:"untrusted",subject:u?.subject?_f(u.subject):void 0,issuer:u?.issuer?_f(u.issuer):void 0});return}o({kind:"error",message:d.message})})})}function _f(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 Kb(t,e){let n=await Fn(),r=n&&tn(n.pid)?n.loopbackPort:t.port,i=t.port===en?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 Yb(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 $f(){try{let t=Of.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Lf(t){return t.port===en?t.host:`${t.host}:${t.port}`}var vc,Ws=J(()=>{"use strict";He();$n();zi();fc();pc();Ji();$r();Vi();zi();vc=class extends Error{host;port;constructor(e,n){let s=n===en?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${mn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});var q,fa=J(()=>{"use strict";q={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 Pe}from"zod";var op,Sv,ap,dp,cp,$c=J(()=>{"use strict";op=Pe.object({protocolVersion:Pe.number().optional(),clientCapabilities:Pe.record(Pe.unknown()).optional(),clientInfo:Pe.object({name:Pe.string(),version:Pe.string().optional()}).optional()}),Sv=Pe.enum(["full","pending_only","none","after_message"]),ap=Pe.object({cwd:Pe.string(),mcpServers:Pe.array(Pe.unknown()).optional(),_meta:Pe.record(Pe.unknown()).optional()}),dp=Pe.object({upstreamSessionId:Pe.string(),agentId:Pe.string(),cwd:Pe.string(),title:Pe.string().optional(),agentArgs:Pe.array(Pe.string()).optional()}),cp=Pe.object({sessionId:Pe.string(),historyPolicy:Sv.default("full"),afterMessageId:Pe.string().optional(),clientId:Pe.string().optional(),clientInfo:Pe.object({name:Pe.string(),version:Pe.string().optional()}).optional(),_meta:Pe.record(Pe.unknown()).optional()})});import{z as ie}from"zod";function pa(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),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 fp(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:Gi(t._meta,pa(t))};return t.title!==void 0&&(e.title=t.title),e}var lp,up,Oc,AT,kv,RT,Fc=J(()=>{"use strict";ma();lp=ie.object({sessionId:ie.string()}),up=ie.object({cwd:ie.string().optional(),cursor:ie.string().optional()}),Oc=ie.object({used:ie.number().optional(),size:ie.number().optional(),costAmount:ie.number().optional(),costCurrency:ie.string().optional()}),AT=ie.object({sessionId:ie.string(),upstreamSessionId:ie.string().optional(),cwd:ie.string(),title:ie.string().optional(),agentId:ie.string().optional(),currentModel:ie.string().optional(),currentUsage:Oc.optional(),importedFromMachine:ie.string().optional(),importedFromUpstreamSessionId:ie.string().optional(),parentSessionId:ie.string().optional(),forkedFromSessionId:ie.string().optional(),forkedFromMessageId:ie.string().optional(),originatingClient:ie.object({name:ie.string(),version:ie.string().optional()}).optional(),interactive:ie.boolean().optional(),priority:ie.number().int().nonnegative().optional(),updatedAt:ie.string(),attachedClients:ie.number().int().nonnegative(),status:ie.enum(["live","cold"]).default("live"),busy:ie.boolean().default(!1),awaitingInput:ie.boolean().default(!1),compactionState:ie.any().optional(),_meta:ie.record(ie.unknown()).optional()}),kv=ie.object({sessionId:ie.string(),cwd:ie.string(),title:ie.string().optional(),updatedAt:ie.string().optional(),_meta:ie.record(ie.unknown()).optional()}),RT=ie.object({sessions:ie.array(kv),nextCursor:ie.string().optional()})});function Iv(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 Dt(t){if(!t)return{};let e=t[pt];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=dp.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=Oc.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=Iv(n.env);r!==void 0&&(s.env=r)}return s}function Gi(t,e){return{...t??{},[pt]:e}}var pt,ma=J(()=>{"use strict";$c();Fc();pt="hydra-acp"});import{z as X}from"zod";var pp,ha,mp,$T,OT,FT,hp,LT,gp,BT,yp,NT,DT,wp=J(()=>{"use strict";pp=X.object({sessionId:X.string(),prompt:X.array(X.unknown()),_meta:X.record(X.unknown()).optional()}),ha=X.object({sessionId:X.string()}),mp=X.object({clientId:X.string(),name:X.string().optional(),version:X.string().optional()}),$T=X.object({sessionId:X.string(),messageId:X.string(),originator:mp,prompt:X.array(X.unknown()),position:X.number().int().nonnegative(),queueDepth:X.number().int().positive(),enqueuedAt:X.number()}),OT=X.object({sessionId:X.string(),messageId:X.string(),prompt:X.array(X.unknown())}),FT=X.object({sessionId:X.string(),messageId:X.string(),reason:X.enum(["started","cancelled","abandoned"])}),hp=X.object({sessionId:X.string(),messageId:X.string()}),LT=X.object({cancelled:X.boolean(),reason:X.enum(["ok","not_found","already_running"])}),gp=X.object({sessionId:X.string(),messageId:X.string(),prompt:X.array(X.unknown())}),BT=X.object({updated:X.boolean(),reason:X.enum(["ok","not_found","already_running"])}),yp=X.object({sessionId:X.string(),targetMessageId:X.string(),prompt:X.array(X.unknown()),replaceQueue:X.boolean().optional(),onTargetCompleted:X.enum(["reject","send_anyway"]).optional()}),NT=X.object({amended:X.boolean(),reason:X.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:X.string().optional()}),DT=X.object({sessionId:X.string(),cancelledMessageId:X.string(),newMessageId:X.string(),prompt:X.array(X.unknown()),originator:mp,amendedAt:X.number()})});import{z as is}from"zod";var bp,ga,vp=J(()=>{"use strict";bp=is.object({agentId:is.string(),version:is.string(),source:is.enum(["binary","npm"]),phase:is.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:is.number().optional(),totalBytes:is.number().optional(),packageSpec:is.string().optional()}),ga="hydra-acp/agents/install_progress"});var xt=J(()=>{"use strict";fa();$c();ma();Fc();wp();vp()});import{nanoid as xv}from"nanoid";var Lc,Pt,Js=J(()=>{"use strict";xt();Lc=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Pt=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 Lc;let s=xv(),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:q.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??q.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 Nr(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 Dr(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 Bc=J(()=>{"use strict"});import*as Ip from"fs/promises";function Lv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ev,Pv,Hr,Mv,_v,$v,Ov,Fv,kp,ba,xp=J(()=>{"use strict";Ev=64*1024*1024,Pv=1*1024*1024,Hr=64*1024,Mv=6e4,_v=100,$v=1e3,Ov=64*1024,Fv=256*1024,kp=20;ba=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??Ev,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Pv,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,Hr));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}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,Hr)),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,Hr)),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,Mv));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(Lv(e.pattern),c),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??_v,$v)),u=Math.max(1,Math.min(e.maxBytes??Ov,Fv)),p=Math.max(0,Math.min(e.contextBefore??0,kp)),m=Math.max(0,Math.min(e.contextAfter??0,kp)),h=[],w=[],b=[],v=0,S=!1,A=0,T=0,U=(V,N)=>{for(let G of b)G.remaining>0&&(G.match.after===void 0&&(G.match.after=[]),G.match.after.push({cursor:V,line:N}),G.remaining--,v+=N.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(N)!==l&&h.length<f){let G={cursor:V,line:N};if(p>0&&w.length>0){G.before=w.slice();for(let re of G.before)v+=re.line.length}v+=N.length,h.push(G),m>0&&b.push({match:G,remaining:m})}if(p>0)for(w.push({cursor:V,line:N});w.length>p;)w.shift();let H=h.length>=f&&b.length===0,Z=v>=u;return H||Z};for(let V=0;V<o.length;V++){if(o[V]!==10)continue;let N=o.subarray(A,V).toString("utf8"),F=r+A;if(A=V+1,T=A,U(F,N)){S=!0;break}}if(!S&&A<o.length&&this.closed){let V=o.subarray(A).toString("utf8"),N=r+A;U(N,V)&&(S=!0),T=o.length}let O=Math.min(r+T,this.writeCursor),z={matches:h,truncated:S,nextCursor:O,scannedBytes:T};return i>0&&(z.gap=i),this.closed&&O>=this.writeCursor&&(z.eof=!0),z}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(()=>Ip.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var va,dE,Cp=J(()=>{"use strict";va=[{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."}],dE=new Map(va.map(t=>[t.verb,t]))});function Ap(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Ur(t,e){return Nc(t,e.map(n=>n.modelId))}function Nc(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Ap(t),s=e.filter(i=>Ap(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 Sa=J(()=>{"use strict"});function Rp(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=Dc(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 f=n.get(l);f?f.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=Dc(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?Nv(r,i.outIndex,Bv(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?Dv(c,n.get(f)??[]):c;f!==void 0&&s.has(f)&&!Hv(u)&&(u=Uv(u,s.get(f))),r.push(u);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 Dc(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Bv(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Nv(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 Dv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function Hv(t){let n=Dc(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Uv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Tp=J(()=>{"use strict"});function jr(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=Uc(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=jc(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Hc(c))):d==="turn_complete"&&i()}return i(),Jv(s.join(`
15
- `),n)}function Hc(t){let e=qv(t),n=Wv(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function qv(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Wv(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of jv){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${zv(r,200)}`)}return n}function Uc(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 jc(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function zv(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Jv(t,e){if(t.length<=e)return t;let n=t.split(`
16
- `);for(;n.length>0;){let s=Ep+n.join(`
17
- `);if(s.length<=e)return s;n.shift()}return Ep}var Ep,jv,ka=J(()=>{"use strict";Ep=`[older history truncated]
18
- `,jv=["file_path","path","command","pattern","query"]});function Mp(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??Kv}`),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=Qi("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=Qi("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=Qi("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=Qi("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=Qi("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Pp(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Pp(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=Yv(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. Detail is retrievable via the hydra-recall tools if you need to look up specifics. Acknowledge briefly and wait for the next user message.)"),e.join(`
19
- `)}function Qi(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 Pp(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 Yv(t,e){if(t.length===0||e<=0)return"";let n=Vv(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 Vv(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:Uc(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=jc(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Hc(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var Kv,_p=J(()=>{"use strict";ka();Kv="(untitled)"});import*as yn from"fs/promises";async function Xi(t,e){let n=_.queueFile(t);if(e.length===0){await yn.unlink(n).catch(()=>{});return}await yn.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
12
+ sha256: ${fa(b.fingerprint)}${v}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);no(t.host,t.port,b.fingerprint),u=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 m=`${f}://${t.host}:${t.port}`,h=await n(`${m}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Of()})});if(h.status===401)throw new Error(`Wrong password for ${l}.`);if(h.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(h.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!h.ok)throw new Error(`Login to ${l} failed: HTTP ${h.status}`);let w=await h.json();if(!w.session_token||!w.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:w.session_token,expiresAt:w.expires_at,label:Of(),...u?{pinnedFingerprint:u,pinnedAt:new Date().toISOString()}:{}}),_f(t,w.session_token)}async function Yb(t,e){let n=await Vb(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Sc(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Vb(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?$f(p.subject):void 0,issuer:p?.issuer?$f(p.issuer):void 0});return}let u=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:u.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function $f(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 Gb(t,e){let n=await zn(),r=n&&dn(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 Qb(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 Of(){try{let t=Ff.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Bf(t){return t.port===an?t.host:`${t.host}:${t.port}`}var xc,tr=K(()=>{"use strict";Ne();qn();eo();gc();yc();to();qr();ro();eo();xc=class extends Error{host;port;constructor(e,n){let s=n===an?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${vn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});var z,wa=K(()=>{"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 Re}from"zod";var ap,xv,dp,cp,lp,Bc=K(()=>{"use strict";ap=Re.object({protocolVersion:Re.number().optional(),clientCapabilities:Re.record(Re.unknown()).optional(),clientInfo:Re.object({name:Re.string(),version:Re.string().optional()}).optional()}),xv=Re.enum(["full","pending_only","none","after_message"]),dp=Re.object({cwd:Re.string(),mcpServers:Re.array(Re.unknown()).optional(),_meta:Re.record(Re.unknown()).optional()}),cp=Re.object({upstreamSessionId:Re.string(),agentId:Re.string(),cwd:Re.string(),title:Re.string().optional(),agentArgs:Re.array(Re.string()).optional()}),lp=Re.object({sessionId:Re.string(),historyPolicy:xv.default("full"),afterMessageId:Re.string().optional(),clientId:Re.string().optional(),clientInfo:Re.object({name:Re.string(),version:Re.string().optional()}).optional(),_meta:Re.record(Re.unknown()).optional()})});import{z as ae}from"zod";function ba(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),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 pp(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:io(t._meta,ba(t))};return t.title!==void 0&&(e.title=t.title),e}var up,fp,Nc,PT,Cv,MT,Dc=K(()=>{"use strict";va();up=ae.object({sessionId:ae.string()}),fp=ae.object({cwd:ae.string().optional(),cursor:ae.string().optional()}),Nc=ae.object({used:ae.number().optional(),size:ae.number().optional(),costAmount:ae.number().optional(),costCurrency:ae.string().optional()}),PT=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:Nc.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(),_meta:ae.record(ae.unknown()).optional()}),Cv=ae.object({sessionId:ae.string(),cwd:ae.string(),title:ae.string().optional(),updatedAt:ae.string().optional(),_meta:ae.record(ae.unknown()).optional()}),MT=ae.object({sessions:ae.array(Cv),nextCursor:ae.string().optional()})});function Av(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 Bt(t){if(!t)return{};let e=t[mt];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=cp.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=Nc.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=Av(n.env);r!==void 0&&(s.env=r)}return s}function io(t,e){return{...t??{},[mt]:e}}var mt,va=K(()=>{"use strict";Bc();Dc();mt="hydra-acp"});import{z as Q}from"zod";var mp,Sa,hp,BT,NT,DT,gp,HT,yp,UT,wp,jT,qT,bp=K(()=>{"use strict";mp=Q.object({sessionId:Q.string(),prompt:Q.array(Q.unknown()),_meta:Q.record(Q.unknown()).optional()}),Sa=Q.object({sessionId:Q.string()}),hp=Q.object({clientId:Q.string(),name:Q.string().optional(),version:Q.string().optional()}),BT=Q.object({sessionId:Q.string(),messageId:Q.string(),originator:hp,prompt:Q.array(Q.unknown()),position:Q.number().int().nonnegative(),queueDepth:Q.number().int().positive(),enqueuedAt:Q.number()}),NT=Q.object({sessionId:Q.string(),messageId:Q.string(),prompt:Q.array(Q.unknown())}),DT=Q.object({sessionId:Q.string(),messageId:Q.string(),reason:Q.enum(["started","cancelled","abandoned"])}),gp=Q.object({sessionId:Q.string(),messageId:Q.string()}),HT=Q.object({cancelled:Q.boolean(),reason:Q.enum(["ok","not_found","already_running"])}),yp=Q.object({sessionId:Q.string(),messageId:Q.string(),prompt:Q.array(Q.unknown())}),UT=Q.object({updated:Q.boolean(),reason:Q.enum(["ok","not_found","already_running"])}),wp=Q.object({sessionId:Q.string(),targetMessageId:Q.string(),prompt:Q.array(Q.unknown()),replaceQueue:Q.boolean().optional(),onTargetCompleted:Q.enum(["reject","send_anyway"]).optional()}),jT=Q.object({amended:Q.boolean(),reason:Q.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:Q.string().optional()}),qT=Q.object({sessionId:Q.string(),cancelledMessageId:Q.string(),newMessageId:Q.string(),prompt:Q.array(Q.unknown()),originator:hp,amendedAt:Q.number()})});import{z as fs}from"zod";var vp,ka,Sp=K(()=>{"use strict";vp=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()}),ka="hydra-acp/agents/install_progress"});var It=K(()=>{"use strict";wa();Bc();va();Dc();bp();Sp()});import{nanoid as Rv}from"nanoid";var Hc,Pt,sr=K(()=>{"use strict";It();Hc=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Pt=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 Hc;let s=Rv(),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 Yr(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 Vr(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 Uc=K(()=>{"use strict"});import*as xp from"fs/promises";function Dv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var _v,$v,Gr,Ov,Fv,Lv,Bv,Nv,Ip,Ca,Cp=K(()=>{"use strict";_v=64*1024*1024,$v=1*1024*1024,Gr=64*1024,Ov=6e4,Fv=100,Lv=1e3,Bv=64*1024,Nv=256*1024,Ip=20;Ca=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??_v,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min($v,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,Gr));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}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,Gr)),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,Gr)),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,Ov));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(Dv(e.pattern),c),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Fv,Lv)),u=Math.max(1,Math.min(e.maxBytes??Bv,Nv)),p=Math.max(0,Math.min(e.contextBefore??0,Ip)),m=Math.max(0,Math.min(e.contextAfter??0,Ip)),h=[],w=[],b=[],v=0,S=!1,x=0,T=0,F=(J,B)=>{for(let Y of b)Y.remaining>0&&(Y.match.after===void 0&&(Y.match.after=[]),Y.match.after.push({cursor:J,line:B}),Y.remaining--,v+=B.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(B)!==l&&h.length<f){let Y={cursor:J,line:B};if(p>0&&w.length>0){Y.before=w.slice();for(let be of Y.before)v+=be.line.length}v+=B.length,h.push(Y),m>0&&b.push({match:Y,remaining:m})}if(p>0)for(w.push({cursor:J,line:B});w.length>p;)w.shift();let j=h.length>=f&&b.length===0,X=v>=u;return j||X};for(let J=0;J<o.length;J++){if(o[J]!==10)continue;let B=o.subarray(x,J).toString("utf8"),N=r+x;if(x=J+1,T=x,F(N,B)){S=!0;break}}if(!S&&x<o.length&&this.closed){let J=o.subarray(x).toString("utf8"),B=r+x;F(B,J)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),H={matches:h,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(H.gap=i),this.closed&&$>=this.writeCursor&&(H.eof=!0),H}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(()=>xp.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Aa,fE,Ap=K(()=>{"use strict";Aa=[{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."}],fE=new Map(Aa.map(t=>[t.verb,t]))});function Rp(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Qr(t,e){return jc(t,e.map(n=>n.modelId))}function jc(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Rp(t),s=e.filter(i=>Rp(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 Ra=K(()=>{"use strict"});function Tp(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=qc(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 f=n.get(l);f?f.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=qc(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?Uv(r,i.outIndex,Hv(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?jv(c,n.get(f)??[]):c;f!==void 0&&s.has(f)&&!qv(u)&&(u=Wv(u,s.get(f))),r.push(u);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 qc(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Hv(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Uv(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 jv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function qv(t){let n=qc(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Wv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Ep=K(()=>{"use strict"});function Xr(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=zc(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Jc(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Wc(c))):d==="turn_complete"&&i()}return i(),Vv(s.join(`
15
+ `),n)}function Wc(t){let e=Jv(t),n=Kv(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function Jv(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Kv(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of zv){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${Yv(r,200)}`)}return n}function zc(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 Jc(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function Yv(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Vv(t,e){if(t.length<=e)return t;let n=t.split(`
16
+ `);for(;n.length>0;){let s=Pp+n.join(`
17
+ `);if(s.length<=e)return s;n.shift()}return Pp}var Pp,zv,Ta=K(()=>{"use strict";Pp=`[older history truncated]
18
+ `,zv=["file_path","path","command","pattern","query"]});function _p(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??Gv}`),t.synopsis.goal!==void 0&&t.synopsis.goal.trim().length>0&&e.push(`[Goal] ${t.synopsis.goal}`),t.synopsis.outcome!==void 0&&t.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${t.synopsis.outcome}`);let n=oo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=oo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=oo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=oo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=oo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Mp(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Mp(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=Qv(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. Detail is retrievable via the hydra-recall tools if you need to look up specifics. Acknowledge briefly and wait for the next user message.)"),e.join(`
19
+ `)}function oo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
20
+ `)}`}function Mp(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 Qv(t,e){if(t.length===0||e<=0)return"";let n=Xv(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 Xv(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:zc(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=Jc(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Wc(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var Gv,$p=K(()=>{"use strict";Ta();Gv="(untitled)"});import*as In from"fs/promises";async function ao(t,e){let n=_.queueFile(t);if(e.length===0){await In.unlink(n).catch(()=>{});return}await In.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
22
22
  `)+`
23
- `;await yn.writeFile(n,s,"utf8")}async function $p(t){let e=_.queueFile(t),n;try{n=await yn.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 Op(t){let e=_.queueFile(t);await yn.unlink(e).catch(()=>{})}var qc=J(()=>{"use strict";me()});import{customAlphabet as Np}from"nanoid";import*as Up from"fs/promises";function qr(){return`m_${Hp()}`}function Ge(t){return t.startsWith(Jt)?t.slice(Jt.length):t}function Mt(t,e){return t.code=e,t}function Lp(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Zv.has(s)}function eS(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 tS(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 zr(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 Zi(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 sS(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 rS(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function iS(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 oS(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:qr()}}}function Jc(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 aS(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 dS(t){let e=cS(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=lS(t.resolver),n}function cS(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 lS(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 Wr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function zc(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Bp(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}
23
+ `;await In.writeFile(n,s,"utf8")}async function Op(t){let e=_.queueFile(t),n;try{n=await In.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 Fp(t){let e=_.queueFile(t);await In.unlink(e).catch(()=>{})}var Kc=K(()=>{"use strict";pe()});import{customAlphabet as Dp}from"nanoid";import*as jp from"fs/promises";function Zr(){return`m_${Up()}`}function Ve(t){return t.startsWith(Jt)?t.slice(Jt.length):t}function Mt(t,e){return t.code=e,t}function Bp(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&nS.has(s)}function sS(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 rS(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 iS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ti(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function co(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 oS(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 aS(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function dS(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 cS(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:Zr()}}}function Gc(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 lS(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 uS(t){let e=fS(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=pS(t.resolver),n}function fS(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 pS(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 ei(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Vc(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Np(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
25
  ${s.join(`
26
- `)}`}function Kc(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 Dp,Hp,Fp,Gv,Jt,Qv,Wc,Xv,Jr,Zv,wn=J(()=>{"use strict";Bc();xp();Cp();Sa();Tp();_p();qc();xt();Dp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hp=Np(Dp,16),Fp=Np(Dp,16),Gv=20,Jt="hydra_session_";Qv=1e3,Wc=300*1e3,Xv=64,Jr=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;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;inFlightPermissions=new Set;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??`${Jt}${Hp()}`,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.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})}this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Qv,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){rS(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_${Fp()}`,f;try{f=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 u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=c,m=i,h=new Set(n);await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.runResponseChain(m,new Set([...h,d.name]),p+1).then(()=>w()).catch(()=>w()))},Wc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:()=>w(),timer:b,transformerName:d.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(d.name)}let o=iS(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=sS(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.inFlightPermissions.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??[],f=await d({agentId:s,cwd:r,agentArgs:i,...o?{forwardedEnv:o}:{},mcpServers:l});this.accumulateAndResetCost(),this.wireAgent(f.agent),await Dr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedModel:a,agentReportedModel:f.initialModel,logger:this.logger}),await Nr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedMode:c,agentReportedMode:f.initialMode,logger:this.logger}),f.agent.connection.drainBuffered("session/update");let u=[];if(this.historyStore)try{u=await this.historyStore.load(this.sessionId)}catch(v){this.logger?.warn(`swapUpstream: historyStore.load failed: ${v.message}`)}let p=Mp({synopsis:e.artifact,title:e.title,tail:u,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[]};try{await f.agent.connection.request("session/prompt",{sessionId:f.upstreamSessionId,prompt:[{type:"text",text:p}]})}finally{this.internalPromptCapture=void 0}let m=this.upstreamSessionId,h=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let w=this.agent;this.agent=f.agent,this.upstreamSessionId=f.upstreamSessionId,this.agentMeta=f.agentMeta,this.agentCapabilities=f.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:m,...h!==void 0?{previousSummarizedThroughEntry:h}:{}})}catch(v){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${v.message}`)}await w.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:`
26
+ `)}`}function Qc(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 Hp,Up,Lp,Zv,Jt,eS,Yc,tS,ni,nS,xn=K(()=>{"use strict";Uc();Cp();Ap();Ra();Ep();$p();Kc();It();Hp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Up=Dp(Hp,16),Lp=Dp(Hp,16),Zv=20,Jt="hydra_session_";eS=1e3,Yc=300*1e3,tS=64,ni=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;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;inFlightPermissions=new Set;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??`${Jt}${Up()}`,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.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})}this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??eS,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){aS(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_${Lp()}`,f;try{f=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 u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=c,m=i,h=new Set(n);await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.runResponseChain(m,new Set([...h,d.name]),p+1).then(()=>w()).catch(()=>w()))},Yc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:()=>w(),timer:b,transformerName:d.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(d.name)}let o=dS(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=oS(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.inFlightPermissions.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??[],f=await d({agentId:s,cwd:r,agentArgs:i,...o?{forwardedEnv:o}:{},mcpServers:l});this.accumulateAndResetCost(),this.wireAgent(f.agent),await Vr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedModel:a,agentReportedModel:f.initialModel,logger:this.logger}),await Yr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedMode:c,agentReportedMode:f.initialMode,logger:this.logger}),f.agent.connection.drainBuffered("session/update");let u=[];if(this.historyStore)try{u=await this.historyStore.load(this.sessionId)}catch(v){this.logger?.warn(`swapUpstream: historyStore.load failed: ${v.message}`)}let p=_p({synopsis:e.artifact,title:e.title,tail:u,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[]};try{await f.agent.connection.request("session/prompt",{sessionId:f.upstreamSessionId,prompt:[{type:"text",text:p}]})}finally{this.internalPromptCapture=void 0}let m=this.upstreamSessionId,h=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let w=this.agent;this.agent=f.agent,this.upstreamSessionId=f.upstreamSessionId,this.agentMeta=f.agentMeta,this.agentCapabilities=f.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:m,...h!==void 0?{previousSummarizedThroughEntry:h}:{}})}catch(v){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${v.message}`)}await w.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
27
  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 Dr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Nr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Gv){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 f=c.status;(f==="completed"||f==="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)}}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 Mt(new Error("session is closed"),q.SessionNotFound);if(this.clients.has(e.clientId))throw Mt(new Error(`client ${e.clientId} is already attached`),q.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:Rp(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Lp(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Jc(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.inFlightPermissions)n.addClient(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 Mt(new Error("client not attached"),q.SessionNotFound);if(this.closing)throw Mt(new Error("session is closing; new prompts cannot be accepted"),q.SessionClosing);let r=qr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Dt((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=Wr(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:qr()};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>Xv;){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 Mt(new Error("client not attached"),q.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=qr(),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=qr(),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 Mt(new Error("client not attached"),q.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_${Fp()}`,f;try{f=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 u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??zc(e);if(u==="processing"){let p=a,m=o,h=new Set(s);return new Promise(w=>{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,m,new Set([...h,c.name]),p+1,i).then(w).catch(()=>w(i==="notification"?void 0:zc(e))))},Wc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:w,timer:b,transformerName:c.name,method:e,envelope:m,chainIdx:p,originatedBy:h,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):Wc,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:zc(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=Wr((e??{}).prompt),r=Kc(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=zr(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=zr(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=Zi(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=zr(o.options);if(c.length>0){let d=Zi(o.options),l=d.length>0?d.map(w=>({value:w.id,name:w.name??w.id})):c.map(w=>({value:w.modelId,name:w.name??w.modelId})),f=o.name,u=typeof f=="string"&&f.trim()?f.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(w=>w.id===a);if(h>=0){let w={...this.agentAdvertisedConfigOptions[h]};w.options=l,typeof p=="string"&&p.trim()&&(w.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=w}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:m,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(eS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(tS(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(va.some(f=>f.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 f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=q.InternalError,f}}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=va.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(d.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=q.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(m=>m.verb===o)){let m=r.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(m=>{d=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>d({stopReason:"cancelled",reason:m})});let f,u=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=h}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let p=f&&typeof f=="object"&&typeof f.text=="string"?f.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:`
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 Vr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Yr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Zv){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 f=c.status;(f==="completed"||f==="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)}}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 Mt(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw Mt(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:Tp(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Bp(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Gc(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.inFlightPermissions)n.addClient(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 Mt(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw Mt(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=Zr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Bt((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=ei(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:Zr()};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>tS;){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 Mt(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=Zr(),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=Zr(),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 Mt(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_${Lp()}`,f;try{f=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 u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??Vc(e);if(u==="processing"){let p=a,m=o,h=new Set(s);return new Promise(w=>{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,m,new Set([...h,c.name]),p+1,i).then(w).catch(()=>w(i==="notification"?void 0:Vc(e))))},Yc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:w,timer:b,transformerName:c.name,method:e,envelope:m,chainIdx:p,originatedBy:h,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):Yc,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:Vc(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=ei((e??{}).prompt),r=Qc(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=ti(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=ti(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=co(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=ti(o.options);if(c.length>0){let d=co(o.options),l=d.length>0?d.map(w=>({value:w.id,name:w.name??w.id})):c.map(w=>({value:w.modelId,name:w.name??w.modelId})),f=o.name,u=typeof f=="string"&&f.trim()?f.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(w=>w.id===a);if(h>=0){let w={...this.agentAdvertisedConfigOptions[h]};w.options=l,typeof p=="string"&&p.trim()&&(w.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=w}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:m,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(sS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(rS(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(",")}]`),iS(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(Aa.some(f=>f.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 f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=z.InternalError,f}}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=Aa.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(d.push(u),f.add(u))}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(m=>m.verb===o)){let m=r.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(m=>{d=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>d({stopReason:"cancelled",reason:m})});let f,u=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=h}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let p=f&&typeof f=="object"&&typeof f.text=="string"?f.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
29
  ${e}
30
30
  `},_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
31
  ${s.join(`
@@ -38,7 +38,7 @@ ${s}
38
38
  `},_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 f=l.modelId===o?"\u25B6 ":" ",u=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${f}${l.modelId}${u}`});!c&&o&&d.unshift(`\u25B6 ${o}`),a=d.join(`
39
39
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
40
40
  ${a}
41
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Ur(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(f=>f.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(f=>f.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:`
41
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Qr(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(f=>f.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(f=>f.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
42
  ${d}.
43
43
  ${l}:
44
44
  ${c.join(`
@@ -46,9 +46,9 @@ ${l}:
46
46
  `},_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 ":" ",f=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${f}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
47
47
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
48
48
  ${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 Mt(new Error(`unknown mode: ${n} (known: ${r})`),q.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:`
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 Mt(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
50
  _(no config options advertised yet)_
51
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=l.map(u=>Bp(u));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
51
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=l.map(u=>Np(u));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
52
52
  ${f.join(`
53
53
 
54
54
  `)}
@@ -58,16 +58,16 @@ ${f.join(`
58
58
  Available options:
59
59
  ${l}
60
60
  `},_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
- ${Bp(o)}
62
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=Nc(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(h=>h.toLowerCase().includes(l)),u=f.length>0?f:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
61
+ ${Np(o)}
62
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=jc(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(h=>h.toLowerCase().includes(l)),u=f.length>0?f:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
63
63
  ${p}.
64
64
  ${m}:
65
65
  ${u.join(`
66
66
  `)}
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:[]};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 Mt(new Error("/hydra agent requires an agent id"),q.InvalidParams);if(e===this.agentId)throw Mt(new Error(`already on agent ${e}`),q.InvalidParams);if(!this.spawnReplacementAgent)throw Mt(new Error("agent switching not configured for this session"),q.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 Mt(new Error("agent restart not configured for this session"),q.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 Mt(new Error("session is closing"),q.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 f=(d.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let m=Wr(f.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let h=f.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let m=f.status,h=f.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${m}`})}}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(()=>{})})}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 ba(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??Hr,Hr)),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=q.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(()=>Op(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(()=>Up.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}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.inFlightPermissions.size>0||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=!Lp(e,r),o=i?oS(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 Mt(new Error("no clients attached to handle permission request"),q.PermissionDenied);let s=this.rewriteForClient(e),r=aS(s);return new Promise((i,o)=>{let a=!1,c=[],d=0,l,f={addClient:h};this.inFlightPermissions.add(f);let u=this.sessionId,p=w=>{a||(a=!0,this.inFlightPermissions.delete(f),w())},m=w=>w?.code===q.MethodNotFound;function h(w){if(a)return;let b=w.connection.request("session/request_permission",s);c.push({client:w}),d++,b.then(v=>{d--,p(()=>{let S=dS({toolCallId:r,result:v,resolver:w});for(let A of c)A.client.clientId!==w.clientId&&A.client.connection.notify("session/update",{sessionId:u,update:S}).catch(()=>{});i(v)})}).catch(v=>{if(d--,m(v)||(l=v),d===0&&!a){let S=l??Mt(new Error("no client handled permission request"),q.PermissionDenied);p(()=>o(S))}})}for(let w of n)h(w)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:qr(),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(()=>Xi(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=Wr(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.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,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)}};Zv=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 Me}from"zod";function Wp(t){let e=t.trim();if(e.length===0)return;let n=Kr(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=Kr(e.slice(i,o+1)))}if(n===void 0){let i=Jp(e);i!==void 0&&(n=Kr(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,qp))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=eo.safeParse(s.synopsis);i.success&&uS(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function zp(t){let e=t.trim();if(e.length===0)return;let n=Kr(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=Kr(e.slice(d,l+1)))}if(n===void 0){let d=Jp(e);d!==void 0&&(n=Kr(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,qp))}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],f=Me.array(Me.string()).safeParse(l);f.success&&l.length>0&&(i[d]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Kr(t){try{return JSON.parse(t)}catch{return}}function Jp(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 uS(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 jp,eo,qp,Yc,Vc,Ia=J(()=>{"use strict";jp=Me.object({status:Me.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Me.number(),iter:Me.number().int().nonnegative().optional(),attempts:Me.number().int().nonnegative().optional(),lastError:Me.string().optional(),worker:Me.object({upstreamSessionId:Me.string(),pid:Me.number().int().nonnegative()}).optional()}),eo=Me.object({goal:Me.string().optional(),outcome:Me.string().optional(),files_touched:Me.array(Me.string()).optional(),tools_used:Me.array(Me.string()).optional(),rejected_approaches:Me.array(Me.string()).optional(),open_threads:Me.array(Me.string()).optional(),decisions:Me.array(Me.string()).optional(),file_edit_intentions:Me.array(Me.string()).optional(),unresolved_errors:Me.array(Me.string()).optional(),tool_state:Me.array(Me.string()).optional()}),qp=200,Yc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
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:[]};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 Mt(new Error("/hydra agent requires an agent id"),z.InvalidParams);if(e===this.agentId)throw Mt(new Error(`already on agent ${e}`),z.InvalidParams);if(!this.spawnReplacementAgent)throw Mt(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 Mt(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 Mt(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 f=(d.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let m=ei(f.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let h=f.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let m=f.status,h=f.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${m}`})}}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(()=>{})})}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 Ca(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??Gr,Gr)),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(()=>Fp(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(()=>jp.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}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.inFlightPermissions.size>0||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=!Bp(e,r),o=i?cS(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 Mt(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=lS(s);return new Promise((i,o)=>{let a=!1,c=[],d=0,l,f={addClient:h};this.inFlightPermissions.add(f);let u=this.sessionId,p=w=>{a||(a=!0,this.inFlightPermissions.delete(f),w())},m=w=>w?.code===z.MethodNotFound;function h(w){if(a)return;let b=w.connection.request("session/request_permission",s);c.push({client:w}),d++,b.then(v=>{d--,p(()=>{let S=uS({toolCallId:r,result:v,resolver:w});for(let x of c)x.client.clientId!==w.clientId&&x.client.connection.notify("session/update",{sessionId:u,update:S}).catch(()=>{});i(v)})}).catch(v=>{if(d--,m(v)||(l=v),d===0&&!a){let S=l??Mt(new Error("no client handled permission request"),z.PermissionDenied);p(()=>o(S))}})}for(let w of n)h(w)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Zr(),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(()=>ao(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=ei(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.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,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)}};nS=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 Te}from"zod";function zp(t){let e=t.trim();if(e.length===0)return;let n=si(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=si(e.slice(i,o+1)))}if(n===void 0){let i=Kp(e);i!==void 0&&(n=si(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,Wp))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=lo.safeParse(s.synopsis);i.success&&mS(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Jp(t){let e=t.trim();if(e.length===0)return;let n=si(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=si(e.slice(d,l+1)))}if(n===void 0){let d=Kp(e);d!==void 0&&(n=si(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,Wp))}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],f=Te.array(Te.string()).safeParse(l);f.success&&l.length>0&&(i[d]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function si(t){try{return JSON.parse(t)}catch{return}}function Kp(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 mS(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 qp,lo,Wp,Xc,Zc,Ea=K(()=>{"use strict";qp=Te.object({status:Te.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Te.number(),iter:Te.number().int().nonnegative().optional(),attempts:Te.number().int().nonnegative().optional(),lastError:Te.string().optional(),worker:Te.object({upstreamSessionId:Te.string(),pid:Te.number().int().nonnegative()}).optional()}),lo=Te.object({goal:Te.string().optional(),outcome:Te.string().optional(),files_touched:Te.array(Te.string()).optional(),tools_used:Te.array(Te.string()).optional(),rejected_approaches:Te.array(Te.string()).optional(),open_threads:Te.array(Te.string()).optional(),decisions:Te.array(Te.string()).optional(),file_edit_intentions:Te.array(Te.string()).optional(),unresolved_errors:Te.array(Te.string()).optional(),tool_state:Te.array(Te.string()).optional()}),Wp=200,Xc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
71
71
  {
72
72
  "title": "short summary, max 80 chars",
73
73
  "synopsis": {
@@ -77,7 +77,7 @@ ${m}:
77
77
  "open_threads": ["work started but not finished"]
78
78
  }
79
79
  }
80
- Use empty arrays/strings where a field doesn't apply.`;Vc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
80
+ Use empty arrays/strings where a field doesn't apply.`;Zc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
81
81
  {
82
82
  "title": "short summary, max 80 chars",
83
83
  "goal": "the user's original ask",
@@ -89,248 +89,251 @@ Use empty arrays/strings where a field doesn't apply.`;Vc=`Reply with ONLY a JSO
89
89
  "unresolved_errors": ["errors left open at session end"],
90
90
  "tool_state": ["runtime state relevant for recall"]
91
91
  }
92
- Use empty arrays/strings where a field doesn't apply.`});import*as Yr from"fs/promises";import*as EE from"path";import{customAlphabet as fS}from"nanoid";import{z as te}from"zod";function to(){return`${hS}${mS()}`}function bS(t){if(!Gc.test(t))throw new Error(`unsafe session id: ${t}`)}function tl(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,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var pS,mS,hS,Qc,Xc,gS,Zc,el,yS,wS,Gc,xa,nl=J(()=>{"use strict";me();Hs();Ia();pS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",mS=fS(pS,16),hS="hydra_lineage_";Qc=te.object({name:te.string(),description:te.string().optional()}),Xc=te.object({id:te.string(),name:te.string().optional(),description:te.string().optional()}),gS=te.object({modelId:te.string(),name:te.string().optional(),description:te.string().optional()}),Zc=te.object({used:te.number().optional(),size:te.number().optional(),costAmount:te.number().optional(),costCurrency:te.string().optional(),cumulativeCost:te.number().optional()}),el=te.object({name:te.string(),version:te.string().optional()}),yS=te.object({previousUpstreamSessionId:te.string(),previousSummarizedThroughEntry:te.number().int().nonnegative().optional()}),wS=te.object({version:te.literal(1),sessionId:te.string(),lineageId:te.string().optional(),upstreamSessionId:te.string(),importedFromSessionId:te.string().optional(),importedFromUpstreamSessionId:te.string().optional(),importedFromMachine:te.string().optional(),agentId:te.string(),cwd:te.string(),title:te.string().optional(),synopsis:eo.optional(),compactionState:jp.optional(),rollbackBreadcrumb:yS.optional(),summarizedThroughEntry:te.number().int().nonnegative().optional(),agentArgs:te.array(te.string()).optional(),currentModel:te.string().optional(),currentMode:te.string().optional(),currentUsage:Zc.optional(),agentCommands:te.array(Qc).optional(),agentModes:te.array(Xc).optional(),agentModels:te.array(gS).optional(),pendingHistorySync:te.boolean().optional(),parentSessionId:te.string().optional(),forkedFromSessionId:te.string().optional(),forkedFromMessageId:te.string().optional(),originatingClient:el.optional(),interactive:te.boolean().optional(),priority:te.number().int().nonnegative().optional(),forwardedEnv:te.record(te.string(),te.string()).optional(),createdAt:te.string(),updatedAt:te.string()}),Gc=/^[A-Za-z0-9_-]+$/;xa=class{async write(e){bS(e.sessionId);let n={version:1,...e};await Bt(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!Gc.test(e))return;let n=await zt(_.sessionFile(e));if(n!==void 0)try{return wS.parse(n)}catch{return}}async delete(e){if(Gc.test(e)){try{await Yr.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await Yr.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 Yr.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 SS}from"url";import*as no from"path";import*as Aa from"fs";function kS(){try{let t=no.dirname(SS(import.meta.url));for(let e=0;e<8;e+=1){let n=no.join(t,"package.json");if(Aa.existsSync(n)){let r=JSON.parse(Aa.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=no.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,Ks,Ht=J(()=>{"use strict";fe=kS(),Ks="hydra-acp-cat"});function sl(t){let e=new Map;for(let n of sm(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 em(t){return sl(t).map(e=>e.name)}function rl(t){let e=new Map;for(let n of sm(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 tm(t){return rl(t).map(e=>e.path)}function nm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function sm(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:Xp(i),paths:new Set},e.set(c,d)):d.toolName=Xp(i);for(let l of Zp(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 Zp(i.rawInput,i.locations))a.paths.add(c)}return e}function Xp(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Zp(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 il=J(()=>{"use strict"});import{promises as ro}from"fs";import*as ul from"path";async function io(t){let e;try{e=await ro.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return _S(e)}function _S(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 oo(t,e,n=mm){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 Ys(t,e){await ro.mkdir(ul.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await ro.writeFile(t,n.length>0?n.join(`
92
+ Use empty arrays/strings where a field doesn't apply.`});import*as ri from"fs/promises";import*as $E from"path";import{customAlphabet as hS}from"nanoid";import{z as te}from"zod";function uo(){return`${wS}${yS()}`}function kS(t){if(!el.test(t))throw new Error(`unsafe session id: ${t}`)}function il(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,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var gS,yS,wS,tl,nl,bS,sl,rl,vS,SS,el,Pa,ol=K(()=>{"use strict";pe();Qs();Ea();gS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",yS=hS(gS,16),wS="hydra_lineage_";tl=te.object({name:te.string(),description:te.string().optional()}),nl=te.object({id:te.string(),name:te.string().optional(),description:te.string().optional()}),bS=te.object({modelId:te.string(),name:te.string().optional(),description:te.string().optional()}),sl=te.object({used:te.number().optional(),size:te.number().optional(),costAmount:te.number().optional(),costCurrency:te.string().optional(),cumulativeCost:te.number().optional()}),rl=te.object({name:te.string(),version:te.string().optional()}),vS=te.object({previousUpstreamSessionId:te.string(),previousSummarizedThroughEntry:te.number().int().nonnegative().optional()}),SS=te.object({version:te.literal(1),sessionId:te.string(),lineageId:te.string().optional(),upstreamSessionId:te.string(),importedFromSessionId:te.string().optional(),importedFromUpstreamSessionId:te.string().optional(),importedFromMachine:te.string().optional(),agentId:te.string(),cwd:te.string(),title:te.string().optional(),synopsis:lo.optional(),compactionState:qp.optional(),rollbackBreadcrumb:vS.optional(),summarizedThroughEntry:te.number().int().nonnegative().optional(),agentArgs:te.array(te.string()).optional(),currentModel:te.string().optional(),currentMode:te.string().optional(),currentUsage:sl.optional(),agentCommands:te.array(tl).optional(),agentModes:te.array(nl).optional(),agentModels:te.array(bS).optional(),pendingHistorySync:te.boolean().optional(),parentSessionId:te.string().optional(),forkedFromSessionId:te.string().optional(),forkedFromMessageId:te.string().optional(),originatingClient:rl.optional(),interactive:te.boolean().optional(),priority:te.number().int().nonnegative().optional(),forwardedEnv:te.record(te.string(),te.string()).optional(),createdAt:te.string(),updatedAt:te.string()}),el=/^[A-Za-z0-9_-]+$/;Pa=class{async write(e){kS(e.sessionId);let n={version:1,...e};await Ft(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!el.test(e))return;let n=await zt(_.sessionFile(e));if(n!==void 0)try{return SS.parse(n)}catch{return}}async delete(e){if(el.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 xS}from"url";import*as fo from"path";import*as _a from"fs";function CS(){try{let t=fo.dirname(xS(import.meta.url));for(let e=0;e<8;e+=1){let n=fo.join(t,"package.json");if(_a.existsSync(n)){let r=JSON.parse(_a.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=fo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,rr,Nt=K(()=>{"use strict";fe=CS(),rr="hydra-acp-cat"});function al(t){let e=new Map;for(let n of rm(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 tm(t){return al(t).map(e=>e.name)}function dl(t){let e=new Map;for(let n of rm(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 nm(t){return dl(t).map(e=>e.path)}function sm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function rm(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:Zp(i),paths:new Set},e.set(c,d)):d.toolName=Zp(i);for(let l of em(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 em(i.rawInput,i.locations))a.paths.add(c)}return e}function Zp(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function em(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 cl=K(()=>{"use strict"});import{promises as mo}from"fs";import*as hl from"path";async function ho(t){let e;try{e=await mo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return FS(e)}function FS(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 go(t,e,n=hm){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 ir(t,e){await mo.mkdir(hl.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await mo.writeFile(t,n.length>0?n.join(`
94
94
  `)+`
95
- `:"")}async function hm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await ro.mkdir(ul.dirname(t),{recursive:!0}),await ro.appendFile(t,JSON.stringify(n)+`
96
- `,{encoding:"utf8"}))}function Ea(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function fl(t,e,n=mm){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=oo(r,o,n)))}return r}var mm,Pa=J(()=>{"use strict";mm=500});import{z as Ce}from"zod";function ao(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 sn(t){return FS.parse(t)}var $S,OS,FS,Vs=J(()=>{"use strict";nl();Ia();$S=Ce.object({method:Ce.string(),params:Ce.unknown(),recordedAt:Ce.number()}),OS=Ce.object({sessionId:Ce.string(),lineageId:Ce.string(),upstreamSessionId:Ce.string().optional(),agentId:Ce.string(),cwd:Ce.string(),title:Ce.string().optional(),synopsis:eo.optional(),summarizedThroughEntry:Ce.number().int().nonnegative().optional(),currentModel:Ce.string().optional(),currentMode:Ce.string().optional(),currentUsage:Zc.optional(),agentCommands:Ce.array(Qc).optional(),agentModes:Ce.array(Xc).optional(),interactive:Ce.boolean().optional(),originatingClient:el.optional(),priority:Ce.number().int().nonnegative().optional(),createdAt:Ce.string(),updatedAt:Ce.string()}),FS=Ce.object({version:Ce.literal(1),exportedAt:Ce.string(),exportedFrom:Ce.object({hydraVersion:Ce.string(),machine:Ce.string(),hydraHost:Ce.string().optional()}),session:OS,history:Ce.array($S),promptHistory:Ce.array(Ce.string()).optional(),toolBlobs:Ce.record(Ce.string()).optional()})});import{createHash as VS}from"crypto";function kl(t){if(Array.isArray(t))return t.map(kl);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=kl(t[n]);return e}return t}function cs(t){let{tui:e,...n}=t,s=JSON.stringify(kl(n));return VS("sha256").update(s).digest("hex").slice(0,16)}var ho=J(()=>{"use strict";He()});function Il(t){return Math.floor(t/4)}function Om(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=Il(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 Fm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var xl=J(()=>{"use strict"});function go(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Lm=J(()=>{"use strict"});import{posix as ak}from"path";import dk from"strip-ansi";function tt(t){return dk(t).replace(ck,"")}function Se(t){return tt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Sn(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 hk(n);case"agent_thought_chunk":case"agent_thought":return gk(n);case"user_message_chunk":return yk(n);case"prompt_received":return wk(n);case"tool_call":return bk(n,e);case"tool_call_update":return xk(n,e);case"plan":return Rk(n);case"current_mode_update":return Tk(n);case"current_model_update":return Ek(n);case"turn_complete":return Pk(n);case"usage_update":return mk(n);case"available_commands_update":return fk(n);case"available_modes_update":return pk(n);case"session_info_update":return uk(n);case"config_option_update":return lk(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function lk(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 uk(t){let e=ze(t,"title"),n=e!==void 0?Se(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 Ja(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:Se(r)};typeof s.description=="string"&&(i.description=Se(s.description)),e.push(i)}return e}function fk(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Ja(e)}:null}function pk(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:Se(r.id)};typeof r.name=="string"&&(i.name=Se(r.name)),typeof r.description=="string"&&(i.description=Se(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function mk(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 hk(t){let e=yo(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:go(t)}}function gk(t){let e=typeof t.text=="string"?tt(t.text):yo(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:go(t)}}function yk(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 wk(t){let e=Mk(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Dm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Bm(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 Ka(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=Bm(r.oldText),o=Bm(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 Hm(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:tt(n)}function bk(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(Dm(r)){let m=Hm(t);if(m!==null){let h=ze(t,"status"),w={kind:"exit-plan-mode",toolCallId:n,plan:m};return h!==void 0&&(w.status=h),w}}let i=qm(Se(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=Ka(t);d!==null&&(c.editDiff=d);let l=jm(t);l!==void 0&&(c.detail=l);let f=Cl(t);f!==void 0&&(c.detailFull=f);let u=Um(t);u!==void 0&&(c.locations=u);let p=go(t);return p!==void 0&&(c.workerTaskId=p),c}function Um(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function jm(t){let e=Cl(t);if(e===void 0)return;let n=Se(e),s=t.rawInput;return s&&typeof s.command=="string"?kk(n,Nm):Ik(n,Nm)}function Cl(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 tt(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 qe(Se(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 qe(Se(s))}}}function Sk(t){for(let e of vk)if(t.startsWith(e))return!0;return!1}function qm(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return qe(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 qe(o)}return Sk(t)?qe(`/${t}`):n.cwd&&n.cwd.length>0?qe(ak.resolve(n.cwd,t)):t}function kk(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Ik(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 xk(t,e={}){let n=ze(t,"toolCallId")??ze(t,"id");if(!n)return null;let s=ze(t,"title"),r=s!==void 0?qm(Se(s),t,e):void 0,i=ze(t,"status"),o=Ka(t),a=jm(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=ze(t,"name")??s;if(Dm(d)){let m={kind:"exit-plan-mode",toolCallId:n},h=Hm(t);return h!==null&&(m.plan=h),i!==void 0&&(m.status=i),m}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=Cl(t);f!==void 0&&(l.detailFull=f);let u=Um(t);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let m=Ck(t);m!==null&&(l.errorText=m),Ak(t,m)&&(l.upstreamInterrupted=!0)}let p=go(t);return p!==void 0&&(l.workerTaskId=p),l}function Ck(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 tt(s)}return null}function Ak(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 Rk(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"?Se(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 Tk(t){let e=ze(t,"currentModeId")??ze(t,"currentMode")??ze(t,"mode");return e?{kind:"mode-changed",mode:Se(e)}:null}function Ek(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:Se(e),...s&&s.length>0?{availableModels:s}:{}}}function Pk(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 tt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?tt(e.text):null}function Mk(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 ck,Nm,vk,ls=J(()=>{"use strict";me();Lm();ck=/[\x00-\x08\x0b-\x1f\x7f]/g;Nm=64;vk=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function Xr(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=$k(o);if(d.length===0)continue;let l=d;if(c!==void 0){let f=e.get(c)??[],u=[];for(let p of d)f.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(c,[...f,...u]),l=u}for(let f of l)_k(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Zr(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 _k(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 $k(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,f=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||f===void 0||e.push({path:o,oldText:l,newText:f})}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=Ka(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var Ya=J(()=>{"use strict";ls()});function kn(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:q.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 ni=J(()=>{"use strict";xt()});import{spawn as GI}from"child_process";import{setTimeout as QI}from"timers/promises";async function Rh(){let t=await Fn();if(t&&tn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function XI(t){let e=await Xs(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===cs(t)?"match":"mismatch":"missing"}async function ps(t){let e=await XI(t);if(e!=="match"){if(e==="mismatch"){let n=mn();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
- `),od(),await ad(t)}}async function id(t){let e=await Rh();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function Xs(t,e=1e3){let n=await Rh();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 od(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");GI(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function ad(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await id(t))return;await QI(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Zs=J(()=>{"use strict";Ji();ho();$r()});import{WebSocket as sx}from"ws";async function er(t,e,n=rx){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=Yi(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new sx(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 Bl(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=f=>{clearTimeout(c),o.off("open",d),i(f)};o.once("open",d),o.once("error",l)})}var rx,Bl,vo=J(()=>{"use strict";Vi();rx=1e4,Bl=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 cd from"fs/promises";function ix(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 Fn();if(t&&tn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await ye();return Fh(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Fh(t,e,n){return`${n?"https":"http"}://${ix(t)}:${e}`}async function _e(t,e={}){let n=await Ds(),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(f){if(e.rethrowNetworkError)throw f;process.stderr.write(`Could not reach daemon at ${s}: ${f.message}
95
+ `:"")}async function gm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await mo.mkdir(hl.dirname(t),{recursive:!0}),await mo.appendFile(t,JSON.stringify(n)+`
96
+ `,{encoding:"utf8"}))}function Fa(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function gl(t,e,n=hm){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=go(r,o,n)))}return r}var hm,La=K(()=>{"use strict";hm=500});import{z as xe}from"zod";function yo(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 ln(t){return NS.parse(t)}var LS,BS,NS,or=K(()=>{"use strict";ol();Ea();LS=xe.object({method:xe.string(),params:xe.unknown(),recordedAt:xe.number()}),BS=xe.object({sessionId:xe.string(),lineageId:xe.string(),upstreamSessionId:xe.string().optional(),agentId:xe.string(),cwd:xe.string(),title:xe.string().optional(),synopsis:lo.optional(),summarizedThroughEntry:xe.number().int().nonnegative().optional(),currentModel:xe.string().optional(),currentMode:xe.string().optional(),currentUsage:sl.optional(),agentCommands:xe.array(tl).optional(),agentModes:xe.array(nl).optional(),interactive:xe.boolean().optional(),originatingClient:rl.optional(),priority:xe.number().int().nonnegative().optional(),createdAt:xe.string(),updatedAt:xe.string()}),NS=xe.object({version:xe.literal(1),exportedAt:xe.string(),exportedFrom:xe.object({hydraVersion:xe.string(),machine:xe.string(),hydraHost:xe.string().optional()}),session:BS,history:xe.array(LS),promptHistory:xe.array(xe.string()).optional(),toolBlobs:xe.record(xe.string()).optional()})});import{createHash as XS}from"crypto";function Al(t){if(Array.isArray(t))return t.map(Al);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Al(t[n]);return e}return t}function gs(t){let{tui:e,...n}=t,s=JSON.stringify(Al(n));return XS("sha256").update(s).digest("hex").slice(0,16)}var xo=K(()=>{"use strict";Ne()});function Rl(t){return Math.floor(t/4)}function Fm(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=Rl(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 Lm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var Tl=K(()=>{"use strict"});function Co(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Bm=K(()=>{"use strict"});import{posix as lk}from"path";import uk from"strip-ansi";function tt(t){return uk(t).replace(fk,"")}function Ie(t){return tt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Rn(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 wk(n);case"agent_thought_chunk":case"agent_thought":return bk(n);case"user_message_chunk":return vk(n);case"prompt_received":return Sk(n);case"tool_call":return kk(n,e);case"tool_call_update":return Rk(n,e);case"plan":return Pk(n);case"current_mode_update":return Mk(n);case"current_model_update":return _k(n);case"turn_complete":return $k(n);case"usage_update":return yk(n);case"available_commands_update":return hk(n);case"available_modes_update":return gk(n);case"session_info_update":return mk(n);case"config_option_update":return pk(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function pk(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 mk(t){let e=qe(t,"title"),n=e!==void 0?Ie(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 Xa(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:Ie(r)};typeof s.description=="string"&&(i.description=Ie(s.description)),e.push(i)}return e}function hk(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Xa(e)}:null}function gk(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:Ie(r.id)};typeof r.name=="string"&&(i.name=Ie(r.name)),typeof r.description=="string"&&(i.description=Ie(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function yk(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 wk(t){let e=Ao(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Co(t)}}function bk(t){let e=typeof t.text=="string"?tt(t.text):Ao(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Co(t)}}function vk(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=Ao(t.content);return n===null?null:{kind:"user-text",text:n}}function Sk(t){let e=Ok(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Hm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Nm(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 Za(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=Nm(r.oldText),o=Nm(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 Um(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:tt(n)}function kk(t,e={}){let n=qe(t,"toolCallId")??qe(t,"id");if(!n)return null;let s=qe(t,"title")??qe(t,"name")??qe(t,"label")??"tool call",r=qe(t,"name")??qe(t,"title");if(Hm(r)){let m=Um(t);if(m!==null){let h=qe(t,"status"),w={kind:"exit-plan-mode",toolCallId:n,plan:m};return h!==void 0&&(w.status=h),w}}let i=Wm(Ie(s),t,e),o=qe(t,"status"),a=qe(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Za(t);d!==null&&(c.editDiff=d);let l=qm(t);l!==void 0&&(c.detail=l);let f=El(t);f!==void 0&&(c.detailFull=f);let u=jm(t);u!==void 0&&(c.locations=u);let p=Co(t);return p!==void 0&&(c.workerTaskId=p),c}function jm(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 qm(t){let e=El(t);if(e===void 0)return;let n=Ie(e),s=t.rawInput;return s&&typeof s.command=="string"?Ck(n,Dm):Ak(n,Dm)}function El(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 tt(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 Ue(Ie(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 Ue(Ie(s))}}}function xk(t){for(let e of Ik)if(t.startsWith(e))return!0;return!1}function Wm(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ue(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 Ue(o)}return xk(t)?Ue(`/${t}`):n.cwd&&n.cwd.length>0?Ue(lk.resolve(n.cwd,t)):t}function Ck(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Ak(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 Rk(t,e={}){let n=qe(t,"toolCallId")??qe(t,"id");if(!n)return null;let s=qe(t,"title"),r=s!==void 0?Wm(Ie(s),t,e):void 0,i=qe(t,"status"),o=Za(t),a=qm(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=qe(t,"name")??s;if(Hm(d)){let m={kind:"exit-plan-mode",toolCallId:n},h=Um(t);return h!==null&&(m.plan=h),i!==void 0&&(m.status=i),m}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=El(t);f!==void 0&&(l.detailFull=f);let u=jm(t);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let m=Tk(t);m!==null&&(l.errorText=m),Ek(t,m)&&(l.upstreamInterrupted=!0)}let p=Co(t);return p!==void 0&&(l.workerTaskId=p),l}function Tk(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Ao(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 tt(s)}return null}function Ek(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 Pk(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"?Ie(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 Mk(t){let e=qe(t,"currentModeId")??qe(t,"currentMode")??qe(t,"mode");return e?{kind:"mode-changed",mode:Ie(e)}:null}function _k(t){let e=qe(t,"currentModel")??qe(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:Ie(e),...s&&s.length>0?{availableModels:s}:{}}}function $k(t){let e=qe(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 Ao(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?tt(e.text):null}function Ok(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Ao(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function qe(t,e){let n=t[e];return typeof n=="string"?n:void 0}var fk,Dm,Ik,ys=K(()=>{"use strict";pe();Bm();fk=/[\x00-\x08\x0b-\x1f\x7f]/g;Dm=64;Ik=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function di(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=Lk(o);if(d.length===0)continue;let l=d;if(c!==void 0){let f=e.get(c)??[],u=[];for(let p of d)f.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(c,[...f,...u]),l=u}for(let f of l)Fk(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function ci(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 Fk(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 Lk(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,f=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||f===void 0||e.push({path:o,oldText:l,newText:f})}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=Za(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var ed=K(()=>{"use strict";ys()});function Tn(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 fi=K(()=>{"use strict";It()});import{spawn as ZI}from"child_process";import{setTimeout as ex}from"timers/promises";async function Th(){let t=await zn();if(t&&dn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function tx(t){let e=await cr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===gs(t)?"match":"mismatch":"missing"}async function vs(t){let e=await tx(t);if(e!=="match"){if(e==="mismatch"){let n=vn();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
+ `),fd(),await pd(t)}}async function ud(t){let e=await Th();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function cr(t,e=1e3){let n=await Th();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 fd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");ZI(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function pd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await ud(t))return;await ex(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var lr=K(()=>{"use strict";to();xo();qr()});import{WebSocket as ox}from"ws";async function ur(t,e,n=ax){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=so(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 ox(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 Ul(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=f=>{clearTimeout(c),o.off("open",d),i(f)};o.once("open",d),o.once("error",l)})}var ax,Ul,Eo=K(()=>{"use strict";ro();ax=1e4,Ul=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 hd from"fs/promises";function dx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function wi(){let t=await zn();if(t&&dn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await ye();return Lh(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Lh(t,e,n){return`${n?"https":"http"}://${dx(t)}:${e}`}async function Ee(t,e={}){let n=await Gs(),s=await wi(),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(f){if(e.rethrowNetworkError)throw f;process.stderr.write(`Could not reach daemon at ${s}: ${f.message}
98
98
  `),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 f=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(f=p)}let u=e.errorPrefix??"Daemon returned";process.stderr.write(`${u} ${f}
99
- `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function ci(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 ld(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?ox(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
99
+ `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function bi(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 gd(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?cx(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
101
101
  `),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
102
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
103
103
  `),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 ox(t){return t.split(/\s+/).filter(e=>e.length>0)}async function li(){let t=await cd.readFile(_.config(),"utf8");return JSON.parse(t)}async function Nl(t){await cd.writeFile(_.config(),JSON.stringify(t,null,2)+`
105
- `,{encoding:"utf8",mode:384})}var ms=J(()=>{"use strict";He();$n();me();$r();vo()});async function jt(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 Dl(t,n):c}finally{clearTimeout(a)}}async function In(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 jt(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})):[]}async function Lh(t,e=fetch){let n=await jt(`${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 jt(`${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 Hl(t,e=fetch){let n=await jt(`${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 ud(t,e,n={},s=fetch){let r=await jt(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},3e4,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 xn(t,e,n=fetch){let s=await jt(`${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 Bh(t,e,n,s=fetch){let r=await jt(`${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 Nh(t,e,n,s=fetch){let r=await jt(`${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 Dh(t,e,n=fetch){let s=await jt(`${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 Hh(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await jt(`${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 Uh(t,e,n=fetch){let s=await jt(`${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 fd(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 Dl,So=J(()=>{"use strict";Dl=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 Ul(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function jh(t,e){let n=t??"?",s=Ul(e);return s?`${n}${ax}${s}`:n}function qh(t){return t??"?"}function Wh(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:jl(e,n)}function jl(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var ax,ql=J(()=>{"use strict";ax="\u2022"});function zh(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(!md.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${md.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function pi(t,e=Date.now()){return{session:Ge(t.sessionId),upstream:lx(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:ux(t.status,t.busy,t.awaitingInput,cx(t.compactionState)),agent:qh(t.agentId),model:Ul(t.currentModel)??"-",age:fx(t.updatedAt,e),title:t.title??"-",cwd:qe(t.cwd),cost:Wh(t.currentUsage)}}function cx(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 lx(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function ux(t,e,n,s){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":s?"LIVE\u27F3":"LIVE"}function mi(t,e={}){let n=e.columns??ui,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]=px(fi[r],t.map(i=>i[r]));return s}function fx(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 px(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function hs(t,e,n,s={}){let r=s.columns??ui,i=s.cwdMaxWidth??dx,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,A)=>A===r.length-1?t[S]:o(S)).join(pd);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Wl.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(pd);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Wl.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),f=n-d-l*pd.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:v,i:S}of a){if(S===c)continue;let A=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(A,Math.max(0,p-1));u.set(S,T),p=Math.max(0,p-T)}u.set(c,Math.max(0,p));let m=r.length-1,h=(v,S,A)=>{if(v==="cwd")return ko(t[v],S).padEnd(S);let T=mx(t[v],S);return A?T:T.padEnd(S)},b=r.map((v,S)=>Wl.has(v)?h(v,u.get(S)??0,S===m):o(v)).join(pd);return b.length>n?b.slice(0,n):b}function mx(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function ko(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 md,ui,Wl,fi,pd,dx,hd=J(()=>{"use strict";ql();me();wn();md=["session","upstream","host","state","agent","model","age","cwd","title","cost"],ui=["session","state","age","cwd","title","agent","cost"],Wl=new Set(["cwd","title"]),fi={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},pd=" ",dx=32});import{spawn as xx}from"child_process";import{Writable as Cx}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=Ax(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??xx,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 Cx({write(l,f,u){if(!a.writable){u();return}a.write(l,m=>{if(m&&m.code!=="EPIPE"){u(m);return}u()})||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 Ax(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 zl=J(()=>{"use strict"});import Rx from"chalk";import{highlight as Tx,supportsLanguage as yd}from"cli-highlight";import bd from"string-width";function gs(t,e={}){switch(t.kind){case"user-text":{let n=Jl(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 Jl(t.text," ","agent");case"agent-thought":return Jl(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return Gx(t,e.maxPlanItems??Yx);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 Kl(t,e){return hi(t,e).styled}function hi(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=[],f=0;for(;f<t.length;){let u=t[f];if(u==="^"){a+="^^",c+=1,f+=1;continue}if(u==="*"&&t[f+1]==="*"){let p=t.indexOf("**",f+2);if(p!==-1&&p>f+2){let m=t.slice(f+2,p),h=hi(m,e),w=c;a+=`^+${h.styled}${r}`;for(let b of h.links)l.push({start:w+b.start,end:w+b.end,url:b.url});c+=h.cleanLength,h.ansi&&(d=!0),f=p+2;continue}}if(u==="`"){let p=t.indexOf("`",f+1);if(p!==-1&&p>f+1){let m=t.slice(f+1,p);a+=`${n}${m}${s}`,c+=m.length,f=p+1;continue}}if(u==="["){let p=t.indexOf("]",f+1);if(p!==-1&&t[p+1]==="("&&p>f+1){let m=-1;{let h=1,w=p+2;for(;w<t.length;){let b=t[w];if(b==="\\"&&w+1<t.length){w+=2;continue}if(b==="(")h+=1;else if(b===")"&&(h-=1,h===0)){m=w;break}w+=1}}if(m!==-1&&m>p+2){let h=t.slice(f+1,p),w=t.slice(p+2,m),b=hi(h,e),v=c,S=w.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${w}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let A of b.links)l.push({start:v+A.start,end:v+A.end,url:A.url});c+=b.cleanLength,S&&l.push({start:v,end:c,url:w}),f=m+1;continue}}}a+=u,c+=1,f+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function Ex(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 sg(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 rg(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,f="",u=[],p=i!==" ",m=(b,v,S=" ",A,T)=>{let U={prefix:S,body:b,bodyStyle:v};r!==void 0&&(U.prefixStyle=r),A&&A.length>0&&(U.links=A),T&&(U.ansi=!0),c.push(U)},h=()=>p?(p=!1,i):" ",w=()=>{if(u.length!==0){if(s){let b=og(f,u);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 u)m(b.replace(/\^/g,"^^"),n);u=[],f=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(w(),l=!1):(l=!0,f=S[1]??"");continue}if(l){u.push(v);continue}let A=v.match(/^(#{1,6})\s+(.*)$/);if(A){let N=A[1].length,F=A[2]??"",H=s?N===1?"heading-1":N===2?"heading-2":"heading-3":n,Z=s?sg(H):o;m(Kl(F,Z),H,h());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&Px(T)&&Io(v).length===Io(T).length){let N=Io(v),F=[],H=b+2;for(;H<d.length&&d[H].includes("|");)F.push(Io(d[H])),H++;let Z=Bx(N,F,a);for(let G of Z)r!==void 0&&(G.prefixStyle=r),c.push(G);b=H-1;continue}let U=v.match(/^(\s*)[-*+]\s+(.*)$/);if(U){let N=U[1]??"",F=U[2]??"",H=hi(F,o),Z=N.length+2,G=H.links.map(re=>({start:re.start+Z,end:re.end+Z,url:re.url}));m(`${N}\u2022 ${H.styled}`,n,h(),G,H.ansi);continue}let O=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if(O){let N=O[1]??"",F=O[2]??"",H=O[3]??"",Z=hi(H,o),G=N.length+F.length+2,re=Z.links.map(Y=>({start:Y.start+G,end:Y.end+G,url:Y.url}));m(`${N}${F}. ${Z.styled}`,n,h(),re,Z.ansi);continue}let z=v.trim()==="",V=hi(v,o);m(V.styled,n,z?" ":h(),V.links,V.ansi)}for(l&&w();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function ys(t,e){return rg(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function gi(t){return rg(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Io(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 Px(t){if(!t.includes("|"))return!1;let e=Io(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function wd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return bd(e)}function $x(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:bd(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:wd(r)}),n=i}return e}function Ox(t,e){let n=[],s="",r=0;for(let i of t){let o=bd(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 Fx(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=Ox(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=bd(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 Lx(t,e){let n=t.length;if(t.reduce((l,f)=>l+f,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,ig)),i=r.reduce((l,f)=>l+f,0);if(i>=e)return r;let o=e-i,a=t.map((l,f)=>({i:f,slack:Math.max(0,l-r[f])})).filter(l=>l.slack>0),c=a.reduce((l,f)=>l+f.slack,0);if(c===0)return r;for(let l of a){let f=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let d=e-i;for(;d>0;){let l=-1,f=0;for(let u=0;u<n;u++){let p=t[u]-r[u];p>f&&(f=p,l=u)}if(l<0)break;r[l]=r[l]+1,d--}return r}function Bx(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=wd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let f=d[l]??"",u=wd(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let d=Math.max(s*ig,n-Mx-(s-1)*_x);i=Lx(r,d)}let o=(d,l,f)=>{let u=[],p=1;for(let h=0;h<s;h++){let w=d[h]??"",b=i[h],v=Fx($x(w),b);u.push(v),v.length>p&&(p=v.length)}let m=[];for(let h=0;h<p;h++){let w=[];for(let b=0;b<s;b++){let v=u[b][h]??"",S=i[b],A=wd(v),T=Kl(v,f);w.push(T+" ".repeat(Math.max(0,S-A)))}m.push({prefix:" ",body:w.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...o(t,"heading-3",sg("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 og(t,e){if(t.length===0||!yd(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=Tx(e.join(`
109
- `),{language:t,theme:Nx,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 Hx(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return yd("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return yd("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=Dx[s];return r&&yd(r)?r:""}function Jl(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 Ux(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Cn(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 ag(t){if(t.length<=4096&&t.split(`
104
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function cx(t){return t.split(/\s+/).filter(e=>e.length>0)}async function vi(){let t=await hd.readFile(_.config(),"utf8");return JSON.parse(t)}async function jl(t){await hd.writeFile(_.config(),JSON.stringify(t,null,2)+`
105
+ `,{encoding:"utf8",mode:384})}var Ss=K(()=>{"use strict";Ne();qn();pe();qr();Eo()});async function Ht(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 ql(t,n):c}finally{clearTimeout(a)}}async function En(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 Ht(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})):[]}async function Bh(t,e=fetch){let n=await Ht(`${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 Ht(`${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 Wl(t,e=fetch){let n=await Ht(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function yd(t,e,n={},s=fetch){let r=await Ht(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},3e4,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 Pn(t,e,n=fetch){let s=await Ht(`${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 Nh(t,e,n,s=fetch){let r=await Ht(`${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 Dh(t,e,n,s=fetch){let r=await Ht(`${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 Hh(t,e,n=fetch){let s=await Ht(`${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 Uh(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await Ht(`${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 jh(t,e,n=fetch){let s=await Ht(`${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 wd(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 ql,Po=K(()=>{"use strict";ql=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 zl(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function qh(t,e){let n=t??"?",s=zl(e);return s?`${n}${lx}${s}`:n}function Wh(t){return t??"?"}function zh(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Jl(e,n)}function Jl(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var lx,Kl=K(()=>{"use strict";lx="\u2022"});function Jh(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 Ii(t,e=Date.now()){return{session:Ve(t.sessionId),upstream:px(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:mx(t.status,t.busy,t.awaitingInput,fx(t.compactionState)),agent:Wh(t.agentId),model:zl(t.currentModel)??"-",age:hx(t.updatedAt,e),title:t.title??"-",cwd:Ue(t.cwd),cost:zh(t.currentUsage)}}function fx(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 px(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function mx(t,e,n,s){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":s?"LIVE\u27F3":"LIVE"}function xi(t,e={}){let n=e.columns??Si,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]=gx(ki[r],t.map(i=>i[r]));return s}function hx(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 gx(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function ks(t,e,n,s={}){let r=s.columns??Si,i=s.cwdMaxWidth??ux,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(bd);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Yl.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(bd);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Yl.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),f=n-d-l*bd.length;f<0&&(f=0);let u=new Map,p=f;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));u.set(S,T),p=Math.max(0,p-T)}u.set(c,Math.max(0,p));let m=r.length-1,h=(v,S,x)=>{if(v==="cwd")return Mo(t[v],S).padEnd(S);let T=yx(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>Yl.has(v)?h(v,u.get(S)??0,S===m):o(v)).join(bd);return b.length>n?b.slice(0,n):b}function yx(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function Mo(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,Si,Yl,ki,bd,ux,Sd=K(()=>{"use strict";Kl();pe();xn();vd=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Si=["session","state","age","cwd","title","agent","cost"],Yl=new Set(["cwd","title"]),ki={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},bd=" ",ux=32});import{spawn as Rx}from"child_process";import{Writable as Tx}from"stream";function kd(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=Ex(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??Rx,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 Tx({write(l,f,u){if(!a.writable){u();return}a.write(l,m=>{if(m&&m.code!=="EPIPE"){u(m);return}u()})||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 Ex(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 Vl=K(()=>{"use strict"});import Px from"chalk";import{highlight as Mx,supportsLanguage as Id}from"cli-highlight";import Cd from"string-width";function Is(t,e={}){switch(t.kind){case"user-text":{let n=Gl(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 Gl(t.text," ","agent");case"agent-thought":return Gl(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return Zx(t,e.maxPlanItems??Qx);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 Ql(t,e){return Ci(t,e).styled}function Ci(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=[],f=0;for(;f<t.length;){let u=t[f];if(u==="^"){a+="^^",c+=1,f+=1;continue}if(u==="*"&&t[f+1]==="*"){let p=t.indexOf("**",f+2);if(p!==-1&&p>f+2){let m=t.slice(f+2,p),h=Ci(m,e),w=c;a+=`^+${h.styled}${r}`;for(let b of h.links)l.push({start:w+b.start,end:w+b.end,url:b.url});c+=h.cleanLength,h.ansi&&(d=!0),f=p+2;continue}}if(u==="`"){let p=t.indexOf("`",f+1);if(p!==-1&&p>f+1){let m=t.slice(f+1,p);a+=`${n}${m}${s}`,c+=m.length,f=p+1;continue}}if(u==="["){let p=t.indexOf("]",f+1);if(p!==-1&&t[p+1]==="("&&p>f+1){let m=-1;{let h=1,w=p+2;for(;w<t.length;){let b=t[w];if(b==="\\"&&w+1<t.length){w+=2;continue}if(b==="(")h+=1;else if(b===")"&&(h-=1,h===0)){m=w;break}w+=1}}if(m!==-1&&m>p+2){let h=t.slice(f+1,p),w=t.slice(p+2,m),b=Ci(h,e),v=c,S=w.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${w}\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:w}),f=m+1;continue}}}a+=u,c+=1,f+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function _x(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 rg(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 ig(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,f="",u=[],p=i!==" ",m=(b,v,S=" ",x,T)=>{let F={prefix:S,body:b,bodyStyle:v};r!==void 0&&(F.prefixStyle=r),x&&x.length>0&&(F.links=x),T&&(F.ansi=!0),c.push(F)},h=()=>p?(p=!1,i):" ",w=()=>{if(u.length!==0){if(s){let b=ag(f,u);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 u)m(b.replace(/\^/g,"^^"),n);u=[],f=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(w(),l=!1):(l=!0,f=S[1]??"");continue}if(l){u.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let B=x[1].length,N=x[2]??"",j=s?B===1?"heading-1":B===2?"heading-2":"heading-3":n,X=s?rg(j):o;m(Ql(N,X),j,h());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&$x(T)&&_o(v).length===_o(T).length){let B=_o(v),N=[],j=b+2;for(;j<d.length&&d[j].includes("|");)N.push(_o(d[j])),j++;let X=Hx(B,N,a);for(let Y of X)r!==void 0&&(Y.prefixStyle=r),c.push(Y);b=j-1;continue}let F=v.match(/^(\s*)[-*+]\s+(.*)$/);if(F){let B=F[1]??"",N=F[2]??"",j=Ci(N,o),X=B.length+2,Y=j.links.map(be=>({start:be.start+X,end:be.end+X,url:be.url}));m(`${B}\u2022 ${j.styled}`,n,h(),Y,j.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let B=$[1]??"",N=$[2]??"",j=$[3]??"",X=Ci(j,o),Y=B.length+N.length+2,be=X.links.map(V=>({start:V.start+Y,end:V.end+Y,url:V.url}));m(`${B}${N}. ${X.styled}`,n,h(),be,X.ansi);continue}let H=v.trim()==="",J=Ci(v,o);m(J.styled,n,H?" ":h(),J.links,J.ansi)}for(l&&w();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function xs(t,e){return ig(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Ai(t){return ig(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function _o(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 $x(t){if(!t.includes("|"))return!1;let e=_o(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function xd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Cd(e)}function Lx(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:Cd(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:xd(r)}),n=i}return e}function Bx(t,e){let n=[],s="",r=0;for(let i of t){let o=Cd(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 Nx(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=Bx(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=Cd(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 Dx(t,e){let n=t.length;if(t.reduce((l,f)=>l+f,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,og)),i=r.reduce((l,f)=>l+f,0);if(i>=e)return r;let o=e-i,a=t.map((l,f)=>({i:f,slack:Math.max(0,l-r[f])})).filter(l=>l.slack>0),c=a.reduce((l,f)=>l+f.slack,0);if(c===0)return r;for(let l of a){let f=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let d=e-i;for(;d>0;){let l=-1,f=0;for(let u=0;u<n;u++){let p=t[u]-r[u];p>f&&(f=p,l=u)}if(l<0)break;r[l]=r[l]+1,d--}return r}function Hx(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=xd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let f=d[l]??"",u=xd(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let d=Math.max(s*og,n-Ox-(s-1)*Fx);i=Dx(r,d)}let o=(d,l,f)=>{let u=[],p=1;for(let h=0;h<s;h++){let w=d[h]??"",b=i[h],v=Nx(Lx(w),b);u.push(v),v.length>p&&(p=v.length)}let m=[];for(let h=0;h<p;h++){let w=[];for(let b=0;b<s;b++){let v=u[b][h]??"",S=i[b],x=xd(v),T=Ql(v,f);w.push(T+" ".repeat(Math.max(0,S-x)))}m.push({prefix:" ",body:w.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...o(t,"heading-3",rg("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 ag(t,e){if(t.length===0||!Id(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=Mx(e.join(`
109
+ `),{language:t,theme:Ux,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 qx(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Id("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Id("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=jx[s];return r&&Id(r)?r:""}function Gl(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 Wx(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Mn(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 dg(t){if(t.length<=4096&&t.split(`
112
112
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
113
113
  `);return i.length>40&&(s=i.slice(0,40).join(`
114
- `),r=!0),{text:s,truncated:r}}function xo(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,f=o.toLowerCase(),u=l.toLowerCase();(u.startsWith(`${f} `)||u.startsWith(`${f} `))&&(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 m=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let h=t.locations?.[0]?.path??t.detailFull??"";(h.startsWith("/")||h.startsWith("~"))&&a.push({start:m,end:m+l.length,url:h})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Cn(l-t.startedAt)}`}let c={prefix:` ${zx(t.status)} `,prefixStyle:Jx(t.status),body:o,bodyStyle:Qx(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Se(t.errorText),bodyStyle:"tool-status-fail"}),d}function dg(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
115
- `))e.push({prefix:" ",body:Se(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Se(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
116
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=Hx(r);if(i.length>0){let o=og(i,s.map(a=>Se(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:Se(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function lg(t){cg=t>=0?t:0}function Yl(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=` (~${Ux(d)})`}else{let d=qx(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 ${Se(qe(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=Vl(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...ys(c)),s.length>0&&s.unshift({body:""}),s}function ug(t){let e=tt(t.oldText).split(`
114
+ `),r=!0),{text:s,truncated:r}}function $o(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,f=o.toLowerCase(),u=l.toLowerCase();(u.startsWith(`${f} `)||u.startsWith(`${f} `))&&(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 m=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let h=t.locations?.[0]?.path??t.detailFull??"";(h.startsWith("/")||h.startsWith("~"))&&a.push({start:m,end:m+l.length,url:h})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Mn(l-t.startedAt)}`}let c={prefix:` ${Yx(t.status)} `,prefixStyle:Vx(t.status),body:o,bodyStyle:eC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Ie(t.errorText),bodyStyle:"tool-status-fail"}),d}function cg(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
115
+ `))e.push({prefix:" ",body:Ie(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Ie(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
116
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=qx(r);if(i.length>0){let o=ag(i,s.map(a=>Ie(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:Ie(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function ug(t){lg=t>=0?t:0}function Xl(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=` (~${Wx(d)})`}else{let d=Jx(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 ${Ie(Ue(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=Zl(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(...xs(c)),s.length>0&&s.unshift({body:""}),s}function fg(t){let e=tt(t.oldText).split(`
117
117
  `),n=tt(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 qx(t){let{oldLines:e,newLines:n}=ug(t),s=0,r=0;for(let i of fg(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function ng(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Vl(t,e={}){let n=e.maxLines??jx,s=e.contextLines??cg,{oldLines:r,newLines:i}=ug(t),o=fg(r,i),a=[];if(Number.isFinite(s)){if(!o.some(u=>u.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let u=0;u<o.length;u++)if(o[u].op!=="="){let p=Math.max(0,u-s),m=Math.min(o.length-1,u+s);for(let h=p;h<=m;h++)l[h]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push(ng(o[f])),f++;continue}let u=f;for(;u<o.length&&!l[u];)u++;let p=u-f;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),f=u}}else for(let d of o)a.push(ng(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let f=a.length-d;c.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}c.push(a[d])}return c.join(`
119
- `)}function fg(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(...Wx(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 Wx(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 Gl(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function zx(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 Jx(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 pg(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...ys(t.plan));let n=t.status;if(n!==void 0){let s=Kx(n);s!==null&&e.push(s)}return e}function Kx(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 Vx(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 Gx(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}=Vx(t.entries,e),l=d-c<a,f="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let m=a-p;f=m===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${m} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=c;p<d;p++){let m=t.entries[p];if(!m)continue;let h=m.status??"pending",w=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",b=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=m.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Kl(v,Ex(b));u.push({prefix:" ",body:`${w} ${S}`,bodyStyle:b})}return u}function Qx(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 ig,Mx,_x,Je,Nx,Dx,jx,cg,Yx,yi=J(()=>{"use strict";me();ls();ig=6,Mx=2,_x=3;Je=new Rx.Instance({level:3}),Nx={keyword:Je.blueBright,built_in:Je.cyan,type:Je.cyanBright,literal:Je.blue,number:Je.greenBright,string:Je.yellow,regexp:Je.red,comment:Je.gray,function:Je.yellow,title:Je.yellow,class:Je.yellowBright,attr:Je.cyan,attribute:Je.cyan,variable:Je.white,params:Je.white,meta:Je.magenta,symbol:Je.magenta,addition:Je.greenBright,deletion:Je.redBright,section:Je.cyan,tag:Je.cyan,name:Je.cyanBright};Dx={".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"};jx=40,cg=Number.POSITIVE_INFINITY;Yx=5});import{highlight as Xx,supportsLanguage as Zx}from"cli-highlight";async function hg(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=sn(d)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
121
- `),process.exit(1)}let f=Xr(l.history);r=e.fold===!0?f.map(u=>({...u,hunks:Zr(u.hunks)})):f}else process.stderr.write(`Daemon returned HTTP ${s.status}
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 Jx(t){let{oldLines:e,newLines:n}=fg(t),s=0,r=0;for(let i of pg(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function sg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Zl(t,e={}){let n=e.maxLines??zx,s=e.contextLines??lg,{oldLines:r,newLines:i}=fg(t),o=pg(r,i),a=[];if(Number.isFinite(s)){if(!o.some(u=>u.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let u=0;u<o.length;u++)if(o[u].op!=="="){let p=Math.max(0,u-s),m=Math.min(o.length-1,u+s);for(let h=p;h<=m;h++)l[h]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push(sg(o[f])),f++;continue}let u=f;for(;u<o.length&&!l[u];)u++;let p=u-f;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),f=u}}else for(let d of o)a.push(sg(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let f=a.length-d;c.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}c.push(a[d])}return c.join(`
119
+ `)}function pg(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(...Kx(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 Kx(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 eu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function Yx(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 Vx(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 mg(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...xs(t.plan));let n=t.status;if(n!==void 0){let s=Gx(n);s!==null&&e.push(s)}return e}function Gx(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 Xx(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 Zx(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}=Xx(t.entries,e),l=d-c<a,f="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let m=a-p;f=m===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${m} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=c;p<d;p++){let m=t.entries[p];if(!m)continue;let h=m.status??"pending",w=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",b=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=m.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Ql(v,_x(b));u.push({prefix:" ",body:`${w} ${S}`,bodyStyle:b})}return u}function eC(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 og,Ox,Fx,We,Ux,jx,zx,lg,Qx,Ri=K(()=>{"use strict";pe();ys();og=6,Ox=2,Fx=3;We=new Px.Instance({level:3}),Ux={keyword:We.blueBright,built_in:We.cyan,type:We.cyanBright,literal:We.blue,number:We.greenBright,string:We.yellow,regexp:We.red,comment:We.gray,function:We.yellow,title:We.yellow,class:We.yellowBright,attr:We.cyan,attribute:We.cyan,variable:We.white,params:We.white,meta:We.magenta,symbol:We.magenta,addition:We.greenBright,deletion:We.redBright,section:We.cyan,tag:We.cyan,name:We.cyanBright};jx={".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"};zx=40,lg=Number.POSITIVE_INFINITY;Qx=5});import{highlight as tC,supportsLanguage as nC}from"cli-highlight";async function gg(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 Ee(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Ee(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=ln(d)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
121
+ `),process.exit(1)}let f=di(l.history);r=e.fold===!0?f.map(u=>({...u,hunks:ci(u.hunks)})):f}else process.stderr.write(`Daemon returned HTTP ${s.status}
122
122
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
123
- `);return}let i=gd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(Ql(r,a)),await i.flush()}function Ql(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=nC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
125
- `:n.join("")}function eC(t){let e=[];for(let n of t.hunks){let s=Vl(n,{maxLines:1/0});tC(s)&&e.push({body:s,oldCount:mg(n.oldText),newCount:mg(n.newText)})}return e}function tC(t){if(t.length===0)return!1;for(let e of t.split(`
126
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function nC(t,e){let n=eC(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(`
123
+ `);return}let i=kd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(tu(r,a)),await i.flush()}function tu(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=iC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
125
+ `:n.join("")}function sC(t){let e=[];for(let n of t.hunks){let s=Zl(n,{maxLines:1/0});rC(s)&&e.push({body:s,oldCount:hg(n.oldText),newCount:hg(n.newText)})}return e}function rC(t){if(t.length===0)return!1;for(let e of t.split(`
126
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function iC(t,e){let n=sC(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
127
  `)+`
128
128
 
129
- `;return!e||!Zx("diff")?i:Xx(i,{language:"diff"})}function mg(t){if(t.length===0)return 0;let e=t.split(`
130
- `);return e[e.length-1]===""&&e.pop(),e.length}var Xl=J(()=>{"use strict";ms();Vs();Ya();yi();zl()});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=sn(i)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
132
- `),process.exit(1)}let a=tu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let u=Xr(o.history);d=e.fold===!0?u.map(p=>({...p,hunks:Zr(p.hunks)})):u}if(e.json){let u={...a};d!==null&&(u.diff=d),process.stdout.write(JSON.stringify(u,null,2)+`
133
- `);return}let l=process.stdout.isTTY===!0,f=!e.noColor&&l;if(c){let u=gd({disabled:e.noPager===!0});u.stream.write(vd(a,e.verbose===!0)),u.stream.write(`
134
- `),u.stream.write(Ql(d??[],f)),await u.flush();return}process.stdout.write(vd(a,e.verbose===!0))}function tu(t,e){let n=t.session,s=t.history,r=nm(s),i=sl(s),o=rl(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 vd(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:")}${rC(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,f)=>l+f.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,Zl),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>Zl&&n.push(` ... ${t.tools.length-Zl} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>sC.has(l.name)),d=c.reduce((l,f)=>l+f.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,eu),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>eu&&n.push(` ... ${o.length-eu} more (use --verbose to see all)`)}return n.join(`
129
+ `;return!e||!nC("diff")?i:tC(i,{language:"diff"})}function hg(t){if(t.length===0)return 0;let e=t.split(`
130
+ `);return e[e.length-1]===""&&e.pop(),e.length}var nu=K(()=>{"use strict";Ss();or();ed();Ri();Vl()});async function yg(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 Ee(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Ee(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=ln(i)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
132
+ `),process.exit(1)}let a=iu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let u=di(o.history);d=e.fold===!0?u.map(p=>({...p,hunks:ci(p.hunks)})):u}if(e.json){let u={...a};d!==null&&(u.diff=d),process.stdout.write(JSON.stringify(u,null,2)+`
133
+ `);return}let l=process.stdout.isTTY===!0,f=!e.noColor&&l;if(c){let u=kd({disabled:e.noPager===!0});u.stream.write(Ad(a,e.verbose===!0)),u.stream.write(`
134
+ `),u.stream.write(tu(d??[],f)),await u.flush();return}process.stdout.write(Ad(a,e.verbose===!0))}function iu(t,e){let n=t.session,s=t.history,r=sm(s),i=al(s),o=dl(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 Ad(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:")}${aC(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,f)=>l+f.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,su),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>su&&n.push(` ... ${t.tools.length-su} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>oC.has(l.name)),d=c.reduce((l,f)=>l+f.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,ru),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>ru&&n.push(` ... ${o.length-ru} more (use --verbose to see all)`)}return n.join(`
135
135
  `)+`
136
- `}function rC(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 Zl,eu,sC,nu=J(()=>{"use strict";ms();Vs();il();Ya();zl();Xl();Zl=10,eu=15,sC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Id,Nn,bi,Co,qg,Ao,au,xd,sr,Wg,rr,zg,ir,Jg,or,vi,Si,Kg,ki,Yg,Vg,Gg,du,Qg,Cd,Xg,Zg,Ro=J(()=>{"use strict";Id="\x1B[?2004h",Nn="\x1B[?2004l",bi="\x1B[200~",Co="\x1B[201~",qg="\x1B[?1049l",Ao="\x1B[?7h",au="\x1B[?7l",xd="\x1B[?25h",sr="\x1B[?1l",Wg="\x1B[>1u",rr="\x1B[<u",zg="\x1B[>4;2m",ir="\x1B[>4;0m",Jg="\x1B[>5;1m",or="\x1B[>5;0m",vi="\x1B[?1000l",Si="\x1B[?1002l",Kg="\x1B[?1003l",ki="\x1B[?1006l",Yg="\x1B[?1015l",Vg="\x1B[?w",Gg="\x1B[=24;1w",du="\x1B[=0;0w",Qg="\x1B]22;pointer\x07",Cd="\x1B]22;default\x07",Xg="\x1B[?2026h",Zg="\x1B[?2026l"});function Dn(){process.stdout.write(rr),process.stdout.write(Nn),process.stdout.write(ir),process.stdout.write(or),process.stdout.write(vi),process.stdout.write(Si),process.stdout.write(ki),process.stdout.write(sr),process.stdout.write("\x1B>")}function on(t){return t.width??80}function ar(t){return t.height??24}function Hn(t,e){let n=on(t),s=ar(t),r=e.contentWidth??oC,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),f=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u=ey.repeat(a-2),p=uC(u,e.title);t.moveTo(l,f),t.dim.noFormat(aC),fC(t,p),t.dim.noFormat(dC);for(let m=1;m<=c;m++)t.moveTo(l,f+m),t.dim.noFormat(ty),t.moveTo(l+a-1,f+m),t.dim.noFormat(ty);return t.moveTo(l,f+d-1),t.dim.noFormat(cC+ey.repeat(a-2)+lC),{x:l,y:f,w:a,h:d,contentX:l+1,contentY:f+1,contentW:o,contentH:c}}function uC(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 fC(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 nt(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function Ad(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function ws(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=(u,p,m)=>{a||s(u,p,m,f)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},f=u=>{l(),o(u)};e.grabInput({}),e.on("key",d),e.on("resize",c)})}var oC,ey,ty,aC,dC,cC,lC,xi=J(()=>{"use strict";Ro();oC=64,ey="\u2500",ty="\u2502",aC="\u250C",dC="\u2510",cC="\u2514",lC="\u2518"});function ny(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 hC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??pC,footer:mC};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}] ${ny(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 gC(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 yC(t){return typeof t!="object"||t===null?!1:t.code===q.AuthRequired}function sy(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[pt];if(!(typeof s!="object"||s===null))return s}function wC(t){let e=sy(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function bC(t){let e=sy(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 ry(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!yC(e))throw e;let n=wC(e)??t.fallbackAgentId??"",s=bC(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 vC(t,e,n){t.grabInput(!1),Dn(),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+`
136
+ `}function aC(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 su,ru,oC,ou=K(()=>{"use strict";Ss();or();cl();ed();Vl();nu();su=10,ru=15,oC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Ed,Yn,Ei,Oo,Wg,Fo,uu,Pd,mr,zg,hr,Jg,gr,Kg,yr,Pi,Mi,Yg,_i,Vg,Gg,Qg,fu,Xg,Md,Zg,ey,Lo=K(()=>{"use strict";Ed="\x1B[?2004h",Yn="\x1B[?2004l",Ei="\x1B[200~",Oo="\x1B[201~",Wg="\x1B[?1049l",Fo="\x1B[?7h",uu="\x1B[?7l",Pd="\x1B[?25h",mr="\x1B[?1l",zg="\x1B[>1u",hr="\x1B[<u",Jg="\x1B[>4;2m",gr="\x1B[>4;0m",Kg="\x1B[>5;1m",yr="\x1B[>5;0m",Pi="\x1B[?1000l",Mi="\x1B[?1002l",Yg="\x1B[?1003l",_i="\x1B[?1006l",Vg="\x1B[?1015l",Gg="\x1B[?w",Qg="\x1B[=24;1w",fu="\x1B[=0;0w",Xg="\x1B]22;pointer\x07",Md="\x1B]22;default\x07",Zg="\x1B[?2026h",ey="\x1B[?2026l"});function Vn(){process.stdout.write(hr),process.stdout.write(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(Pi),process.stdout.write(Mi),process.stdout.write(_i),process.stdout.write(mr),process.stdout.write("\x1B>")}function fn(t){return t.width??80}function wr(t){return t.height??24}function Gn(t,e){let n=fn(t),s=wr(t),r=e.contentWidth??cC,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),f=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u=ty.repeat(a-2),p=mC(u,e.title);t.moveTo(l,f),t.dim.noFormat(lC),hC(t,p),t.dim.noFormat(uC);for(let m=1;m<=c;m++)t.moveTo(l,f+m),t.dim.noFormat(ny),t.moveTo(l+a-1,f+m),t.dim.noFormat(ny);return t.moveTo(l,f+d-1),t.dim.noFormat(fC+ty.repeat(a-2)+pC),{x:l,y:f,w:a,h:d,contentX:l+1,contentY:f+1,contentW:o,contentH:c}}function mC(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 hC(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 nt(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function _d(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Cs(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=(u,p,m)=>{a||s(u,p,m,f)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},f=u=>{l(),o(u)};e.grabInput({}),e.on("key",d),e.on("resize",c)})}var cC,ty,ny,lC,uC,fC,pC,Oi=K(()=>{"use strict";Lo();cC=64,ty="\u2500",ny="\u2502",lC="\u250C",uC="\u2510",fC="\u2514",pC="\u2518"});function sy(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 wC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??gC,footer:yC};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}] ${sy(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 bC(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 vC(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function ry(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[mt];if(!(typeof s!="object"||s===null))return s}function SC(t){let e=ry(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function kC(t){let e=ry(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 iy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!vC(e))throw e;let n=SC(e)??t.fallbackAgentId??"",s=kC(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 IC(t,e,n){t.grabInput(!1),Vn(),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
137
  `);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
138
  failed to spawn ${e.command}: ${c.message}
139
139
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
140
140
  failed to spawn ${e.command}: ${a.message}
141
- `),i({exitCode:-1})}})}function SC(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 cu(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(SC(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 iy(t,e,n,s,r){Dn();let i=hC(e,n,s),o=!1,a,c,d=()=>{let f=4;i.command&&f++,i.url&&f++,i.methodLines&&(f+=1+i.methodLines.length),a&&f++,c&&f++;let u=Hn(t,{contentHeight:f,contentWidth:80,title:"Authentication required"}),p=u.contentW,m=0;if(a&&(t.moveTo(u.contentX,u.contentY+m),t.brightYellow.noFormat(nt(` ${a}`,p)),m++),c&&(t.moveTo(u.contentX,u.contentY+m),t.brightRed.noFormat(nt(` ${c}`,p)),m++),t.moveTo(u.contentX,u.contentY+m),t.brightWhite.bold.noFormat(nt(` ${i.title}`,p)),m+=2,t.moveTo(u.contentX,u.contentY+m),t.noFormat(nt(` ${i.description}`,p)),m++,i.command&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(nt(i.command,p-7)),m++),i.url&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(nt(i.url,p-7)),m++),i.methodLines){t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Methods reported by the agent:"),m++;for(let h of i.methodLines)t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" "),t.noFormat(nt(h.label,p-3)),m++}return m++,t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(` ${i.footer}`),u},l=i.methodLines?.length??0;return ws({term:t,render:()=>{d()},onKey:(f,u,p,m)=>{if(o)return;let h=gC(f,p,l);if(h.kind!=="ignore"){if(h.kind==="retry"||h.kind==="back"||h.kind==="cancel"){m(h.kind);return}if(h.kind==="selectMethod"){let w=i.methodLines?.[h.index]?.method;if(!w||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${ny(w)}\u2026`,d();let b=r.runTerminalAuth??(v=>vC(t,v));(async()=>{let v=await cu(w,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){m("terminal-completed");return}if(v.kind==="retry"){m("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 pC,mC,lu=J(()=>{"use strict";fa();ma();xi();pC="This agent requires authentication before use.",mC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as ly}from"timers/promises";function PC(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var AC,RC,TC,EC,Ci,uu=J(()=>{"use strict";vo();ni();AC=200,RC=5e3,TC=2,EC=60,Ci=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(()=>{}),ly(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=AC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await er(s,this.opts.subprotocols);this.bindStream(kn(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>=EC)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 ly(n),this.destroyed)return;n=Math.min(n*TC,RC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(PC(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 uy(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:uy(t,["allow_once","allow_always"])}}}function fy(t){return{outcome:{outcome:"selected",optionId:uy(t,["reject_once","reject_always"])}}}function Ed(t){return t&&typeof t=="object"?t:void 0}function To(t){return typeof t=="string"&&t.length>0?t:void 0}function py(t){let e=Ed(t),n=Ed(e?.toolCall),s={paths:[]};if(!n)return s;let r=To(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=To(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(Ed(d)?.path);let c=Ed(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=To(c.command);d&&(s.command=d);let l=To(c.url);l&&(s.url=l);let f=To(c.description);f&&(s.description=f)}return s}function my(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 Pd=J(()=>{"use strict"});function EA(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function $y(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 PA(t,e){let n=$y(t),s=$y(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 Eo(){if(vs!==void 0)return vs;if(EA())return vs=null,vs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Oy,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&PA(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}vs={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{}vs=null}}catch{vs=null}return vs}function Po(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Oy}`}var Oy,vs,mu=J(()=>{"use strict";Ht();Oy="@hydra-acp/cli"});import*as Mo from"fs/promises";import*as hu from"path";async function _o(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=hu.resolve(We(e)),s;try{s=await Mo.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 Fy(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 Mo.stat(r)).isDirectory())return r}catch{}return null}async function Ly(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=hu.resolve(We(r)),o;try{o=(await Mo.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";He()});import{EventEmitter as MA}from"events";import{WebSocket as _A}from"ws";function $A(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=Yi(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new _A(t,e,n),o=()=>{i.off("error",a),s(kn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function By(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??$A,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Pt(d),f;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)f=s.reuseSessionId;else{let h=n.replace(/\s+/g," ").trim().slice(0,60);f=(await ud(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}}catch(h){throw d.close().catch(()=>{}),h}let u=new yu(l,d,f,t,o),p=!1,m=h=>{p||(p=!0,u.emit("event",h),d.close().catch(()=>{}))};l.onNotification("session/update",h=>{let w=h?.update;w!==void 0&&u.emit("event",{kind:"update",update:w})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw d.close().catch(()=>{}),xn(t,f,o).catch(()=>{}),h}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[pt]:{ancillary:!0}}}).then(h=>{let w=h&&typeof h=="object"?h.stopReason:void 0;m(w==="cancelled"?{kind:"cancelled"}:w==="error"||w==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var yu,Ny=J(()=>{"use strict";Vi();So();Js();ni();xt();yu=class extends MA{_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(()=>{}),xn(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 wu,Fd,Dy=J(()=>{"use strict";yi();ls();wu=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())}},Fd=class extends wu{_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=Sn(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=gi(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=gi(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=xo(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=xo(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=gs(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return ys(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this._pendingThoughtText=null,this._pendingThoughtRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function FA(t,e){return`[pasted #${t} +${e} lines]`}var OA,Ld,bu,Un,vu=J(()=>{"use strict";OA=/\[pasted #(\d+) \+\d+ lines\]/g,Ld=/\[pasted #(\d+) \+\d+ lines\]$/,bu=/^\[pasted #(\d+) \+\d+ lines\]/;Un=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;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.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||this.attachments.splice(e,1)}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){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]}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.insertChar(e.ch),[];if(e.type==="paste"){this.lastEscapeAt=null;let n=e.text.split(`
143
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(FA(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.insertNewline(),[];case"shift-tab":return this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return 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.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"backspace":return this.backspace(),[];case"delete":return this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(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.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.yank(),[];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(OA,(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=[]}insertChar(e){if(e.length===0)return;if(e.includes(`
141
+ `),i({exitCode:-1})}})}function xC(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 pu(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(xC(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 oy(t,e,n,s,r){Vn();let i=wC(e,n,s),o=!1,a,c,d=()=>{let f=4;i.command&&f++,i.url&&f++,i.methodLines&&(f+=1+i.methodLines.length),a&&f++,c&&f++;let u=Gn(t,{contentHeight:f,contentWidth:80,title:"Authentication required"}),p=u.contentW,m=0;if(a&&(t.moveTo(u.contentX,u.contentY+m),t.brightYellow.noFormat(nt(` ${a}`,p)),m++),c&&(t.moveTo(u.contentX,u.contentY+m),t.brightRed.noFormat(nt(` ${c}`,p)),m++),t.moveTo(u.contentX,u.contentY+m),t.brightWhite.bold.noFormat(nt(` ${i.title}`,p)),m+=2,t.moveTo(u.contentX,u.contentY+m),t.noFormat(nt(` ${i.description}`,p)),m++,i.command&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(nt(i.command,p-7)),m++),i.url&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(nt(i.url,p-7)),m++),i.methodLines){t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Methods reported by the agent:"),m++;for(let h of i.methodLines)t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" "),t.noFormat(nt(h.label,p-3)),m++}return m++,t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(` ${i.footer}`),u},l=i.methodLines?.length??0;return Cs({term:t,render:()=>{d()},onKey:(f,u,p,m)=>{if(o)return;let h=bC(f,p,l);if(h.kind!=="ignore"){if(h.kind==="retry"||h.kind==="back"||h.kind==="cancel"){m(h.kind);return}if(h.kind==="selectMethod"){let w=i.methodLines?.[h.index]?.method;if(!w||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${sy(w)}\u2026`,d();let b=r.runTerminalAuth??(v=>IC(t,v));(async()=>{let v=await pu(w,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){m("terminal-completed");return}if(v.kind==="retry"){m("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 gC,yC,mu=K(()=>{"use strict";wa();va();Oi();gC="This agent requires authentication before use.",yC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as uy}from"timers/promises";function $C(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var EC,PC,MC,_C,Fi,hu=K(()=>{"use strict";Eo();fi();EC=200,PC=5e3,MC=2,_C=60,Fi=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(()=>{}),uy(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=EC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await ur(s,this.opts.subprotocols);this.bindStream(Tn(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>=_C)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 uy(n),this.destroyed)return;n=Math.min(n*MC,PC)}}bindStream(e){this.current=e,e.onMessage(n=>{if($C(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 fy(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 br(t){return{outcome:{outcome:"selected",optionId:fy(t,["allow_once","allow_always"])}}}function py(t){return{outcome:{outcome:"selected",optionId:fy(t,["reject_once","reject_always"])}}}function Fd(t){return t&&typeof t=="object"?t:void 0}function Bo(t){return typeof t=="string"&&t.length>0?t:void 0}function my(t){let e=Fd(t),n=Fd(e?.toolCall),s={paths:[]};if(!n)return s;let r=Bo(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Bo(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(Fd(d)?.path);let c=Fd(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Bo(c.command);d&&(s.command=d);let l=Bo(c.url);l&&(s.url=l);let f=Bo(c.description);f&&(s.description=f)}return s}function hy(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 Ld=K(()=>{"use strict"});function _A(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Oy(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 $A(t,e){let n=Oy(t),s=Oy(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 No(){if(Rs!==void 0)return Rs;if(_A())return Rs=null,Rs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Fy,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&$A(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Rs={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{}Rs=null}}catch{Rs=null}return Rs}function Do(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Fy}`}var Fy,Rs,wu=K(()=>{"use strict";Nt();Fy="@hydra-acp/cli"});import*as Ho from"fs/promises";import*as bu from"path";async function Uo(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=bu.resolve(je(e)),s;try{s=await Ho.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 Ly(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 Ho.stat(r)).isDirectory())return r}catch{}return null}async function By(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=bu.resolve(je(r)),o;try{o=(await Ho.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 vu=K(()=>{"use strict";Ne()});import{EventEmitter as OA}from"events";import{WebSocket as FA}from"ws";function LA(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=so(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 FA(t,e,n),o=()=>{i.off("error",a),s(Tn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Ny(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??LA,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Pt(d),f;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)f=s.reuseSessionId;else{let h=n.replace(/\s+/g," ").trim().slice(0,60);f=(await yd(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}}catch(h){throw d.close().catch(()=>{}),h}let u=new Su(l,d,f,t,o),p=!1,m=h=>{p||(p=!0,u.emit("event",h),d.close().catch(()=>{}))};l.onNotification("session/update",h=>{let w=h?.update;w!==void 0&&u.emit("event",{kind:"update",update:w})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw d.close().catch(()=>{}),Pn(t,f,o).catch(()=>{}),h}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[mt]:{ancillary:!0}}}).then(h=>{let w=h&&typeof h=="object"?h.stopReason:void 0;m(w==="cancelled"?{kind:"cancelled"}:w==="error"||w==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var Su,Dy=K(()=>{"use strict";ro();Po();sr();fi();It();Su=class extends OA{_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(()=>{}),Pn(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 ku,Ud,Hy=K(()=>{"use strict";Ri();ys();ku=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())}},Ud=class extends ku{_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=Rn(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=Ai(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Ai(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=$o(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=$o(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=Is(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return xs(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 NA(t,e){return`[pasted #${t} +${e} lines]`}var BA,jd,Iu,DA,Qn,xu=K(()=>{"use strict";BA=/\[pasted #(\d+) \+\d+ lines\]/g,jd=/\[pasted #(\d+) \+\d+ lines\]$/,Iu=/^\[pasted #(\d+) \+\d+ lines\]/;DA=500,Qn=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>DA&&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(NA(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"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(BA,(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
145
  `)){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(Ld);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(bu);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=`
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(jd);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(Iu);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
147
  `,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
148
  `,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
149
  `,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(Ld);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(Ld);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(bu);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(Ld);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(bu);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.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 Ti,Bd,Su=J(()=>{"use strict";Ti=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())}},Bd=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 LA from"path";function $o(t){return Hy[LA.extname(t).toLowerCase()]??null}function BA(t){return $o(t)!==null}function ku(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(!NA.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 DA(t){return ku(t)!==null}function Vt(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function Uy(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(!DA(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!BA(o))return null;n.push(o)}return n.length>0?n:null}var An,Hy,NA,Nd=J(()=>{"use strict";An=10*1024*1024,Hy={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};NA=new Set(Object.values(Hy))});import HA from"string-width";function jy(t,e){if(!t||e<=0)return 0;let n=0;for(let s of UA.segment(t)){let r=HA(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function qy(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 UA,Wy=J(()=>{"use strict";UA=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as jA}from"child_process";import Iu from"fs/promises";import qA from"os";import WA from"path";async function Ky(t={}){let e={...xu,...t};return e.platform==="darwin"?YA(e):e.platform==="linux"?VA(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Yy(t={}){let e={...xu,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Ei(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Ei(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 Oo(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Cu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Vy(t,e={}){let{target:n="both",...s}=e,r={...xu,...s},i=await zA(r,t,n);if(i.ok)return i;let o=JA(r,t,n);return o.ok||o.reason!==Gy?o:i}async function zA(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await Dd(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 Ei(t,"wl-copy")?Jy(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Ei(t,"xclip")?Jy(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 Jy(t,e,n,s,r,i,o){let a=n;if(i){try{await Dd(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await Dd(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await Dd(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function JA(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>zy)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${zy} 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??KA)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Gy}}function KA(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 YA(t){let e=WA.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 Qy(t.spawn,"osascript",s);let r=await eR(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Iu.unlink(e).catch(()=>{})}try{let r=await Oo(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Cu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function VA(t){let e=await GA(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await ZA(t,e),s=XA(n);if(s)try{let r=await Oo(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>An?{ok:!1,reason:`clipboard image is ${Vt(r.length)}, max ${Vt(An)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Oo(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Cu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function GA(t){return t.env.WAYLAND_DISPLAY&&await Ei(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Ei(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function XA(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of QA)if(e.has(n))return n;return null}async function ZA(t,e){try{return(await Oo(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
152
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Cu(t){return t.replace(/\r\n?/g,`
153
- `)}async function Ei(t,e){try{return await Qy(t.spawn,"which",[e]),!0}catch{return!1}}async function eR(t,e){try{let n=await Iu.readFile(t);return e&&await Iu.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>An?{ok:!1,reason:`clipboard image is ${Vt(n.length)}, max ${Vt(An)}`}:{ok:!0,kind:"image",attachment:{mimeType:$o(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Qy(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 Dd(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 Oo(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",f=>{o.push(typeof f=="string"?Buffer.from(f):f)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",f=>{d||(d=!0,r(f))}),i.on("close",f=>{c=f??0,l()})})}var xu,zy,Gy,QA,Au=J(()=>{"use strict";Nd();xu={platform:process.platform,env:process.env,spawn:jA,tmpdir:qA.tmpdir};zy=74994;Gy="no TTY available for OSC 52 clipboard write";QA=["image/png","image/jpeg","image/gif","image/webp"]});function tR(){Fo===0&&process.stdout.write(Xg),Fo++}function nR(){Fo!==0&&(Fo--,Fo===0&&process.stdout.write(Zg))}function Ue(t){tR();try{t()}finally{nR()}}var Fo,Ru=J(()=>{"use strict";Ro();Fo=0});import{spawn as sR}from"child_process";import{statSync as rR}from"fs";import{homedir as Xy}from"os";import{isAbsolute as Zy,resolve as iR}from"path";import lr from"string-width";import oR from"wrap-ansi";function mR(t){let e=t.replace(/\r\n?$|\n$/,"");return pR.test(e)?e:null}function hR(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function ew(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 qn(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 ks(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 tw(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){jn(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let c=o.indexOf(s,a);if(c===-1){jn(t,e.slice(a),n);return}c>a&&jn(t,e.slice(a,c),n);let d=r!==null&&c===r;jn(t,e.slice(c,c+s.length),d?"search-highlight-active":"search-highlight"),a=c+s.length}}function Lo(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function jn(t,e,n){if(e.length!==0)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.green.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 gR(t,e){return e<=0?[t]:t.length===0?[""]:oR(t,e,{hard:!0,trim:!1}).split(`
154
- `)}function lw(t){cw=t}function uw(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 Ss(t){return lr(t,{ambiguousIsNarrow:!cw})}function Pi(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 yR.test(n)?{text:t.slice(e,e+2),width:0}:null}function nw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Pi(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 sw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=Pi(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function wR(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=Pi(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function fw(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(Pi(t,e))return!0;return!1}function*Nu(t){let e=0;for(;e<t.length;){let n=Pi(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(Pi(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 Bu.segment(t.slice(e,s)))yield{text:i,width:Ss(i)};e=s}}function bR(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 vR(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&fw(t);return!s&&!dw.test(t)?SR(t,e):kR(t,e,s)}function SR(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 kR(t,e,n){let s=[],r=n?[...Nu(t)]:IR(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 IR(t){let e=[];for(let{segment:n}of Bu.segment(t))e.push({text:n,width:Ss(n)});return e}function ct(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&fw(t);if(!s&&t.length<=e&&!dw.test(t))return t;if(!s)return Ss(t)<=e?t:e<=1?rw(t,e):rw(t,e-1)+"\u2026";let r=[...Nu(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?iw(r,e):iw(r,e-1)+"\u2026"}function rw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Bu.segment(t)){let i=Ss(r);if(s+i>e)break;n+=r,s+=i}return n}function iw(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 xR(t){let e=t.indexOf(`
155
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function ow(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Ud(t.used)}/${Ud(t.size)}`):e.push(Ud(t.used)):typeof t.size=="number"&&e.push(`/${Ud(t.size)}`),typeof t.costAmount=="number"&&e.push(jl(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Ud(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Wd(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_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 jd(){let t=[vi,Si,Kg,ki,Yg,du,Nn,ir,or,rr,sr,"\x1B>",Ao,xd,Cd,"\x1B]9;4;0\x07",qg].join("");try{process.stdout.write(t)}catch{}}function pw(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 aw(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",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":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":null:null}var Tu,Hd,Eu,Pu,aR,Ne,Ke,De,Mu,_u,dR,cR,lR,$u,Ou,Fu,uR,fR,pR,qd,dw,Bu,cw,yR,Lu,Du=J(()=>{"use strict";Su();ql();me();wn();Nd();yi();Wy();Au();Ru();Ro();Tu=500,Hd=1,Eu=/[A-Za-z0-9_]/,Pu=/[A-Za-z0-9_./\-~+@]/,aR=/\x1b\[[0-9;]*[A-Za-z]/g,Ne=1,Ke=1,De=1,Mu=8,_u=5,dR=12,cR=12,lR=30,$u=6,Ou=4,Fu=2,uR=1e3,fR=1e4,pR=/^(https?|ftp):\/\/\S+$/;qd=class{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onMouse;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;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};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;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.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??uR,this.painter=new Ti(this.term),this.scheduler=new Bd({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??fR,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(au),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(Cd),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Ao),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(jd(),this.term.fullscreen(!1),this.term(`
156
- `)))}installBracketedPaste(){process.stdout.write(Id),process.stdout.write(zg),process.stdout.write(Jg),process.stdout.write(Wg);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(Nn),process.stdout.write(ir),process.stdout.write(or),process.stdout.write(rr),process.stdout.write(sr),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(Vg),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(du),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>jd(),this.onProcessSignal=e=>{jd(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{jd(),process.stderr.write(`
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(jd);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(jd);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(Iu);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(jd);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(Iu);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 Ni,qd,Cu=K(()=>{"use strict";Ni=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())}},qd=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 HA from"path";function jo(t){return Uy[HA.extname(t).toLowerCase()]??null}function UA(t){return jo(t)!==null}function Au(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(!jA.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 qA(t){return Au(t)!==null}function Vt(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function jy(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(!qA(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!UA(o))return null;n.push(o)}return n.length>0?n:null}var _n,Uy,jA,Wd=K(()=>{"use strict";_n=10*1024*1024,Uy={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};jA=new Set(Object.values(Uy))});import WA from"string-width";function qy(t,e){if(!t||e<=0)return 0;let n=0;for(let s of zA.segment(t)){let r=WA(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Wy(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 zA,zy=K(()=>{"use strict";zA=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as JA}from"child_process";import Ru from"fs/promises";import KA from"os";import YA from"path";async function Yy(t={}){let e={...Tu,...t};return e.platform==="darwin"?XA(e):e.platform==="linux"?ZA(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Vy(t={}){let e={...Tu,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Di(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Di(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 qo(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Gy(t,e={}){let{target:n="both",...s}=e,r={...Tu,...s},i=await VA(r,t,n);if(i.ok)return i;let o=GA(r,t,n);return o.ok||o.reason!==Qy?o:i}async function VA(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await zd(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 Di(t,"wl-copy")?Ky(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Di(t,"xclip")?Ky(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 Ky(t,e,n,s,r,i,o){let a=n;if(i){try{await zd(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await zd(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await zd(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function GA(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Jy)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Jy} 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??QA)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Qy}}function QA(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 XA(t){let e=YA.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 Xy(t.spawn,"osascript",s);let r=await rR(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Ru.unlink(e).catch(()=>{})}try{let r=await qo(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function ZA(t){let e=await eR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await sR(t,e),s=nR(n);if(s)try{let r=await qo(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>_n?{ok:!1,reason:`clipboard image is ${Vt(r.length)}, max ${Vt(_n)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await qo(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function eR(t){return t.env.WAYLAND_DISPLAY&&await Di(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Di(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 tR)if(e.has(n))return n;return null}async function sR(t,e){try{return(await qo(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
152
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Eu(t){return t.replace(/\r\n?/g,`
153
+ `)}async function Di(t,e){try{return await Xy(t.spawn,"which",[e]),!0}catch{return!1}}async function rR(t,e){try{let n=await Ru.readFile(t);return e&&await Ru.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>_n?{ok:!1,reason:`clipboard image is ${Vt(n.length)}, max ${Vt(_n)}`}:{ok:!0,kind:"image",attachment:{mimeType:jo(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Xy(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 zd(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 qo(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",f=>{o.push(typeof f=="string"?Buffer.from(f):f)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",f=>{d||(d=!0,r(f))}),i.on("close",f=>{c=f??0,l()})})}var Tu,Jy,Qy,tR,Pu=K(()=>{"use strict";Wd();Tu={platform:process.platform,env:process.env,spawn:JA,tmpdir:KA.tmpdir};Jy=74994;Qy="no TTY available for OSC 52 clipboard write";tR=["image/png","image/jpeg","image/gif","image/webp"]});function iR(){Wo===0&&process.stdout.write(Zg),Wo++}function oR(){Wo!==0&&(Wo--,Wo===0&&process.stdout.write(ey))}function De(t){iR();try{t()}finally{oR()}}var Wo,Mu=K(()=>{"use strict";Lo();Wo=0});import{spawn as aR}from"child_process";import{statSync as dR}from"fs";import{homedir as Zy}from"os";import{isAbsolute as ew,resolve as cR}from"path";import Sr from"string-width";import lR from"wrap-ansi";function wR(t){let e=t.replace(/\r\n?$|\n$/,"");return yR.test(e)?e:null}function bR(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function tw(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 Zn(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 Es(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 nw(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){Xn(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let c=o.indexOf(s,a);if(c===-1){Xn(t,e.slice(a),n);return}c>a&&Xn(t,e.slice(a,c),n);let d=r!==null&&c===r;Xn(t,e.slice(c,c+s.length),d?"search-highlight-active":"search-highlight"),a=c+s.length}}function zo(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function Xn(t,e,n){if(e.length!==0)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.green.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 vR(t,e){return e<=0?[t]:t.length===0?[""]:lR(t,e,{hard:!0,trim:!1}).split(`
154
+ `)}function uw(t){lw=t}function fw(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 Ts(t){return Sr(t,{ambiguousIsNarrow:!lw})}function Hi(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 SR.test(n)?{text:t.slice(e,e+2),width:0}:null}function sw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Hi(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 rw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=Hi(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function kR(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=Hi(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function pw(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(Hi(t,e))return!0;return!1}function*ju(t){let e=0;for(;e<t.length;){let n=Hi(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(Hi(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 Uu.segment(t.slice(e,s)))yield{text:i,width:Ts(i)};e=s}}function IR(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 xR(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&pw(t);return!s&&!cw.test(t)?CR(t,e):AR(t,e,s)}function CR(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 AR(t,e,n){let s=[],r=n?[...ju(t)]:RR(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 RR(t){let e=[];for(let{segment:n}of Uu.segment(t))e.push({text:n,width:Ts(n)});return e}function lt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&pw(t);if(!s&&t.length<=e&&!cw.test(t))return t;if(!s)return Ts(t)<=e?t:e<=1?iw(t,e):iw(t,e-1)+"\u2026";let r=[...ju(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?ow(r,e):ow(r,e-1)+"\u2026"}function iw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Uu.segment(t)){let i=Ts(r);if(s+i>e)break;n+=r,s+=i}return n}function ow(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 TR(t){let e=t.indexOf(`
155
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function aw(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Kd(t.used)}/${Kd(t.size)}`):e.push(Kd(t.used)):typeof t.size=="number"&&e.push(`/${Kd(t.size)}`),typeof t.costAmount=="number"&&e.push(Jl(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Kd(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Gd(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_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 Yd(){let t=[Pi,Mi,Yg,_i,Vg,fu,Yn,gr,yr,hr,mr,"\x1B>",Fo,Pd,Md,"\x1B]9;4;0\x07",Wg].join("");try{process.stdout.write(t)}catch{}}function mw(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 dw(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",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 _u,Jd,$u,Ou,uR,Le,ze,Be,Fu,Lu,fR,pR,mR,Bu,Nu,Du,hR,gR,yR,Vd,cw,Uu,lw,SR,Hu,qu=K(()=>{"use strict";Cu();Kl();pe();xn();Wd();Ri();zy();Pu();Mu();Lo();_u=500,Jd=1,$u=/[A-Za-z0-9_]/,Ou=/[A-Za-z0-9_./\-~+@]/,uR=/\x1b\[[0-9;]*[A-Za-z]/g,Le=1,ze=1,Be=1,Fu=8,Lu=5,fR=12,pR=12,mR=30,Bu=6,Nu=4,Du=2,hR=1e3,gR=1e4,yR=/^(https?|ftp):\/\/\S+$/;Vd=class{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onMouse;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;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};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;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.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??hR,this.painter=new Ni(this.term),this.scheduler=new qd({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??gR,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(uu),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(Md),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Fo),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Yd(),this.term.fullscreen(!1),this.term(`
156
+ `)))}installBracketedPaste(){process.stdout.write(Ed),process.stdout.write(Jg),process.stdout.write(Kg),process.stdout.write(zg);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(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(hr),process.stdout.write(mr),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(Gg),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(fu),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Yd(),this.onProcessSignal=e=>{Yd(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Yd(),process.stderr.write(`
157
157
  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(Gg),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.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(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(bi)){this.handleRawStdinSegment(n);return}if(n.includes(`
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(Qg),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.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(Ei)){this.handleRawStdinSegment(n);return}if(n.includes(`
159
159
  `)){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=aw(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=aw(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=bi,s=Co;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=Uy(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=mR(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,f]of this.keyedBlocks)l!==e&&f.start>s.start&&(f.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 f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.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 f={prefix:d,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),c+=this.wrappedRowsOf(f)}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=Lu(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&&Ue(()=>{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()))}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(aR,""):(c=a.slice(o.start,o.end),Lo(r.bodyStyle)&&(c=sw(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 f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=d===r?Math.max(0,Math.min(u,o)):0,m=d===i?Math.max(0,Math.min(u,a)):u;c.set(f,{start:p,end:m,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.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,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=c&&f.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(au),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.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.focusedPane="main",this.scheduleRepaint())}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=Wd(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 s=this.mouseCell(n),r=hR(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),s!==null&&i!=="release"){let o=this.keyAtRow(s.y)!==null;this.setPointerShape(o?"pointer":"default")}if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let o=this.lastLeftClick;o!==null&&s!==null&&Math.abs(s.x-o.x)<=Hd&&Math.abs(s.y-o.y)<=Hd&&Date.now()-o.t<=Tu||this.flushPendingBlockClick(),this.pressCell=s,this.handleSelectionPress(s);return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let c=this.keyAtRow(s.y);if(c!==null){let d=s.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;this.schedulePendingBlockClick(c,s.y-d)}}this.handleSelectionRelease(s)}}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<=Tu&&Math.abs(e.x-r.x)<=Hd&&Math.abs(e.y-r.y)<=Hd){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}=nw(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),!Eu.test(r[a]))return null;let c=a;for(;c>0&&Eu.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Eu.test(r[d]);)d++;let l=s.length,f=s.length;for(let u=0;u<i.length;u++)if(i[u]===c&&l===s.length&&(l=u),i[u]===d&&f===s.length){f=u;break}return{start:l,end:f}}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}=nw(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 m=p.url;return{raw:m.startsWith("file://")?m.slice(7):m,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Pu.test(r[a]))return null;let c=a;for(;c>0&&Pu.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Pu.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let f=null,u=r.slice(d).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Xy():`${Xy()}/${n.slice(2)}`);let s=Zy(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=Zy(n)?n:iR(this.sessionbar.cwd,n);if(s)return i;try{if(rR(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 f of c)f.includes("%f")&&(d=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let f=sR(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.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)},Tu);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&&Vy(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"?Qg:Cd))}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),f=i-l;return f<0||f>=d.length?null:d[f]?.blockKey??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),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Ss(p.prefix??""),w=e-1-h;if(w<0)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=Lo(p.bodyStyle)?qy(Nu(p.body),w):jy(p.body,w);return{sourceLineId:m.sourceLineId,offset:m.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 f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let m=p.body.length;if(e.col<f+m){o=l.length-1-u;break}f+=m}}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()-Ne-De-Ke-De-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),Ue(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Ke-De-Ne;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Ne),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=Lu(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=jh(this.sessionbar.agent,this.sessionbar.model),o=qe(this.sessionbar.cwd),a=ow(this.sessionbar.usage),c=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,c,()=>{let d=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+d,f=Math.max(8,e-l),u,p;if(r){let m=Math.min(r.length,8);u=Math.min(o.length,Math.max(8,f-m)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(ct(o,u)),r&&this.term(" \xB7 ").bold.noFormat(ct(r,p)),this.term.eraseLineAfter(),a){let m=lr(a),h=Math.max(1,e-m);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Lu(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=ow(this.btwOverlayUsage),a=o?` ${o} `:"",c=o?"\u2500\u2500":"",d=s.length+lr(n)+i.length+lr(r)+lr(a)+c.length,l="\u2500".repeat(Math.max(0,e-d)),f=`${e}|${r}|${this.btwOverlayStatus}|${o??""}`;return{left:s,label:n,sidSep:i,sid:r,middle:l,usage:a,right:c,signature:f}}paintBtwHeader(e){switch(this.term.dim(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.yellow(e.sid),this.term.dim(e.middle),e.usage&&this.term.dim.noFormat(e.usage),this.term.dim(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 u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}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(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let u=0;u<s;u++){let p=n+u,m=u-d,h=m>=0?c[m]:void 0,w=this.activeMatchCol(h,l),b=h?this.selectionRangeForChunk(h):null,v=ew("sb",e,h,this.scrollbackHighlight,w,b);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,w,f,b)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let m of c)m.blockKey!==void 0&&u.add(m.blockKey);let p=[];for(let m of this.pendingVisibleKeys)u.has(m)&&p.push(m);for(let m of p)this.pendingVisibleKeys.delete(m),this.onBlockVisible(m)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(_u,this.queuedTexts.length)}chipRows(){return Math.min(Ou,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($u,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-Ne-De-Ke,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 f=c+l,u=this.completions[l],p=l===e-1&&this.completions.length>$u,m=this.completions.length-$u+1,h=u?p?`comp|${n}|overflow|${m}`:`comp|${n}|${d}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${m} more match(es)`);return}let w=u.name.padEnd(d),b=u.description??"",v=n-w.length-4,S=v>0?ct(b,v):"";this.term(" ").brightCyan(w),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-Ne-De-Ke-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Ou,f=this.attachments.length-Ou,u=this.attachments[c],p=u?`${u.name??"image"} \xB7 ${Vt(u.sizeBytes)}`:"",m=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,m,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(bR(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-Ne-De-Ke,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,f=this.queuedTexts[d],u=d===e-1&&this.queuedTexts.length>_u,p=this.queuedTexts.length-_u,m=f===void 0?"":u?`+ ${p+1} more queued`:ct(xR(f),n-4),h=!u&&d===c,w=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${m}`;this.paintRow(l,w,()=>{if(f===void 0)return;let b=`\u23F3 ${m}`,v=b+" ".repeat(Math.max(0,n-1-b.length));h?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=qn(s.buffer,n),i=ks(r,s,Mu),o=this.term.height-i.rendered-Ke-De-Ne+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,f="wrap",u="";d&&(d.bufferIdx===0&&d.startCol===0?f="first":d.startCol===0&&(f="newline"),u=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(f==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):f==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(u):this.term.noFormat(u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Fu-Ke-De-Ne+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${ct(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${ct(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-Ke-De-Ne+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(` ${ct(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,f=` ${d?"\u276F":" "} ${a+1}. ${ct(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(f):this.term.dim(f)})}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-Ke-De-Ne+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 ${ct(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,f=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${ct(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${ct(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(lR,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-Ke-De-Ne+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} ${ct(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(` ${ct(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,u=` ${l?"\u276F":" "} ${c+1}. ${ct(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Ne-De,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Cn(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let c=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${c} stalled`):this.term.brightYellow(`${c} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${c} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${c} ${this.banner.status}`):this.term.brightGreen(`${c} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let d=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(d),this.term.eraseLineAfter(),r){let l=lr(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):r.kind==="compaction"?this.term.brightYellow.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-Ke-De-Ne+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ke-De-Ne;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-Ke-De-Ne+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ke-De-Ne;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-Fu-Ke-De-Ne+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-Ke-De-Ne+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Ke-De-Ne;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-Ke-De-Ne+1;this.term.moveTo(2,f);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=qn(s.buffer,n),i=ks(r,s,Mu),a=this.term.height-i.rendered-Ke-De-Ne+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Ke-De-Ne;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 Fu;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=qn(s.buffer,n);return Math.min(Mu,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(dR,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(cR,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-Ke-De-Ne+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${ct(e.title,n-5)}`)});let a=Math.max(...e.options.map(c=>c.label.length),0);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,u=` ${l?"\u276F":" "} ${c+1}. `,p=d.label.padEnd(a),m=n-u.length-3,h=`${u}${ct(`${p} ${d.value}`,m)}`;o(`opts|o|${n}|${c}|${l?"1":"0"}|${d.value}|${d.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}o(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}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()-Ke-De-Ne,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 f=this.wrapBtwTail(n,c);for(let u=0;u<c;u++){let p=d+1+u,m=f.length-c+u,h=m>=0?f[m]:void 0,w=ew(`btw|c${u}`,n,h);this.paintRow(p,w,()=>{h?this.writeFormattedLine(h,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 f of this.lines)s(f)||d.push(f);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 f=this.wrapOne(l,e);if(r.push(f),i+=f.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 f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",i=Ss(r),o=Math.max(1,n-i),a=Lo(e.bodyStyle),c=e.ansi?gR(e.body,o):vR(e.body,o,{stripMarkup:a}),d=[],l=0;for(let f=0;f<c.length;f++){let u=c[f]??"",p={prefix:f===0?e.prefix:" ".repeat(i),body:u};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.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let m=e.body.indexOf(u,l),h=m===-1?l:m;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&jn(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Ss(e.prefix??"")),a=Lo(e.bodyStyle),c=e.ansi?e.body:ct(e.body,o,{stripMarkup:a}),d=(l,f)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let u=s!==null&&s>=f?s-f:null;tw(this.term,l,e.bodyStyle,this.scrollbackHighlight,u,r)}else jn(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(c.length,i.start)),f=Math.max(l,Math.min(c.length,i.end)),u=Lo(e.bodyStyle);if(d(c.slice(0,l),0),f>l){let m=c.slice(l,f);u&&(m=sw(m)),jn(this.term,m,"selection-highlight")}let p=c.slice(f);if(u&&f>l){let m=wR(c.slice(0,f));m.length>0&&(p=m+p)}d(p,f)}else this.scrollbackHighlight!==null&&!e.ansi?tw(this.term,c,e.bodyStyle,this.scrollbackHighlight,s,r):jn(this.term,c,e.bodyStyle);if(e.fillRow){let l=e.ansi?lr(c):Ss(c),f=o-l;if(f>0){let u=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;jn(this.term," ".repeat(f),u)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};dw=/[^\x20-\x7e]/,Bu=new Intl.Segmenter(void 0,{granularity:"grapheme"}),cw=!1;yR=/[a-zA-Z+\-:_!#/]/;Lu=Ge});function CR(t,e,n=zd){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 mw(t,e){Dn();let n=Ge(e.sessionId),s=e.importedFromMachine??"another machine",r=qe(e.cwd),i=zd.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+zd.length*2+2,d=Hn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(d.contentX,d.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(nt(p.value,l-p.label.length-2)),u++;return u++,hw(t,d,u,{intro:"What do you want to do?",choices:zd,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return ws({term:t,render:o,onKey:(a,c,d,l)=>{let f=AR(a,d);if(!f)return;let u=CR(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function hw(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(Ad(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 AR(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 gw(t,e,n){let s=Ge(e.sessionId),r=e.title??qe(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=Hn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(nt(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+nt(r,d-2)),l++,l++,hw(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},f=p=>{l(),n.pop(),c(p)},u=(p,m,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(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(h?.isCharacter){let w=p.toLowerCase();if(w==="l"){f("launch");return}if(w==="v"){f("view");return}if(w==="n"){i<o.length-1&&(i++,a());return}if(w==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,m,h)=>{d||u(p,m,h)},onResize:()=>{d||a()}})})}var zd,Hu=J(()=>{"use strict";me();wn();xi();zd=[{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 Bo(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 yw(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=Bo(e);return o.length<=r.length?null:o+i}var Jd=J(()=>{"use strict"});import*as ww from"os";async function ur(t,e,n={}){let s=n.defaultCwd??(e?await Fy(e.cwd):void 0)??ww.homedir();Dn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:Ge(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:qe(e.cwd)}]:[],a=s,c=null,d=!1,l=null,f=()=>{let h=o.length+6;l=Hn(t,{contentHeight:h,title:r});let w=l.contentW,b=0;for(let v of o)t.moveTo(l.contentX,l.contentY+b),t.dim.noFormat(` ${v.label}`),t.noFormat(nt(v.value,w-v.label.length-2)),b++;b++,t.moveTo(l.contentX,l.contentY+b),t.noFormat(` ${i}`),b+=2,p(b),b+=2,c!==null?(t.moveTo(l.contentX,l.contentY+b),t.red.noFormat(` ${nt(c,w-2)}`)):(t.moveTo(l.contentX,l.contentY+b),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},u=()=>o.length+3,p=h=>{if(!l)return;let w=h??u();t.moveTo(l.contentX,l.contentY+w).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+w),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+w),t.bold.noFormat(" cwd: ");let b=l.contentW-6-2;t.noFormat(RR(a,b)),d||t.bgWhite(" ")},m=()=>{if(p(),!l)return;let h=u()+2;t.moveTo(l.contentX,l.contentY+h).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+h),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+h),c!==null?t.red.noFormat(` ${nt(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return ws({term:t,render:f,hideCursor:!1,onKey:(h,w,b,v)=>{if(!d){if(h==="ENTER"||h==="KP_ENTER"){let S=a;d=!0,c=null,m(),_o(S).then(A=>{if(d=!1,A.ok){v({kind:"ok",path:A.path});return}c=A.reason,m()});return}if(h==="ESCAPE"){v({kind:"back"});return}if(h==="CTRL_C"||h==="CTRL_D"){v({kind:"cancel"});return}if(h==="TAB"){d=!0,Ly(a).then(S=>{if(d=!1,S.matches.length===0)return;let A;if(S.matches.length===1)A=S.prefix+S.matches[0];else{let T=Bo(S.matches);if(T.length<=S.basePrefix.length)return;A=S.prefix+T}A!==a&&(a=A,c=null,m())});return}if(h==="BACKSPACE"){a.length>0&&(a=a.slice(0,-1),c=null,m());return}if(h==="CTRL_U"){a="",c=null,m();return}if(h==="CTRL_W"){let S=a.replace(/[/\s]+$/,""),A=Math.max(S.lastIndexOf("/"),S.lastIndexOf(" "));a=A>=0?S.slice(0,A+1):"",c=null,m();return}if(b?.isCharacter){a+=h,c=null,m();return}}}})}function RR(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var Uu=J(()=>{"use strict";me();wn();gu();Jd();xi()});function qu(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Wu(t,e){let n=()=>{process.stdout.write(rr),process.stdout.write(Nn),process.stdout.write(ir),process.stdout.write(or),process.stdout.write(vi),process.stdout.write(Si),process.stdout.write(ki),process.stdout.write(sr),process.stdout.write("\x1B>")};n();let s=e.prefs??qu();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(E=>E.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=Yd(e.sessions,r),o=R=>{let E=R;return s.filters.cwdOnly&&(E=E.filter(L=>L.cwd===r)),s.filters.includeNonInteractive||(E=E.filter(L=>L.interactive===!0)),E=_R(E,s.filters.hostFilter),E},a=o(i),c={columns:e.config.tui.sessionColumns??ui,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>pi(R,Date.now())),l=mi(d,c),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(E=>E.sessionId===e.currentSessionId);R>=0&&(u=R+1)}let m=!1,h="",w=120,b=!1,v=0,S="normal",A=null,T=!1,U="input",O=new Un({history:[],collapsePastes:!1}),z=[],V=!1,N=0,F=0,H=null,Z=!1,G="",re=null,Y=!1,de=new Un({history:[]});e.initialPrompt&&de.setBuffer(e.initialPrompt);let je=e.config.tui.promptHistoryMaxEntries;io(_.globalTuiHistoryFile()).then(R=>{let E=R.length>je?R.slice(R.length-je):R;de.setHistory(E)}).catch(()=>{});let Ae=new Ti(t),et=ar(t),pe=on(t),K=0,st="",_t=0,ht=[],$t=1,Ot=0,xs=0,pr=0,an="",Mi=[],Wn=1,No=0,Re=[],gt=1,Cs=0,mr=0,hr=0,As=()=>{et=ar(t),pe=on(t);let R=Math.max(10,pe-ju-1);_t=Math.max(10,pe-bw);let E=Math.max(10,pe-8);st=MR(r,E);let L=de.state();ht=qn(L.buffer,_t);let ee=ks(ht,L,Kd);$t=ee.rendered,Ot=ee.windowStart,xs=ee.cursorVisualRow,pr=ee.cursorVisualCol;let oe=6+$t,Ve=Math.max(3,et-oe);K=Math.min(a.length,Ve),an=hs(fi,l,R,c).padEnd(R),Mi=d.map(Te=>hs(Te,l,R,c).padEnd(R))},Do=()=>{d=a.map(R=>pi(R,Date.now())),l=mi(d,c),f=1+a.length,As()},yt=()=>{let R=o(i);m&&h.length>0?a=R.filter(E=>OR(E,h)):a=R,Do(),m?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+K>a.length&&(p=Math.max(0,a.length-K)),be()},Rs=R=>{if(R!==void 0){let E=a.findIndex(L=>L.sessionId===R);if(E>=0){u=E+1,be();return}}u=a.length>0?1:0,p=0,be()},be=()=>{if(u===0)return;let R=u-1;R<p?p=R:R>=p+K?p=R-K+1:p+K>a.length&&(p=Math.max(0,a.length-K))},wt=()=>Math.max(2,pe-2),bt=()=>{let R=wt(),E=`\u2500 ${st} `,L=Math.max(1,R-E.length),ee="\u2500".repeat(L);u===0?t.brightBlue.noFormat(`\u256D${E}${ee}\u256E`):t.dim.noFormat(`\u256D${E}${ee}\u256E`)},gr=()=>{let R=wt(),E="\u2500".repeat(R);u===0?t.brightBlue.noFormat(`\u2570${E}\u256F`):t.dim.noFormat(`\u2570${E}\u256F`)},zn=R=>{let E=ht[R];return E?(de.state().buffer[E.bufferIdx]??"").slice(E.startCol,E.endCol):""},Ts=R=>{let E=wt(),L=zn(R),ee=Math.max(0,E-1-L.length),oe=" ".repeat(ee);u===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${L}${oe}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${L}${oe}`),t.dim.noFormat("\u2502"))},Rn=R=>{let E=Mi[R]??"",L=a[R],ee=L&&L.priority&&L.priority>0?"* ":" ";u===R+1?t.brightWhite.bgBlue.noFormat(`${ee}${E}`):t.noFormat(`${ee}${E}`)},yr=()=>{let R=p,E=Math.max(0,a.length-p-K),L=[];return s.filters.cwdOnly&&L.push("cwd-only"),s.filters.hostFilter!=="__all"&&L.push(s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`),s.filters.includeNonInteractive&&L.push("+non-interactive"),R>0&&L.push(`\u2191 ${R} above`),E>0&&L.push(`\u2193 ${E} below`),L.length===0?"":` ${L.join(" \xB7 ")}`},Jn=R=>Ge(R),_i=()=>{let R=A?`${A.sessionId}|${A.status}`:"";return["ind",S,R,G,re??"",m?`1|${h}|${a.length}`:"0",yr()].join("")},ke=()=>{Ue(()=>{Ae.paintRow(wr(),_i(),()=>{if(S==="confirm-kill"&&A)t.brightYellow.noFormat(` kill ${Jn(A.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&A)A.status==="live"?t.brightRed.noFormat(` kill + delete ${Jn(A.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Jn(A.sessionId)}? [y/N]`);else if(S==="busy"&&A)t.dim.noFormat(` working on ${Jn(A.sessionId)}\u2026`);else if(S==="rename"&&A)t.brightYellow.noFormat(` title: ${G}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(re!==null)t.dim.noFormat(` ${re}`);else if(m){t.brightYellow.noFormat(` /${h}`),t.bgBrightYellow(" ");let R=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${R} \xB7 ^c clears`)}else t.dim.noFormat(yr())})})},Kn=R=>Wn+1+R,Gt=()=>Wn+$t+1,dn=()=>Wn+$t+3,Es=R=>dn()+1+(R-p),wr=()=>dn()+1+K,Qe=()=>{let R=xs-Ot;if(R<0||R>=$t)return;let E=3+pr;t.moveTo(E,Kn(R))},Ft=()=>`ct|${u===0?"f":"u"}|${wt()}|${st}`,cn=()=>`cb|${u===0?"f":"u"}|${wt()}`,Ie=R=>`cbb|${u===0?"f":"u"}|${wt()}|${zn(R)}`,$i=()=>`h|${an}`,ln=R=>{let E=a[R],L=E&&E.priority&&E.priority>0?"* ":" ",ee=Mi[R]??"";return`sr|${u===R+1?"1":"0"}|${L}${ee}`},$e=()=>{Ue(()=>{t.hideCursor(),As(),be(),Wn=1,Ae.ensureSize(pe,et),Ae.paintRow(Wn,Ft(),()=>{bt()});for(let R=0;R<$t;R++){let E=Ot+R;Ae.paintRow(Kn(R),Ie(E),()=>{Ts(E)})}Ae.paintRow(Gt(),cn(),()=>{gr()}),Ae.paintRow(Gt()+1,"blank",()=>{}),Ae.paintRow(dn(),$i(),()=>{t.dim.noFormat(` ${an}`)});for(let R=0;R<K;R++){let E=p+R,L=dn()+1+R;E<a.length?Ae.paintRow(L,ln(E),()=>{Rn(E)}):Ae.paintRow(L,"blank",()=>{})}ke();for(let R=wr()+1;R<=et;R++)Ae.paintRow(R,"blank",()=>{});u===0&&(Qe(),t.hideCursor(!1))})},Ps=()=>{Ae.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),$e()},Ms=()=>{Ue(()=>{t.hideCursor(),Ae.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
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=dw(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=dw(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=Ei,s=Oo;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=jy(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=wR(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,f]of this.keyedBlocks)l!==e&&f.start>s.start&&(f.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 f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.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 f={prefix:d,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),c+=this.wrappedRowsOf(f)}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=Hu(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&&De(()=>{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()))}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(uR,""):(c=a.slice(o.start,o.end),zo(r.bodyStyle)&&(c=rw(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 f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=d===r?Math.max(0,Math.min(u,o)):0,m=d===i?Math.max(0,Math.min(u,a)):u;c.set(f,{start:p,end:m,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.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,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=c&&f.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(uu),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.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.focusedPane="main",this.scheduleRepaint())}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=Gd(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 s=this.mouseCell(n),r=bR(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),s!==null&&i!=="release"){let o=this.keyAtRow(s.y)!==null;this.setPointerShape(o?"pointer":"default")}if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let o=this.lastLeftClick;o!==null&&s!==null&&Math.abs(s.x-o.x)<=Jd&&Math.abs(s.y-o.y)<=Jd&&Date.now()-o.t<=_u||this.flushPendingBlockClick(),this.pressCell=s,this.handleSelectionPress(s);return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let c=this.keyAtRow(s.y);if(c!==null){let d=s.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;this.schedulePendingBlockClick(c,s.y-d)}}this.handleSelectionRelease(s)}}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<=_u&&Math.abs(e.x-r.x)<=Jd&&Math.abs(e.y-r.y)<=Jd){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}=sw(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),!$u.test(r[a]))return null;let c=a;for(;c>0&&$u.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&$u.test(r[d]);)d++;let l=s.length,f=s.length;for(let u=0;u<i.length;u++)if(i[u]===c&&l===s.length&&(l=u),i[u]===d&&f===s.length){f=u;break}return{start:l,end:f}}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}=sw(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 m=p.url;return{raw:m.startsWith("file://")?m.slice(7):m,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Ou.test(r[a]))return null;let c=a;for(;c>0&&Ou.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Ou.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let f=null,u=r.slice(d).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Zy():`${Zy()}/${n.slice(2)}`);let s=ew(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=ew(n)?n:cR(this.sessionbar.cwd,n);if(s)return i;try{if(dR(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 f of c)f.includes("%f")&&(d=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let f=aR(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.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)},_u);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&&Gy(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"?Xg:Md))}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),f=i-l;return f<0||f>=d.length?null:d[f]?.blockKey??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),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Ts(p.prefix??""),w=e-1-h;if(w<0)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=zo(p.bodyStyle)?Wy(ju(p.body),w):qy(p.body,w);return{sourceLineId:m.sourceLineId,offset:m.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 f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let m=p.body.length;if(e.col<f+m){o=l.length-1-u;break}f+=m}}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()-Le-Be-ze-Be-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),De(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-ze-Be-Le;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Le),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=Hu(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=qh(this.sessionbar.agent,this.sessionbar.model),o=Ue(this.sessionbar.cwd),a=aw(this.sessionbar.usage),c=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,c,()=>{let d=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+d,f=Math.max(8,e-l),u,p;if(r){let m=Math.min(r.length,8);u=Math.min(o.length,Math.max(8,f-m)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(lt(o,u)),r&&this.term(" \xB7 ").bold.noFormat(lt(r,p)),this.term.eraseLineAfter(),a){let m=Sr(a),h=Math.max(1,e-m);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Hu(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=aw(this.btwOverlayUsage),a=o?` ${o} `:"",c=o?"\u2500\u2500":"",d=s.length+Sr(n)+i.length+Sr(r)+Sr(a)+c.length,l="\u2500".repeat(Math.max(0,e-d)),f=`${e}|${r}|${this.btwOverlayStatus}|${o??""}`;return{left:s,label:n,sidSep:i,sid:r,middle:l,usage:a,right:c,signature:f}}paintBtwHeader(e){switch(this.term.dim(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.yellow(e.sid),this.term.dim(e.middle),e.usage&&this.term.dim.noFormat(e.usage),this.term.dim(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 u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}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(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let u=0;u<s;u++){let p=n+u,m=u-d,h=m>=0?c[m]:void 0,w=this.activeMatchCol(h,l),b=h?this.selectionRangeForChunk(h):null,v=tw("sb",e,h,this.scrollbackHighlight,w,b);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,w,f,b)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let m of c)m.blockKey!==void 0&&u.add(m.blockKey);let p=[];for(let m of this.pendingVisibleKeys)u.has(m)&&p.push(m);for(let m of p)this.pendingVisibleKeys.delete(m),this.onBlockVisible(m)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Lu,this.queuedTexts.length)}chipRows(){return Math.min(Nu,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(Bu,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-Le-Be-ze,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 f=c+l,u=this.completions[l],p=l===e-1&&this.completions.length>Bu,m=this.completions.length-Bu+1,h=u?p?`comp|${n}|overflow|${m}`:`comp|${n}|${d}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${m} more match(es)`);return}let w=u.name.padEnd(d),b=u.description??"",v=n-w.length-4,S=v>0?lt(b,v):"";this.term(" ").brightCyan(w),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-Le-Be-ze-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Nu,f=this.attachments.length-Nu,u=this.attachments[c],p=u?`${u.name??"image"} \xB7 ${Vt(u.sizeBytes)}`:"",m=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,m,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(IR(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-Le-Be-ze,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,f=this.queuedTexts[d],u=d===e-1&&this.queuedTexts.length>Lu,p=this.queuedTexts.length-Lu,m=f===void 0?"":u?`+ ${p+1} more queued`:lt(TR(f),n-4),h=!u&&d===c,w=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${m}`;this.paintRow(l,w,()=>{if(f===void 0)return;let b=`\u23F3 ${m}`,v=b+" ".repeat(Math.max(0,n-1-b.length));h?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=Zn(s.buffer,n),i=Es(r,s,Fu),o=this.term.height-i.rendered-ze-Be-Le+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,f="wrap",u="";d&&(d.bufferIdx===0&&d.startCol===0?f="first":d.startCol===0&&(f="newline"),u=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(f==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):f==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(u):this.term.noFormat(u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Du-ze-Be-Le+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${lt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${lt(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-ze-Be-Le+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(` ${lt(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,f=` ${d?"\u276F":" "} ${a+1}. ${lt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(f):this.term.dim(f)})}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-ze-Be-Le+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 ${lt(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,f=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${lt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${lt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(mR,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-ze-Be-Le+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} ${lt(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(` ${lt(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,u=` ${l?"\u276F":" "} ${c+1}. ${lt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Le-Be,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Mn(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let c=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${c} stalled`):this.term.brightYellow(`${c} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${c} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${c} ${this.banner.status}`):this.term.brightGreen(`${c} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let d=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(d),this.term.eraseLineAfter(),r){let l=Sr(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):r.kind==="compaction"?this.term.brightYellow.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-ze-Be-Le+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-ze-Be-Le+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-Du-ze-Be-Le+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-ze-Be-Le+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-ze-Be-Le+1;this.term.moveTo(2,f);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=Zn(s.buffer,n),i=Es(r,s,Fu),a=this.term.height-i.rendered-ze-Be-Le+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-ze-Be-Le;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 Du;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=Zn(s.buffer,n);return Math.min(Fu,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(fR,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(pR,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-ze-Be-Le+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${lt(e.title,n-5)}`)});let a=Math.max(...e.options.map(c=>c.label.length),0);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,u=` ${l?"\u276F":" "} ${c+1}. `,p=d.label.padEnd(a),m=n-u.length-3,h=`${u}${lt(`${p} ${d.value}`,m)}`;o(`opts|o|${n}|${c}|${l?"1":"0"}|${d.value}|${d.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}o(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}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()-ze-Be-Le,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 f=this.wrapBtwTail(n,c);for(let u=0;u<c;u++){let p=d+1+u,m=f.length-c+u,h=m>=0?f[m]:void 0,w=tw(`btw|c${u}`,n,h);this.paintRow(p,w,()=>{h?this.writeFormattedLine(h,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 f of this.lines)s(f)||d.push(f);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 f=this.wrapOne(l,e);if(r.push(f),i+=f.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 f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",i=Ts(r),o=Math.max(1,n-i),a=zo(e.bodyStyle),c=e.ansi?vR(e.body,o):xR(e.body,o,{stripMarkup:a}),d=[],l=0;for(let f=0;f<c.length;f++){let u=c[f]??"",p={prefix:f===0?e.prefix:" ".repeat(i),body:u};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.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let m=e.body.indexOf(u,l),h=m===-1?l:m;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&Xn(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Ts(e.prefix??"")),a=zo(e.bodyStyle),c=e.ansi?e.body:lt(e.body,o,{stripMarkup:a}),d=(l,f)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let u=s!==null&&s>=f?s-f:null;nw(this.term,l,e.bodyStyle,this.scrollbackHighlight,u,r)}else Xn(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(c.length,i.start)),f=Math.max(l,Math.min(c.length,i.end)),u=zo(e.bodyStyle);if(d(c.slice(0,l),0),f>l){let m=c.slice(l,f);u&&(m=rw(m)),Xn(this.term,m,"selection-highlight")}let p=c.slice(f);if(u&&f>l){let m=kR(c.slice(0,f));m.length>0&&(p=m+p)}d(p,f)}else this.scrollbackHighlight!==null&&!e.ansi?nw(this.term,c,e.bodyStyle,this.scrollbackHighlight,s,r):Xn(this.term,c,e.bodyStyle);if(e.fillRow){let l=e.ansi?Sr(c):Ts(c),f=o-l;if(f>0){let u=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Xn(this.term," ".repeat(f),u)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};cw=/[^\x20-\x7e]/,Uu=new Intl.Segmenter(void 0,{granularity:"grapheme"}),lw=!1;SR=/[a-zA-Z+\-:_!#/]/;Hu=Ve});function ER(t,e,n=Qd){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 hw(t,e){Vn();let n=Ve(e.sessionId),s=e.importedFromMachine??"another machine",r=Ue(e.cwd),i=Qd.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Qd.length*2+2,d=Gn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(d.contentX,d.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(nt(p.value,l-p.label.length-2)),u++;return u++,gw(t,d,u,{intro:"What do you want to do?",choices:Qd,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Cs({term:t,render:o,onKey:(a,c,d,l)=>{let f=PR(a,d);if(!f)return;let u=ER(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function gw(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(_d(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 PR(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 yw(t,e,n){let s=Ve(e.sessionId),r=e.title??Ue(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=Gn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(nt(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+nt(r,d-2)),l++,l++,gw(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},f=p=>{l(),n.pop(),c(p)},u=(p,m,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(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(h?.isCharacter){let w=p.toLowerCase();if(w==="l"){f("launch");return}if(w==="v"){f("view");return}if(w==="n"){i<o.length-1&&(i++,a());return}if(w==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,m,h)=>{d||u(p,m,h)},onResize:()=>{d||a()}})})}var Qd,Wu=K(()=>{"use strict";pe();xn();Oi();Qd=[{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 Jo(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 ww(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=Jo(e);return o.length<=r.length?null:o+i}var Xd=K(()=>{"use strict"});import*as bw from"os";async function kr(t,e,n={}){let s=n.defaultCwd??(e?await Ly(e.cwd):void 0)??bw.homedir();Vn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:Ve(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ue(e.cwd)}]:[],a=s,c=null,d=!1,l=null,f=[],u=[],p=()=>{f.push(a),f.length>500&&f.shift(),u=[]},m=()=>{let x=f.pop();x!==void 0&&(u.push(a),a=x)},h=()=>{let x=u.pop();x!==void 0&&(f.push(a),a=x)},w=()=>{let x=o.length+6;l=Gn(t,{contentHeight:x,title:r});let T=l.contentW,F=0;for(let $ of o)t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(` ${$.label}`),t.noFormat(nt($.value,T-$.label.length-2)),F++;F++,t.moveTo(l.contentX,l.contentY+F),t.noFormat(` ${i}`),F+=2,v(F),F+=2,c!==null?(t.moveTo(l.contentX,l.contentY+F),t.red.noFormat(` ${nt(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=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 F=l.contentW-6-2;t.noFormat(MR(a,F)),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(` ${nt(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Cs({term:t,render:w,hideCursor:!1,onKey:(x,T,F,$)=>{if(!d){if(x==="ENTER"||x==="KP_ENTER"){let H=a;d=!0,c=null,S(),Uo(H).then(J=>{if(d=!1,J.ok){$({kind:"ok",path:J.path});return}c=J.reason,S()});return}if(x==="ESCAPE"){$({kind:"back"});return}if(x==="CTRL_C"||x==="CTRL_D"){$({kind:"cancel"});return}if(x==="TAB"){d=!0,By(a).then(H=>{if(d=!1,H.matches.length===0)return;let J;if(H.matches.length===1)J=H.prefix+H.matches[0];else{let B=Jo(H.matches);if(B.length<=H.basePrefix.length)return;J=H.prefix+B}J!==a&&(p(),a=J,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 H=a.replace(/[/\s]+$/,""),J=Math.max(H.lastIndexOf("/"),H.lastIndexOf(" ")),B=J>=0?H.slice(0,J+1):"";B!==a&&(p(),a=B,c=null,S());return}if(x===""){m(),c=null,S();return}if(x==="\x1B_"||x==="\x1B"){h(),c=null,S();return}if(F?.isCharacter){p(),a+=x,c=null,S();return}}}})}function MR(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var zu=K(()=>{"use strict";pe();xn();vu();Xd();Oi()});function Ku(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Yu(t,e){let n=()=>{process.stdout.write(hr),process.stdout.write(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(Pi),process.stdout.write(Mi),process.stdout.write(_i),process.stdout.write(mr),process.stdout.write("\x1B>")};n();let s=e.prefs??Ku();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=ec(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(L=>L.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(L=>L.interactive===!0)),P=LR(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??Si,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Ii(R,Date.now())),l=xi(d,c),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(u=R+1)}let m=!1,h="",w=120,b=!1,v=0,S="normal",x=null,T=!1,F="input",$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,j=null,X=!1,Y="",be=[],V=[],ge=()=>{be.push(Y),be.length>500&&be.shift(),V=[]},Je=()=>{let R=be.pop();R!==void 0&&(V.push(Y),Y=R)},Ms=()=>{let R=V.pop();R!==void 0&&(be.push(Y),Y=R)},Ct=()=>{be=[],V=[]},de=null,ee=!1,$e=new Qn({history:[]});e.initialPrompt&&$e.setBuffer(e.initialPrompt);let pn=e.config.tui.promptHistoryMaxEntries;ho(_.globalTuiHistoryFile()).then(R=>{let P=R.length>pn?R.slice(R.length-pn):R;$e.setHistory(P)}).catch(()=>{});let Ce=new Ni(t),$n=wr(t),Ke=fn(t),Xe=0,xr="",Gt=0,Qt=[],Ut=1,es=0,ve=0,Cr=0,Ar="",_s=[],mn=1,$s=0,Rr=[],ut=1,ts=0,Pe=0,Xt=0,gt=()=>{$n=wr(t),Ke=fn(t);let R=Math.max(10,Ke-Ju-1);Gt=Math.max(10,Ke-vw);let P=Math.max(10,Ke-8);xr=FR(r,P);let L=$e.state();Qt=Zn(L.buffer,Gt);let Z=Es(Qt,L,Zd);Ut=Z.rendered,es=Z.windowStart,ve=Z.cursorVisualRow,Cr=Z.cursorVisualCol;let re=6+Ut,Ye=Math.max(3,$n-re);Xe=Math.min(a.length,Ye),Ar=ks(ki,l,R,c).padEnd(R),_s=d.map(Se=>ks(Se,l,R,c).padEnd(R))},Ui=()=>{d=a.map(R=>Ii(R,Date.now())),l=xi(d,c),f=1+a.length,gt()},at=()=>{let R=o(i);m&&h.length>0?a=R.filter(P=>NR(P,h)):a=R,Ui(),m?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+Xe>a.length&&(p=Math.max(0,a.length-Xe)),Zt()},ns=R=>{if(R!==void 0){let P=a.findIndex(L=>L.sessionId===R);if(P>=0){u=P+1,Zt();return}}u=a.length>0?1:0,p=0,Zt()},Zt=()=>{if(u===0)return;let R=u-1;R<p?p=R:R>=p+Xe?p=R-Xe+1:p+Xe>a.length&&(p=Math.max(0,a.length-Xe))},hn=()=>Math.max(2,Ke-2),Tr=()=>{let R=hn(),P=`\u2500 ${xr} `,L=Math.max(1,R-P.length),Z="\u2500".repeat(L);u===0?t.brightBlue.noFormat(`\u256D${P}${Z}\u256E`):t.dim.noFormat(`\u256D${P}${Z}\u256E`)},Er=()=>{let R=hn(),P="\u2500".repeat(R);u===0?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},ss=R=>{let P=Qt[R];return P?($e.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},Os=R=>{let P=hn(),L=ss(R),Z=Math.max(0,P-1-L.length),re=" ".repeat(Z);u===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${L}${re}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${L}${re}`),t.dim.noFormat("\u2502"))},jt=R=>{let P=_s[R]??"",L=a[R],Z=L&&L.priority&&L.priority>0?"* ":" ";u===R+1?t.brightWhite.bgBlue.noFormat(`${Z}${P}`):t.noFormat(`${Z}${P}`)},ji=()=>{let R=p,P=Math.max(0,a.length-p-Xe),L=[];return s.filters.cwdOnly&&L.push("cwd-only"),s.filters.hostFilter!=="__all"&&L.push(s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`),s.filters.includeNonInteractive&&L.push("+non-interactive"),R>0&&L.push(`\u2191 ${R} above`),P>0&&L.push(`\u2193 ${P} below`),L.length===0?"":` ${L.join(" \xB7 ")}`},gn=R=>Ve(R),Ko=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,Y,de??"",m?`1|${h}|${a.length}`:"0",ji()].join("")},ue=()=>{De(()=>{Ce.paintRow(On(),Ko(),()=>{if(S==="confirm-kill"&&x)t.brightYellow.noFormat(` kill ${gn(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)x.status==="live"?t.brightRed.noFormat(` kill + delete ${gn(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${gn(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)t.dim.noFormat(` working on ${gn(x.sessionId)}\u2026`);else if(S==="rename"&&x)t.brightYellow.noFormat(` title: ${Y}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(de!==null)t.dim.noFormat(` ${de}`);else if(m){t.brightYellow.noFormat(` /${h}`),t.bgBrightYellow(" ");let R=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${R} \xB7 ^c clears`)}else t.dim.noFormat(ji())})})},yt=R=>mn+1+R,en=()=>mn+Ut+1,me=()=>mn+Ut+3,Yo=R=>me()+1+(R-p),On=()=>me()+1+Xe,Ge=()=>{let R=ve-es;if(R<0||R>=Ut)return;let P=3+Cr;t.moveTo(P,yt(R))},Fs=()=>`ct|${u===0?"f":"u"}|${hn()}|${xr}`,Ls=()=>`cb|${u===0?"f":"u"}|${hn()}`,k=R=>`cbb|${u===0?"f":"u"}|${hn()}|${ss(R)}`,qi=()=>`h|${Ar}`,Pr=R=>{let P=a[R],L=P&&P.priority&&P.priority>0?"* ":" ",Z=_s[R]??"";return`sr|${u===R+1?"1":"0"}|${L}${Z}`},Qe=()=>{De(()=>{t.hideCursor(),gt(),Zt(),mn=1,Ce.ensureSize(Ke,$n),Ce.paintRow(mn,Fs(),()=>{Tr()});for(let R=0;R<Ut;R++){let P=es+R;Ce.paintRow(yt(R),k(P),()=>{Os(P)})}Ce.paintRow(en(),Ls(),()=>{Er()}),Ce.paintRow(en()+1,"blank",()=>{}),Ce.paintRow(me(),qi(),()=>{t.dim.noFormat(` ${Ar}`)});for(let R=0;R<Xe;R++){let P=p+R,L=me()+1+R;P<a.length?Ce.paintRow(L,Pr(P),()=>{jt(P)}):Ce.paintRow(L,"blank",()=>{})}ue();for(let R=On()+1;R<=$n;R++)Ce.paintRow(R,"blank",()=>{});u===0&&(Ge(),t.hideCursor(!1))})},Bs=()=>{Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Qe()},Fn=()=>{De(()=>{t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
164
164
 
165
- `);for(let R of PR){if(R===null){t(`
166
- `);continue}let[E,L]=R;t.brightCyan.noFormat(` ${E.padEnd(ER)}`),t.noFormat(L)(`
165
+ `);for(let R of OR){if(R===null){t(`
166
+ `);continue}let[P,L]=R;t.brightCyan.noFormat(` ${P.padEnd($R)}`),t.noFormat(L)(`
167
167
  `)}t(`
168
168
  `),t.dim.noFormat(" press any key to dismiss")(`
169
- `)})},k=()=>gt+4,Ho=2,rt=0,un=()=>{et=ar(t);let R=Math.max(2,et-(gt+3)-Ho);return Math.max(1,Math.floor(R/2))},_s=()=>{let R=un();N<rt?rt=N:N>=rt+R&&(rt=N-R+1),rt+R>z.length&&(rt=Math.max(0,z.length-R)),rt<0&&(rt=0)},Tn=R=>{pe=on(t);let E=Math.max(2,pe-2),L="\u2500 Find sessions ",ee="\u2500".repeat(Math.max(1,E-L.length));R?t.brightBlue.noFormat(`\u256D${L}${ee}\u256E`):t.dim.noFormat(`\u256D${L}${ee}\u256E`),t.styleReset()},Yn=()=>{pe=on(t),No=Math.max(10,pe-bw);let R=O.state();Re=qn(R.buffer,No);let E=ks(Re,R,TR);gt=E.rendered,Cs=E.windowStart,mr=E.cursorVisualRow,hr=E.cursorVisualCol},Oi=(R,E)=>{pe=on(t);let L=Math.max(2,pe-2),ee=Re[R],oe="";ee&&(oe=(O.state().buffer[ee.bufferIdx]??"").slice(ee.startCol,ee.endCol));let Ve=Math.max(0,L-1-oe.length),Te=" ".repeat(Ve);E?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${oe}${Te}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${oe}${Te}`),t.dim.noFormat("\u2502")),t.styleReset()},Uo=R=>{pe=on(t);let E=Math.max(2,pe-2),L="\u2500".repeat(E);R?t.brightBlue.noFormat(`\u2570${L}\u256F`):t.dim.noFormat(`\u2570${L}\u256F`),t.styleReset()},Vn=()=>3+hr,qt=()=>2+(mr-Cs),br=()=>{let R=U==="input";Ue(()=>{R&&t.hideCursor(),t.moveTo(1,1),Tn(R);for(let E=0;E<gt;E++)t.moveTo(1,2+E),Oi(Cs+E,R);t.moveTo(1,2+gt),Uo(R),R&&(t.moveTo(Vn(),qt()),t.hideCursor(!1))})},jo=()=>{Ue(()=>{t.hideCursor();for(let R=0;R<gt;R++)t.moveTo(1,2+R),Oi(Cs+R,!0);t.moveTo(Vn(),qt()),t.hideCursor(!1)})},Gd={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},qo=(R,E)=>{let L=z[R];if(!L)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let ee=on(t),oe=Math.max(20,ee-ju),Ve=Ge(L.sessionId),Te=L.title??qe(L.cwd),vt=E&&L.snippets.length>1?` [${F+1}/${L.snippets.length}]`:E&&L.totalMatches>L.snippets.length?` [${L.snippets.length} of ${L.totalMatches}]`:"",Lt=`${Ve} ${L.status==="live"?"live":"cold"}`,xr=Math.max(5,oe-Lt.length-vt.length-2),Os=ko(Te,xr),Fs=`${Lt} ${Os}${vt}`.padEnd(oe),At=L.snippets[E?F:0],Xn=At?Gd[At.kind]??At.kind:"",St=At?.toolName?`${Xn} \xB7 ${At.toolName}`:Xn,En=Math.max(10,oe-St.length-6),kt=At?ko(At.text,En):"",Rt=At?` ${St} ${kt}`:" (no snippet)";return{rowBudget:oe,line1:Fs,line2:Rt.padEnd(oe+ju),focusedRow:E}},Fi=(R,E)=>{let{line1:L,focusedRow:ee}=qo(R,E);ee?t.brightWhite.bgBlue.noFormat(`\u276F ${L}`):t.noFormat(` ${L}`),t.styleReset()},Li=(R,E)=>{let{line2:L}=qo(R,E);t.dim.noFormat(L),t.styleReset()},vr=()=>{if(Z)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(H!==null)t.brightRed.noFormat(` ${H}`),t.styleReset(),t.eraseLineAfter();else if(U==="input")z.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=z.length,E=V?" \xB7 truncated":"",L=R>0?` ${R} ${R===1?"session":"sessions"} match${E} \xB7 `:" ";t.dim.noFormat(`${L}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},it=()=>{Yn();let R=U==="input",E=O.state().buffer.join(`
170
- `);Ue(()=>{t.hideCursor(),Ae.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Tn(R);for(let ee=0;ee<gt;ee++)t.moveTo(1,2+ee),Oi(Cs+ee,R);t.moveTo(1,2+gt),Uo(R);let L=z.length;if(L===0)t.moveTo(1,k()),Z||(H===null&&E.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):H===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,k()+1),vr();else{_s();let ee=un(),oe=U!=="input";for(let Ve=0;Ve<ee;Ve++){let Te=rt+Ve;t.moveTo(1,k()+Ve*2),Te<L?Fi(Te,oe&&Te===N):t.eraseLineAfter(),t.moveTo(1,k()+Ve*2+1),Te<L?Li(Te,oe&&Te===N):t.eraseLineAfter()}t.moveTo(1,k()+ee*2),vr()}R&&(t.moveTo(Vn(),qt()),t.hideCursor(!1))})},Xe=(R,E)=>{let L=R-rt;L<0||L>=un()||Ue(()=>{t.moveTo(1,k()+L*2),Fi(R,E),t.moveTo(1,k()+L*2+1),Li(R,E)})},Sr=()=>{Ue(()=>{t.moveTo(1,k()+un()*2),vr()})},Bi=()=>{Ue(()=>{let R=un(),E=z.length,L=U!=="input";for(let ee=0;ee<R;ee++){let oe=rt+ee;t.moveTo(1,k()+ee*2),oe<E?Fi(oe,L&&oe===N):t.eraseLineAfter(),t.moveTo(1,k()+ee*2+1),oe<E?Li(oe,L&&oe===N):t.eraseLineAfter()}t.moveTo(1,k()+R*2),vr()})},kr=()=>O.state().buffer.join(`
171
- `),$s=R=>{let E=gt;O.feed({type:"paste",text:R}),Yn(),gt!==E?it():jo()},Ni=async()=>{let R=kr().trim();if(R.length!==0){if(a.length===0){H="no sessions in view to search",it();return}Z=!0,H=null,it();try{let E=await Hh(e.target,R,{sessionIds:a.map(L=>L.sessionId)});z=E.results,V=E.truncated,N=0,F=0,rt=0,U=E.results.length>0?"results":"input",Yn()}catch(E){H=`search failed: ${E.message}`}finally{Z=!1,it()}}},Di=()=>{},Qd=()=>{Ue(()=>{let R=u===0;R&&t.hideCursor(),Ae.paintRow(Wn,Ft(),()=>{bt()}),Ae.paintRow(Gt(),cn(),()=>{gr()});for(let E=0;E<$t;E++){let L=Ot+E;Ae.paintRow(Kn(E),Ie(L),()=>{Ts(L)})}R&&(Qe(),t.hideCursor(!1))})},Hi=()=>{Ue(()=>{let R=de.state();ht=qn(R.buffer,_t);let E=ks(ht,R,Kd);Ot=E.windowStart,xs=E.cursorVisualRow,pr=E.cursorVisualCol;let L=u===0;L&&t.hideCursor();for(let ee=0;ee<$t;ee++){let oe=Ot+ee;Ae.paintRow(Kn(ee),Ie(oe),()=>{Ts(oe)})}L&&(Qe(),t.hideCursor(!1))})},Wo=R=>{R<p||R>=p+K||Ue(()=>{Ae.paintRow(Es(R),ln(R),()=>{Rn(R)})})},zo=()=>{Ue(()=>{for(let R=0;R<K;R++){let E=dn()+1+R,L=p+R;L<a.length?Ae.paintRow(E,ln(L),()=>{Rn(L)}):Ae.paintRow(E,"blank",()=>{})}ke()})},Xd=()=>{Ue(()=>{Ae.paintRow(dn(),$i(),()=>{t.dim.noFormat(` ${an}`)});for(let R=0;R<K;R++){let E=dn()+1+R,L=p+R;L<a.length?Ae.paintRow(E,ln(L),()=>{Rn(L)}):Ae.paintRow(E,"blank",()=>{})}ke(),u===0&&(Qe(),t.hideCursor(!1))})},Gn=!1,Wt="",Ye=null,Ir=null,Qn=R=>{let E=R.toString("binary");if(!Gn&&E===""&&Ir){Ir();return}if(Gn){let ee=E.indexOf(Co);if(ee===-1){Wt+=E;return}Wt+=E.slice(0,ee),Gn=!1;let oe=Buffer.from(Wt,"binary").toString("utf-8").replace(/\r\n?/g,`
172
- `);Wt="";let Ve=E.slice(ee+Co.length);if(T)U==="input"&&!Z&&$s(oe);else if(u===0&&!m){de.feed({type:"paste",text:oe});let Te=de.state(),vt=qn(Te.buffer,_t);ks(vt,Te,Kd).rendered!==$t?$e():Hi()}Ve.length>0&&Ye&&Ye(Buffer.from(Ve,"binary"));return}let L=E.indexOf(bi);if(L===-1){Ye?.(R);return}L>0&&Ye?.(Buffer.from(E.slice(0,L),"binary")),E=E.slice(L+bi.length),Gn=!0,E.length>0&&Qn(Buffer.from(E,"binary"))};return $e(),await new Promise(R=>{let E=!1,L=null,ee=!1,oe=null,Ve=!1,Te=[],vt=M=>{Te.push(M)},Lt=()=>{Te.pop(),E||Te[Te.length-1]?.onResize()},xr={push:vt,pop:Lt},Os=()=>({kind:"new",cwd:r}),Fs=async()=>{es(),Ae.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),vt({onKey:()=>{},onResize:()=>{}});let W;try{W=await ur(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Lt(),Qt()}W.kind==="ok"&&W.path!==r&&(r=W.path,i=Yd(i,r),yt()),E||$e()};Di=()=>{O=new Un({history:[],collapsePastes:!1}),z=[],V=!1,N=0,F=0,rt=0,H=null,Z=!1,U="input",T=!1,Lt()};let At=(M,W,ue)=>{kt(),Te[Te.length-1]?.onKey(M,W,ue)},Xn=()=>{E||Te[Te.length-1]?.onResize()},St=()=>{if(E)return;E=!0,Te.length=0,L&&(clearInterval(L),L=null),oe&&(oe.abort(),oe=null,ee=!1),t.off("key",At),t.off("resize",Xn),process.stdout.write(Nn);let M=t;M.stdin&&Ye&&(M.stdin.removeListener("data",Qn),M.stdin.on("data",Ye),Ye=null),Gn=!1,Wt="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,wr()+1),t(`
173
- `)},En=()=>{if(E||Te.length>1||S!=="normal"||m||Ve)return;ee&&oe&&(oe.abort(),oe=null,ee=!1);let M=u>0?a[u-1]?.sessionId:void 0;ee=!0;let W=new AbortController;oe=W,fn(M,{silent:!0,signal:W.signal}).finally(()=>{oe===W&&(oe=null),ee=!1})},kt=()=>{E||(L&&clearInterval(L),L=setInterval(En,3e3))},Rt=()=>(St(),R({kind:Y?"exit":"abort"}),!0),Pn=()=>{let M=d.map(W=>`${W.session}|${W.upstream}|${W.host}|${W.state}|${W.agent}|${W.model}|${W.age}|${W.title}|${W.cwd}|${W.cost}`).join(`
174
- `);return`${u}:${p}:${re??""}
175
- ${M}`},fn=async(M,W={})=>{try{let ue=W.silent?Pn():"",j=f,se=await In(e.target,{includeNonInteractive:!0,signal:W.signal}),ae=M??(u>0?a[u-1]?.sessionId:void 0);if(i=Yd(se,r),yt(),ae!==void 0){let xe=a.findIndex(he=>he.sessionId===ae);xe>=0?u=xe+1:u=0}if(u>f-1&&(u=Math.max(0,f-1)),p+K>a.length&&(p=Math.max(0,a.length-K)),be(),W.silent&&Pn()===ue)return;f===j?Xd():$e()}catch(ue){if(W.silent)return;re=`refresh failed: ${ue.message}`,$e()}},pn=async M=>{if(!A)return;let W=A;S="busy",ke();try{await Bh(e.target,W.sessionId,M),S="normal",A=null,G="",await fn(W.sessionId)}catch(ue){S="normal",A=null,G="",re=`rename failed: ${ue.message}`,ke()}},Ls=async M=>{try{await Dh(e.target,M.sessionId),re="title regen queued (press r to refresh)",ke()}catch(W){re=`regen failed: ${W.message}`,ke()}},Jo=async M=>{let ue=(M.priority&&M.priority>0?M.priority:0)>0?null:1,j=ue??0;for(let ae of i)ae.sessionId===M.sessionId&&(ae.priority=j>0?j:void 0);let se=M.sessionId;i=Yd(i,r),yt(),Rs(se),$e(),re=j>0?"priority: high":"priority: normal",ke();try{await Nh(e.target,M.sessionId,ue)}catch(ae){re=`priority failed: ${ae.message}`,ke()}},Ui=async()=>{if(Ve)return;Ve=!0;let M=u>0?a[u-1]?.sessionId:void 0;re="syncing agents\u2026",ke();try{let{synced:W,skipped:ue,agents:j}=await Lh(e.target);await fn(M),re=`synced ${W} new (${ue} known) from ${j} agent${j===1?"":"s"}`,ke()}catch(W){re=`sync failed: ${W.message}`,ke()}finally{Ve=!1}},Ko=async M=>{if(!A)return;let W=A;S="busy",ke();try{M==="kill"?await xn(e.target,W.sessionId):await Uh(e.target,W.sessionId),S="normal",A=null,W.sessionId===e.currentSessionId&&(Y=!0);let ue;if(M==="kill")ue=W.sessionId;else{let j=a.findIndex(se=>se.sessionId===W.sessionId);j>=0&&(ue=a[j+1]?.sessionId??a[j-1]?.sessionId)}await fn(ue)}catch(ue){S="normal",A=null,re=`${M} failed: ${ue.message}`,ke()}},Zd=(M,W)=>{M===0!=(W===0)&&(Qd(),W===0?(t.hideCursor(!1),Qe()):t.hideCursor())},Tt=M=>{let W=Math.min(f-1,Math.max(0,u+M));if(W===u)return;let ue=u;u=W,be(),Ue(()=>{zo(),Zd(ue,u)})},ji=()=>re===null?!1:(re=null,ke(),!0),ot=()=>{Ms(),vt({onKey:M=>{if(M==="CTRL_C"){St(),R({kind:"abort"});return}Lt()},onResize:()=>Ms()})},Mn=M=>{let W=null,ue=null,j=!0,se=()=>{Ue(()=>{if(t.hideCursor(),Ae.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${Ge(M.sessionId)}`)(`
169
+ `)})},At=()=>ut+4,nc=2,st=0,yn=()=>{$n=wr(t);let R=Math.max(2,$n-(ut+3)-nc);return Math.max(1,Math.floor(R/2))},Ln=()=>{let R=yn();B<st?st=B:B>=st+R&&(st=B-R+1),st+R>H.length&&(st=Math.max(0,H.length-R)),st<0&&(st=0)},Wi=R=>{Ke=fn(t);let P=Math.max(2,Ke-2),L="\u2500 Find sessions ",Z="\u2500".repeat(Math.max(1,P-L.length));R?t.brightBlue.noFormat(`\u256D${L}${Z}\u256E`):t.dim.noFormat(`\u256D${L}${Z}\u256E`),t.styleReset()},Ns=()=>{Ke=fn(t),$s=Math.max(10,Ke-vw);let R=$.state();Rr=Zn(R.buffer,$s);let P=Es(Rr,R,_R);ut=P.rendered,ts=P.windowStart,Pe=P.cursorVisualRow,Xt=P.cursorVisualCol},zi=(R,P)=>{Ke=fn(t);let L=Math.max(2,Ke-2),Z=Rr[R],re="";Z&&(re=($.state().buffer[Z.bufferIdx]??"").slice(Z.startCol,Z.endCol));let Ye=Math.max(0,L-1-re.length),Se=" ".repeat(Ye);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${re}${Se}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${re}${Se}`),t.dim.noFormat("\u2502")),t.styleReset()},Vo=R=>{Ke=fn(t);let P=Math.max(2,Ke-2),L="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${L}\u256F`):t.dim.noFormat(`\u2570${L}\u256F`),t.styleReset()},Ds=()=>3+Xt,Hs=()=>2+(Pe-ts),Ji=()=>{let R=F==="input";De(()=>{R&&t.hideCursor(),t.moveTo(1,1),Wi(R);for(let P=0;P<ut;P++)t.moveTo(1,2+P),zi(ts+P,R);t.moveTo(1,2+ut),Vo(R),R&&(t.moveTo(Ds(),Hs()),t.hideCursor(!1))})},_t=()=>{De(()=>{t.hideCursor();for(let R=0;R<ut;R++)t.moveTo(1,2+R),zi(ts+R,!0);t.moveTo(Ds(),Hs()),t.hideCursor(!1)})},wt={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Go=(R,P)=>{let L=H[R];if(!L)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Z=fn(t),re=Math.max(20,Z-Ju),Ye=Ve(L.sessionId),Se=L.title??Ue(L.cwd),$t=P&&L.snippets.length>1?` [${N+1}/${L.snippets.length}]`:P&&L.totalMatches>L.snippets.length?` [${L.snippets.length} of ${L.totalMatches}]`:"",Tt=`${Ye} ${L.status==="live"?"live":"cold"}`,bt=Math.max(5,re-Tt.length-$t.length-2),Ot=Mo(Se,bt),bn=`${Tt} ${Ot}${$t}`.padEnd(re),dt=L.snippets[P?N:0],vt=dt?wt[dt.kind]??dt.kind:"",Ze=dt?.toolName?`${vt} \xB7 ${dt.toolName}`:vt,qs=Math.max(10,re-Ze.length-6),Ws=dt?Mo(dt.text,qs):"",Bn=dt?` ${Ze} ${Ws}`:" (no snippet)";return{rowBudget:re,line1:bn,line2:Bn.padEnd(re+Ju),focusedRow:P}},Mr=(R,P)=>{let{line1:L,focusedRow:Z}=Go(R,P);Z?t.brightWhite.bgBlue.noFormat(`\u276F ${L}`):t.noFormat(` ${L}`),t.styleReset()},Us=(R,P)=>{let{line2:L}=Go(R,P);t.dim.noFormat(L),t.styleReset()},wn=()=>{if(X)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(j!==null)t.brightRed.noFormat(` ${j}`),t.styleReset(),t.eraseLineAfter();else if(F==="input")H.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=H.length,P=J?" \xB7 truncated":"",L=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${L}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},tn=()=>{Ns();let R=F==="input",P=$.state().buffer.join(`
170
+ `);De(()=>{t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Wi(R);for(let Z=0;Z<ut;Z++)t.moveTo(1,2+Z),zi(ts+Z,R);t.moveTo(1,2+ut),Vo(R);let L=H.length;if(L===0)t.moveTo(1,At()),X||(j===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):j===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,At()+1),wn();else{Ln();let Z=yn(),re=F!=="input";for(let Ye=0;Ye<Z;Ye++){let Se=st+Ye;t.moveTo(1,At()+Ye*2),Se<L?Mr(Se,re&&Se===B):t.eraseLineAfter(),t.moveTo(1,At()+Ye*2+1),Se<L?Us(Se,re&&Se===B):t.eraseLineAfter()}t.moveTo(1,At()+Z*2),wn()}R&&(t.moveTo(Ds(),Hs()),t.hideCursor(!1))})},rs=(R,P)=>{let L=R-st;L<0||L>=yn()||De(()=>{t.moveTo(1,At()+L*2),Mr(R,P),t.moveTo(1,At()+L*2+1),Us(R,P)})},_r=()=>{De(()=>{t.moveTo(1,At()+yn()*2),wn()})},Ki=()=>{De(()=>{let R=yn(),P=H.length,L=F!=="input";for(let Z=0;Z<R;Z++){let re=st+Z;t.moveTo(1,At()+Z*2),re<P?Mr(re,L&&re===B):t.eraseLineAfter(),t.moveTo(1,At()+Z*2+1),re<P?Us(re,L&&re===B):t.eraseLineAfter()}t.moveTo(1,At()+R*2),wn()})},$r=()=>$.state().buffer.join(`
171
+ `),Qo=R=>{let P=ut;$.feed({type:"paste",text:R}),Ns(),ut!==P?tn():_t()},sc=async()=>{let R=$r().trim();if(R.length!==0){if(a.length===0){j="no sessions in view to search",tn();return}X=!0,j=null,tn();try{let P=await Uh(e.target,R,{sessionIds:a.map(L=>L.sessionId)});H=P.results,J=P.truncated,B=0,N=0,st=0,F=P.results.length>0?"results":"input",Ns()}catch(P){j=`search failed: ${P.message}`}finally{X=!1,tn()}}},Yi=()=>{},js=()=>{De(()=>{let R=u===0;R&&t.hideCursor(),Ce.paintRow(mn,Fs(),()=>{Tr()}),Ce.paintRow(en(),Ls(),()=>{Er()});for(let P=0;P<Ut;P++){let L=es+P;Ce.paintRow(yt(P),k(L),()=>{Os(L)})}R&&(Ge(),t.hideCursor(!1))})},qt=()=>{De(()=>{let R=$e.state();Qt=Zn(R.buffer,Gt);let P=Es(Qt,R,Zd);es=P.windowStart,ve=P.cursorVisualRow,Cr=P.cursorVisualCol;let L=u===0;L&&t.hideCursor();for(let Z=0;Z<Ut;Z++){let re=es+Z;Ce.paintRow(yt(Z),k(re),()=>{Os(re)})}L&&(Ge(),t.hideCursor(!1))})},rc=R=>{R<p||R>=p+Xe||De(()=>{Ce.paintRow(Yo(R),Pr(R),()=>{jt(R)})})},Vi=()=>{De(()=>{for(let R=0;R<Xe;R++){let P=me()+1+R,L=p+R;L<a.length?Ce.paintRow(P,Pr(L),()=>{jt(L)}):Ce.paintRow(P,"blank",()=>{})}ue()})},Xo=()=>{De(()=>{Ce.paintRow(me(),qi(),()=>{t.dim.noFormat(` ${Ar}`)});for(let R=0;R<Xe;R++){let P=me()+1+R,L=p+R;L<a.length?Ce.paintRow(P,Pr(L),()=>{jt(L)}):Ce.paintRow(P,"blank",()=>{})}ue(),u===0&&(Ge(),t.hideCursor(!1))})},nn=!1,is="",Rt=null,Gi=null,Zo=null,Or=R=>{let P=R.toString("binary");if(!nn&&P===""&&Gi){Gi();return}if(!nn&&(P===""||P==="\x1B_"||P==="\x1B")){Zo?.(P);return}if(nn){let Z=P.indexOf(Oo);if(Z===-1){is+=P;return}is+=P.slice(0,Z),nn=!1;let re=Buffer.from(is,"binary").toString("utf-8").replace(/\r\n?/g,`
172
+ `);is="";let Ye=P.slice(Z+Oo.length);if(T)F==="input"&&!X&&Qo(re);else if(u===0&&!m){$e.feed({type:"paste",text:re});let Se=$e.state(),$t=Zn(Se.buffer,Gt);Es($t,Se,Zd).rendered!==Ut?Qe():qt()}Ye.length>0&&Rt&&Rt(Buffer.from(Ye,"binary"));return}let L=P.indexOf(Ei);if(L===-1){Rt?.(R);return}L>0&&Rt?.(Buffer.from(P.slice(0,L),"binary")),P=P.slice(L+Ei.length),nn=!0,P.length>0&&Or(Buffer.from(P,"binary"))};return Qe(),await new Promise(R=>{let P=!1,L=null,Z=!1,re=null,Ye=!1,Se=[],$t=E=>{Se.push(E)},Tt=()=>{Se.pop(),P||Se[Se.length-1]?.onResize()},bt={push:$t,pop:Tt},Ot=()=>({kind:"new",cwd:r}),bn=async()=>{Ks(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),$t({onKey:()=>{},onResize:()=>{}});let W;try{W=await kr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Tt(),jn()}W.kind==="ok"&&W.path!==r&&(r=W.path,i=ec(i,r),at()),P||Qe()};Yi=()=>{$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,st=0,j=null,X=!1,F="input",T=!1,Tt()};let dt=(E,W,ie)=>{Ws(),Se[Se.length-1]?.onKey(E,W,ie)},vt=()=>{P||Se[Se.length-1]?.onResize()};Zo=E=>{P||Se[Se.length-1]?.onKey(E,null,{})};let Ze=()=>{if(P)return;P=!0,Se.length=0,L&&(clearInterval(L),L=null),re&&(re.abort(),re=null,Z=!1),t.off("key",dt),t.off("resize",vt),process.stdout.write(Yn);let E=t;E.stdin&&Rt&&(E.stdin.removeListener("data",Or),E.stdin.on("data",Rt),Rt=null),nn=!1,is="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,On()+1),t(`
173
+ `)},qs=()=>{if(P||Se.length>1||S!=="normal"||m||Ye)return;Z&&re&&(re.abort(),re=null,Z=!1);let E=u>0?a[u-1]?.sessionId:void 0;Z=!0;let W=new AbortController;re=W,os(E,{silent:!0,signal:W.signal}).finally(()=>{re===W&&(re=null),Z=!1})},Ws=()=>{P||(L&&clearInterval(L),L=setInterval(qs,3e3))},Bn=()=>(Ze(),R({kind:ee?"exit":"abort"}),!0),ea=()=>{let E=d.map(W=>`${W.session}|${W.upstream}|${W.host}|${W.state}|${W.agent}|${W.model}|${W.age}|${W.title}|${W.cwd}|${W.cost}`).join(`
174
+ `);return`${u}:${p}:${de??""}
175
+ ${E}`},os=async(E,W={})=>{try{let ie=W.silent?ea():"",q=f,ne=await En(e.target,{includeNonInteractive:!0,signal:W.signal}),oe=E??(u>0?a[u-1]?.sessionId:void 0);if(i=ec(ne,r),at(),oe!==void 0){let Me=a.findIndex(He=>He.sessionId===oe);Me>=0?u=Me+1:u=0}if(u>f-1&&(u=Math.max(0,f-1)),p+Xe>a.length&&(p=Math.max(0,a.length-Xe)),Zt(),W.silent&&ea()===ie)return;f===q?Xo():Qe()}catch(ie){if(W.silent)return;de=`refresh failed: ${ie.message}`,Qe()}},Qi=async E=>{if(!x)return;let W=x;S="busy",ue();try{await Nh(e.target,W.sessionId,E),S="normal",x=null,Y="",await os(W.sessionId)}catch(ie){S="normal",x=null,Y="",de=`rename failed: ${ie.message}`,ue()}},rt=async E=>{try{await Hh(e.target,E.sessionId),de="title regen queued (press r to refresh)",ue()}catch(W){de=`regen failed: ${W.message}`,ue()}},Nn=async E=>{let ie=(E.priority&&E.priority>0?E.priority:0)>0?null:1,q=ie??0;for(let oe of i)oe.sessionId===E.sessionId&&(oe.priority=q>0?q:void 0);let ne=E.sessionId;i=ec(i,r),at(),ns(ne),Qe(),de=q>0?"priority: high":"priority: normal",ue();try{await Dh(e.target,E.sessionId,ie)}catch(oe){de=`priority failed: ${oe.message}`,ue()}},Dn=async()=>{if(Ye)return;Ye=!0;let E=u>0?a[u-1]?.sessionId:void 0;de="syncing agents\u2026",ue();try{let{synced:W,skipped:ie,agents:q}=await Bh(e.target);await os(E),de=`synced ${W} new (${ie} known) from ${q} agent${q===1?"":"s"}`,ue()}catch(W){de=`sync failed: ${W.message}`,ue()}finally{Ye=!1}},as=async E=>{if(!x)return;let W=x;S="busy",ue();try{E==="kill"?await Pn(e.target,W.sessionId):await jh(e.target,W.sessionId),S="normal",x=null,W.sessionId===e.currentSessionId&&(ee=!0);let ie;if(E==="kill")ie=W.sessionId;else{let q=a.findIndex(ne=>ne.sessionId===W.sessionId);q>=0&&(ie=a[q+1]?.sessionId??a[q-1]?.sessionId)}await os(ie)}catch(ie){S="normal",x=null,de=`${E} failed: ${ie.message}`,ue()}},Hn=(E,W)=>{E===0!=(W===0)&&(js(),W===0?(t.hideCursor(!1),Ge()):t.hideCursor())},ct=E=>{let W=Math.min(f-1,Math.max(0,u+E));if(W===u)return;let ie=u;u=W,Zt(),De(()=>{Vi(),Hn(ie,u)})},sn=()=>de===null?!1:(de=null,ue(),!0),Un=()=>{Fn(),$t({onKey:E=>{if(E==="CTRL_C"){Ze(),R({kind:"abort"});return}Tt()},onResize:()=>Fn()})},zs=E=>{let W=null,ie=null,q=!0,ne=()=>{De(()=>{if(t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${Ve(E.sessionId)}`)(`
176
176
 
177
- `),j)t.dim.noFormat(" loading\u2026")(`
178
- `);else if(ue!==null)t.brightRed.noFormat(` ${ue}`)(`
179
- `);else if(W!==null)for(let he of W)t.noFormat(` ${he}`)(`
177
+ `),q)t.dim.noFormat(" loading\u2026")(`
178
+ `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
179
+ `);else if(W!==null)for(let He of W)t.noFormat(` ${He}`)(`
180
180
  `);t(`
181
181
  `),t.dim.noFormat(" Esc / ^C to return")(`
182
- `)})};se();let ae=new AbortController,xe={onKey:he=>{if(he==="ESCAPE"||he==="CTRL_C"){ae.abort(),Lt();return}},onResize:()=>se()};vt(xe),(async()=>{try{let he=await jt(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(M.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ae.signal});if(!he.ok)throw new Error(`daemon returned HTTP ${he.status}`);let Fe=await he.json(),Ze=sn(Fe),Oe=tu(Ze,M.status);W=vd(Oe,!1).replace(/\n$/,"").split(`
183
- `)}catch(he){if(ae.signal.aborted)return;ue=`failed to load info: ${he.message}`}finally{j=!1,!E&&Te[Te.length-1]===xe&&se()}})()},_n=()=>{if(a.length===0){re="no sessions to search",ke();return}O=new Un({history:[],collapsePastes:!1}),z=[],V=!1,N=0,F=0,rt=0,H=null,Z=!1,U="input",T=!0,Yn(),it(),vt({onKey:(W,ue,j)=>{if(U==="input"){if(Z)return;if(W==="ESCAPE"||W==="CTRL_C"){Di();return}if(W==="ENTER"||W==="KP_ENTER"){if(kr().trim().length===0)return;Ni();return}if((W==="DOWN"||W==="TAB"||W==="CTRL_N")&&z.length>0){U="results",N=0,F=0,Ue(()=>{br(),Xe(0,!0),Sr(),t.hideCursor()});return}let se=O.state(),ae=null;if(j?.isCharacter)ae={type:"char",ch:W};else{let Ze=Wd(W);Ze!==null&&(ae={type:"key",name:Ze})}if(ae===null){t.moveTo(Vn(),qt());return}O.feed(ae);let xe=O.state();if(se.buffer.length===xe.buffer.length&&se.buffer.every((Ze,Oe)=>Ze===xe.buffer[Oe])&&se.row===xe.row&&se.col===xe.col){t.moveTo(Vn(),qt());return}let Fe=gt;Yn(),gt!==Fe?it():jo();return}if(U==="results"){if(W==="ESCAPE"||W==="CTRL_C"){Di();return}if(W==="CTRL_F"){U="input",Bi(),Sr(),br();return}if(W==="ENTER"||W==="KP_ENTER"){let ae=z[N];if(!ae)return;let xe=a.find(Fe=>Fe.sessionId===ae.sessionId);if(!!xe?.importedFromMachine&&!xe.upstreamSessionId){St();let Fe={kind:"attach",sessionId:ae.sessionId};xe.agentId!==void 0&&(Fe.agentId=xe.agentId),R(Fe);return}(async()=>{let Fe=await gw(t,{sessionId:ae.sessionId,title:ae.title,cwd:ae.cwd},xr);if(Fe==="cancel"){St(),R({kind:"abort"});return}if(Fe==="back")return;St();let Ze={kind:"attach",sessionId:ae.sessionId,readonly:Fe==="view"};xe?.agentId!==void 0&&(Ze.agentId=xe.agentId),R(Ze)})();return}if(j?.isCharacter&&(W==="n"||W==="N")){let ae=z[N];if(!ae||ae.snippets.length<=1)return;F=(F+1)%ae.snippets.length,Xe(N,!0);return}if(j?.isCharacter&&(W==="p"||W==="P")){let ae=z[N];if(!ae||ae.snippets.length<=1)return;F=(F-1+ae.snippets.length)%ae.snippets.length,Xe(N,!0);return}let se=ae=>{if(ae<0&&N===0){U="input",Ue(()=>{Xe(0,!1),Sr(),br()});return}let xe=Math.min(z.length-1,Math.max(0,N+ae));if(xe===N)return;let he=N,Fe=rt;N=xe,F=0,_s(),rt!==Fe?Bi():(Ue(()=>{Xe(he,!1),Xe(N,!0)}),Sr())};switch(W){case"UP":case"SHIFT_TAB":case"CTRL_P":se(-1);return;case"DOWN":case"TAB":case"CTRL_N":se(1);return;case"PAGE_UP":se(-un());return;case"PAGE_DOWN":se(un());return;case"HOME":se(-N);return;case"END":se(z.length);return}return}},onResize:()=>it()})},Zn=(M,W,ue)=>{if(S!=="busy"){if(M==="CTRL_O"){Fs();return}if(M==="CTRL_L"){Ps();return}if(S==="rename"){if(M==="ENTER"||M==="KP_ENTER"){let j=G.trim();if(j.length===0){S="normal",A=null,G="",ke();return}pn(j);return}if(M==="ESCAPE"||M==="CTRL_C"){S="normal",A=null,G="",ke();return}if(M==="BACKSPACE"){G.length>0&&(G=G.slice(0,-1),ke());return}if(M==="CTRL_U"){G="",ke();return}if(M==="CTRL_W"){let j=G.replace(/\s+$/,""),se=j.lastIndexOf(" ");G=se>=0?j.slice(0,se):"",ke();return}if(ue?.isCharacter){G+=M,ke();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(M==="y"||M==="Y")){Ko(S==="confirm-kill"?"kill":"delete");return}if(M==="ESCAPE"||M==="CTRL_C"||M==="ENTER"||M==="KP_ENTER"||ue?.isCharacter&&(M==="n"||M==="N")){S="normal",A=null,ke();return}return}if(ji(),M==="CTRL_F"){_n();return}if(u===0&&!m){if(M==="ESCAPE"){Rt();return}if(M==="ENTER"||M==="KP_ENTER"){St();let Oe=de.expandedText(),lt=Os();Oe.trim().length>0&&(lt.prompt=Oe),R(lt);return}if(M==="UP"&&b){let Oe=Date.now(),lt=Oe-v;if(v=Oe,lt<w){Qe();return}b=!1}if(M==="DOWN"){let Oe=de.state(),lt=Oe.historyIndex!==-1||Oe.queueIndex!==-1,ec=ht.length===0||xs===ht.length-1;if(!lt&&ec&&a.length>0){Tt(1);return}}if(M==="PAGE_DOWN"&&(ht.length===0||xs===ht.length-1)&&a.length>0){Tt(1);return}if(M==="CTRL_P"){a.length>0&&Tt(1);return}b=!1;let j=de.state(),se=null;if(ue?.isCharacter)se={type:"char",ch:M};else{let Oe=Wd(M);Oe!==null&&(se={type:"key",name:Oe})}if(se===null){Qe();return}let ae=de.feed(se),xe=de.state(),he=j.buffer.length===xe.buffer.length&&j.buffer.every((Oe,lt)=>Oe===xe.buffer[lt])&&j.row===xe.row&&j.col===xe.col;if(ae.some(Oe=>Oe.type==="exit")){Rt();return}if(he){Qe();return}let Fe=qn(xe.buffer,_t);if(ks(Fe,xe,Kd).rendered!==$t){$e();return}Hi();return}if(!m&&ue?.isCharacter&&M==="?"){ot();return}if(m){if(ue?.isCharacter){h+=M,yt(),$e();return}if(M==="BACKSPACE"){h.length>0?(h=h.slice(0,-1),yt(),$e()):(m=!1,yt(),$e());return}if(M==="ESCAPE"||M==="CTRL_C"){m=!1,h="",yt(),$e();return}}if(ue?.isCharacter){if(M==="/"){m=!0,h="",yt(),$e();return}if(M==="n"||M==="N"){Tt(1);return}if(M==="p"||M==="P"){Tt(-1);return}if(M==="c"||M==="C"){let j=u>0?a[u-1]:void 0,se=Os();j?.cwd&&(se.cwd=j.cwd),St(),R(se);return}if(M==="q"||M==="Q"){Rt();return}if(M==="o"||M==="O"){let j=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,yt(),Rs(j),$e();return}if(M==="h"||M==="H"){let j=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=$R(s.filters.hostFilter,i),yt(),Rs(j),$e();return}if(M==="i"&&u>0){let j=a[u-1];if(!j)return;Mn(j);return}if(M==="I"){let j=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,yt(),Rs(j),$e();return}if(M==="r"||M==="R"){let j=u>0?a[u-1]?.sessionId:void 0;fn(j);return}if(M==="s"||M==="S"){Ui();return}if((M==="v"||M==="V")&&u>0){let j=a[u-1];if(!j)return;St();let se={kind:"attach",sessionId:j.sessionId,readonly:!0};j.agentId!==void 0&&(se.agentId=j.agentId),R(se);return}if((M==="f"||M==="F")&&u>0){let j=a[u-1];if(!j)return;St();let se={kind:"fork",sourceSessionId:j.sessionId,sourceCwd:j.cwd};j.agentId!==void 0&&(se.sourceAgentId=j.agentId),j.importedFromMachine!==void 0&&(se.sourceImportedFromMachine=j.importedFromMachine),j.upstreamSessionId!==void 0&&(se.sourceUpstreamSessionId=j.upstreamSessionId),R(se);return}if((M==="k"||M==="K")&&u>0){let j=a[u-1];if(!j)return;A={sessionId:j.sessionId,cwd:j.cwd,status:j.status},S="confirm-kill",ke();return}if(M==="t"&&u>0){let j=a[u-1];if(!j)return;A={sessionId:j.sessionId,cwd:j.cwd,status:j.status},G=j.title??"",S="rename",ke();return}if(M==="T"&&u>0){let j=a[u-1];if(!j)return;Ls({sessionId:j.sessionId});return}if(M==="*"&&u>0){let j=a[u-1];if(!j)return;Jo(j);return}if((M==="d"||M==="D")&&u>0){let j=a[u-1];if(!j)return;A={sessionId:j.sessionId,cwd:j.cwd,status:j.status},S="confirm-delete",ke();return}return}switch(M){case"UP":case"SHIFT_TAB":case"CTRL_P":M==="UP"&&(u===1&&(b=!0),v=Date.now()),Tt(-1);return;case"DOWN":case"TAB":case"CTRL_N":Tt(1);return;case"PAGE_UP":Tt(-K);return;case"PAGE_DOWN":Tt(K);return;case"HOME":Tt(1-u);return;case"END":Tt(f);return;case"ENTER":case"KP_ENTER":{if(St(),u===0){R(Os());return}let j=a[u-1];if(!j){R({kind:"abort"});return}let se={kind:"attach",sessionId:j.sessionId};j.agentId!==void 0&&(se.agentId=j.agentId),R(se);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Rt();return}}};vt({onKey:(M,W,ue)=>Zn(M,W,ue),onResize:()=>{E||$e()}});let Qt=()=>{t.grabInput({});let M=t;M.stdin&&typeof M.onStdin=="function"&&(Ye=M.onStdin,M.stdin.removeListener("data",M.onStdin),M.stdin.on("data",Qn),process.stdout.write(Id)),t.on("key",At),t.on("resize",Xn)},es=()=>{process.stdout.write(Nn);let M=t;M.stdin&&Ye&&(M.stdin.removeListener("data",Qn),M.stdin.on("data",Ye),Ye=null),Gn=!1,Wt="",t.off("key",At),t.off("resize",Xn),t.grabInput(!1),t.hideCursor(!1)};if(Qt(),process.platform!=="win32"){let M=!1,W=()=>{M&&(M=!1,t.fullscreen(!0),n(),t.hideCursor(),Qt(),E||Ps())};Ir=()=>{M||E||(M=!0,es(),t.fullscreen(!1),process.stdout.write(`${Ao}${xd}
184
- `),process.once("SIGCONT",W),process.kill(process.pid,"SIGTSTP"))}}L=setInterval(En,3e3)})}function MR(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+ko(qe(t),s)}function Yd(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 _R(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function $R(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 OR(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[Ge(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,qe(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var ju,Kd,TR,bw,ER,PR,vw=J(()=>{"use strict";hd();me();wn();So();Pa();vu();Du();Hu();Uu();xi();Su();Ru();Ro();Vs();nu();ju=2,Kd=4,TR=4,bw=4,ER=20,PR=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],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 NR(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Sw(t,e,n){Dn();let s=NR(e,n??FR),r=0,i=()=>{let l=ar(t)-8;return Math.max(1,Math.min(LR,e.length,l))},o=()=>{let l=i();s<r?r=s:s>=r+l&&(r=s-l+1);let f=Math.max(0,e.length-l);r>f&&(r=f),r<0&&(r=0)},a=()=>{o();let l=i(),f=l+4,u=Math.min(BR,Math.max(40,on(t)-8)),p=Hn(t,{contentHeight:f,contentWidth:u,title:"Select agent"}),m=p.contentW,h=0;t.moveTo(p.contentX,p.contentY+h),t.noFormat(" Which agent should this session use?"),h+=2;let w=Math.min(e.length,r+l);for(let v=r;v<w;v++){let S=e[v];if(!S)continue;let A=v===s?"\u276F":" ",T=S.description??S.name,U=` ${A} ${S.id}`;if(t.moveTo(p.contentX,p.contentY+h),v===s){let O=`${U} ${T}`;t.brightWhite.bgBlue.noFormat(Ad(nt(O,m),m))}else{t.noFormat(U);let O=m-U.length-2;O>1&&t.dim.noFormat(` ${nt(T,O)}`)}h++}h++,t.moveTo(p.contentX,p.contentY+h);let b=e.length>l?` (${s+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${b}`),p},c=()=>{s<e.length-1&&(s++,a())},d=()=>{s>0&&(s--,a())};return ws({term:t,render:a,onKey:(l,f,u,p)=>{if(l==="CTRL_C"||l==="CTRL_D"){p({kind:"cancel"});return}if(l==="ESCAPE"){p({kind:"back"});return}if(l==="ENTER"||l==="KP_ENTER"){let m=e[s];m&&p({kind:"select",agentId:m.id,persist:!1});return}if(l==="UP"||l==="SHIFT_TAB"){d();return}if(l==="DOWN"||l==="TAB"){c();return}if(u?.isCharacter){let m=l.toLowerCase();if(m==="s"){let h=e[s];h&&p({kind:"select",agentId:h.id,persist:!0});return}if(m==="j"){c();return}if(m==="k"){d();return}}}})}var FR,LR,BR,kw=J(()=>{"use strict";xi();FR="opencode",LR=20,BR=88});import*as xw from"fs";import*as Cw from"os";import*as Vd from"path";function Aw(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 DR(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function HR(t){return t.replace(/\\ /g," ")}function Iw(t){return t.replace(/ /g,"\\ ")}function UR(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function jR(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Cw.homedir()+n.slice(1)),Vd.isAbsolute(n)?n:Vd.resolve(e,n)}function qR(t){let e;try{e=xw.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Rw(t,e,n=qR){if(!DR(t))return null;let s=HR(t),{dirPrefix:r,base:i}=UR(s),o=jR(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(u=>u.name.startsWith(i)&&(c||!u.name.startsWith(".")));if(d.length===0)return null;let l=d.map(u=>u.isDir?u.name+"/":u.name);if(d.length===1){let u=d[0],p=u.isDir?u.name+"/":u.name;return{replacement:Iw(r+p),candidates:l}}let f=Bo(d.map(u=>u.name));return{replacement:Iw(r+f),candidates:l}}var Tw=J(()=>{"use strict";Jd()});function Ew(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 Pw(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Mw(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 _w=J(()=>{"use strict"});import{appendFileSync as WR,readFileSync as zR,statSync as JR,renameSync as KR}from"fs";import{nanoid as $w}from"nanoid";import YR from"terminal-kit";import zu from"fs/promises";import fr from"path";function Ow(t){if(!Array.isArray(t))return;let e=Sn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Fw(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 QR(t,e){e.has(t)?e.delete(t):e.add(t)}async function Nw(t){let e=await ye(),n=t.target??await Et(e);Uw=e.tui.logMaxBytes,n.isLocal&&!t.target&&await ps(e);let s=YR.terminal;pw(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:pf(e),defaultEnterAction:e.tui.defaultEnterAction},o=qu(),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 f=t;try{for(;f!==null;)f=await ZR(s,e,n,f,r,i,o)}finally{d(),process.off("exit",l)}let u=await Eo();if(u&&process.stderr.write(`\u2728 ${Po(u)}
186
- `),process.stdout.isTTY){let p=await Xs(e);if(p?.version!==void 0){let m=p.version!==fe,h=cs(e),w=p.configDigest!==void 0&&p.configDigest!==h;if(m||w){let b=m?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${mn()} daemon restart\` to apply.`)+`
187
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=Ge(r.sessionId),m=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${mn()} --session ${p}${m}
188
- `)}}function XR(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 V=Math.max(0,c-a),N=e.slice(V),F=[];for(let H=0;H<V;H++){let Z=e[H];if(Z===void 0)continue;let G=n.get(Z);G&&!Gl(G.status)&&F.push(Z)}l=[...F,...N]}let f=c-l.length,u=r===null,p=r??Date.now(),m=p-s,h=!u&&i!==null&&i!=="end_turn"?i:null,w=h==="amended",b=w?`amended \xB7 ${Cn(m)}`:`stopped (${h}) \xB7 ${Cn(m)}`,v;if(c===0)h!==null?v=b:v=u?`thinking \xB7 ${Cn(m)}`:`thought \xB7 ${Cn(m)}`;else{let V=c===1?"tool":"tools",N=h!==null?b:u?Cn(m):`took ${Cn(m)}`,F=[`${c} ${V}`,N];u&&d&&f>0&&F.push(`${f} hidden`),v=F.join(" \xB7 ")}let S=c===0&&u,A=w?"tool-status-cancelled":"tool-status-fail",O=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":h!==null?A:"tool",body:v,bodyStyle:S?"tool-status-running":h!==null?A:"dim"}],z=[null];for(let V of l){let N=n.get(V);if(N){let F=xo(N,p);if(O.push(...F),z.push(...F.map(()=>V)),o?.has(V)){let H=dg(N);O.push(...H),z.push(...H.map(()=>V))}}}return{lines:O,rowOwners:z}}async function ZR(t,e,n,s,r,i,o){let a=await e0(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",d=s0(t,c);d.write(c);let l=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,m=new Ci({url:l,subprotocols:f,onConnect:async g=>{g||u&&await u()},onDisconnect:g=>{p&&p(g)},log:()=>{}}),h=new Pt(m);await m.start(),h.onNotification(ga,g=>{let y=bp.safeParse(g);y.success&&d.applyProgress(y.data)});let w=[],b=null,v=!1,S=!1,A=(g,y)=>{g&&(b?b(g,y):w.push({event:g,rawUpdate:y}))},T,U=g=>{g!==T&&(T=g,g!==void 0&&k.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},O=null,z=null,V=!1,N=0,F=0,H=!1,Z=!1,G,re=null,Y=null,de=null,je=()=>setInterval(()=>{if(re===null||pe===null)return;let g=de===null?0:Date.now()-de;pe.setBanner({elapsedMs:Date.now()-re,stalled:g>=VR}),Xt()},1e3),Ae=!1,et=g=>{let y=F;F=Math.max(0,F+g);let I=typeof pe<"u"&&pe!==null;y===0&&F>0?(Z=!1,re=Date.now(),de=Date.now(),K?.setTurnRunning(!0),I&&pe.setBanner({status:"busy",elapsedMs:0,stalled:!1}),Y===null&&I&&(Y=je())):y>0&&F===0?(Z=!1,re=null,de=null,K?.setTurnRunning(!1),Y!==null&&(clearInterval(Y),Y=null),I&&pe.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):F>0&&Z&&(Z=!1,I&&pe.setBanner({status:"busy",stalled:!1}))},pe=null,K=null,st,_t=null,ht=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]),$t=g=>{let{update:y}=g??{},I=Sn(y,{cwd:bt});t0(y,I),de=Date.now();let x=y?.sessionUpdate;if(typeof x=="string"&&!ht.has(x)){let C=y??{};typeof C.messageId=="string"&&(st=C.messageId)}if(x==="prompt_received"?et(1):I?.kind==="turn-complete"&&(et(-1),V=!0),x==="permission_resolved"){No(y);return}if(x==="hydra_compaction"){Wn(y);return}A(I,y),Cs(y)};h.onNotification("session/update",g=>{if(!v){if(_t!==null){_t.push(g);return}$t(g)}}),h.onNotification("hydra-acp/session/closed",()=>{if(v)return;F>0&&et(-F),typeof pe<"u"&&pe!==null&&pe.setBanner({status:"cold",elapsedMs:void 0})});let Ot=new Map,xs=200,pr=0,an=!1,Mi=4e3;h.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;if(typeof y._meta?.["hydra-acp"]?.amending=="string"){let x=y.messageId,C=y.prompt,P=setTimeout(()=>{v||(Ot.delete(x),kt.set(x,En(x,C)),pe&&K&&Ls())},xs);Ot.set(x,P)}else kt.set(y.messageId,En(y.messageId,y.prompt)),pe&&K&&Ls();if(zn!==void 0&&y.originator?.clientId===zn){let x=Rt.shift();x&&(x.messageId=y.messageId,Pn.set(y.messageId,x))}}),h.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string"||!kt.has(y.messageId))return;kt.set(y.messageId,En(y.messageId,y.prompt));let I=Pn.get(y.messageId);if(I){let x=Array.isArray(y.prompt)?y.prompt:[],C="",P=[];for(let D of x){if(!D||typeof D!="object")continue;let $=D;$.type==="text"&&typeof $.text=="string"?C+=$.text:$.type==="image"&&typeof $.data=="string"&&typeof $.mimeType=="string"&&P.push({data:$.data,mimeType:$.mimeType,sizeBytes:Math.floor($.data.length*3/4)})}I.text=C,I.attachments=P}pe&&K&&Ls()}),h.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;y.reason==="started"&&(G=y.messageId);let I=Ot.get(y.messageId);I!==void 0&&(clearTimeout(I),Ot.delete(y.messageId)),kt.delete(y.messageId)&&pe&&K&&Ls();let C=Pn.get(y.messageId);C&&(Pn.delete(y.messageId),y.reason==="started"&&(C.flushed=!0,A({kind:"user-text",text:C.displayText,attachments:C.attachments}),pn=C))}),h.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let y=g??{};if(!(typeof pe<"u"&&pe!==null))return;pr=Date.now(),an=!0;let x=typeof y.code=="number"?` (${y.code})`:"",C=typeof y.message=="string"&&y.message.length>0?`: ${y.message}`:"";pe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${x}${C} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let y=g??{};if(typeof y.cancelledMessageId!="string")return;let I=y.cancelledMessageId;fn.add(I),pn!==null&&pn.messageId!==void 0&&pn.messageId===I&&(A({kind:"turn-complete",stopReason:"cancelled",amended:!0}),pn=null,fn.delete(I))});let Wn=g=>{let y=g??{},I=typeof y.phase=="string"?y.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 x=typeof y.error=="string"?y.error:"unknown error",C=x.length>40?x.slice(0,40)+"...":x;k.notify(`compaction failed: ${C}`,5e3)}},No=g=>{let y=g??{},I=typeof y.toolCallId=="string"?y.toolCallId:void 0,x;y.outcome&&typeof y.outcome=="object"?x=y.outcome:typeof y.chosenOptionId=="string"&&(x={kind:"selected",optionId:y.chosenOptionId}),gt(I,x?{outcome:x}:void 0)},Re=null,gt=(g,y)=>{if(!Re||Re.toolCallId&&g&&Re.toolCallId!==g)return;let I=Re.resolve;Re=null,k.setPermissionPrompt(null),I(y??{outcome:{outcome:"cancelled"}})},Cs=g=>{if(!Re?.toolCallId)return;let y=g??{};y.sessionUpdate!=="tool_call"&&y.sessionUpdate!=="tool_call_update"||y.toolCallId===Re.toolCallId&&(!y.status||y.status==="pending"||gt(y.toolCallId,void 0))},mr=()=>{if(!Re){k.setPermissionPrompt(null);return}k.setPermissionPrompt({title:Re.title,detail:Re.detail,options:Re.options.map(g=>({label:g.name})),selectedIndex:Re.selectedIndex})},hr=g=>{if(!Re)return;let{options:y,resolve:I}=Re;if(Re=null,k.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};h.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return dr(g);let y=g??{},x=(Array.isArray(y.options)?y.options:[]).map(Q=>({optionId:Q.optionId,name:Se(Q.name??""),...Q.kind!==void 0?{kind:Q.kind}:{}})),C=y.toolCall?.title??y.toolCall?.name??"tool",P=Se(C),D=Se(my(py(g))),$=y.toolCall?.toolCallId;return x.length===0?(k.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${P} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(Q=>{Re={title:P,detail:D,options:x,selectedIndex:0,resolve:Q,toolCallId:$},mr()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let As,Do,yt=!0,Rs=!1;try{let g=await h.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}});Do=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(yt=!1),Rs=Dt(g?._meta??void 0).prompt?.amending===!0}catch{}let be=a.sessionId,wt=a.agentId,bt=a.cwd,gr,zn,Ts,Rn,yr,Jn,_i,ke,Kn,Gt,dn=!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 y={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[pt]:g}}:{}},I=await ry({request:()=>h.request("session/new",y),showBanner:(P,D,$)=>iy(t,P,D,$,{authenticate:Q=>h.request("authenticate",{methodId:Q})}),resolveOnboarding:async P=>{if(P)try{return(await Hl(n)).find(Q=>Q.id===P)?.onboarding}catch{return}},fallbackAgentId:s.agentId});if(I.kind==="cancel")return t.grabInput(!1),m.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),m.close().catch(()=>{});let P={...s};return delete P.sessionId,delete P.forceNew,delete P.resume,delete P.agentId,P}let x=I.result;d.write(c),be=x.sessionId,r.sessionId=be,r.readonly=!1;let C=Dt(x._meta??void 0);C.clientId&&(zn=C.clientId),As=C.upstreamSessionId,C.agentId&&(wt=C.agentId),C.cwd&&(bt=C.cwd),C.title&&(gr=C.title),Ts=C.currentModel,Rn=C.currentMode,Kn=C.currentUsage,Gt=C.turnStartedAt,C.availableCommands&&(yr=Ja(C.availableCommands)),C.availableModes&&(Jn=C.availableModes),_i=Ow(x.configOptions),ke=C.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let y=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:fe},...Object.keys(g).length>0?{_meta:{[pt]:g}}:{}});be=y.sessionId,y.clientId&&(zn=y.clientId),r.sessionId=be,r.readonly=s.readonly===!0;let I=Dt(y._meta??void 0);dn=I.resurrected===!0,As=I.upstreamSessionId,I.agentId&&(wt=I.agentId),I.cwd&&(bt=I.cwd),I.title&&(gr=I.title),Ts=I.currentModel,Rn=I.currentMode,Kn=I.currentUsage,Gt=I.turnStartedAt,I.availableCommands&&(yr=Ja(I.availableCommands)),I.availableModes&&(Jn=I.availableModes),_i=Ow(y.configOptions),ke=I.queue}let Es=_.tuiHistoryFile(be),wr=_.globalTuiHistoryFile(),Qe=await io(Es).catch(()=>[]),Ft=await io(wr).catch(()=>[]);Ft.length>e.tui.promptHistoryMaxEntries&&(Ft=Ft.slice(Ft.length-e.tui.promptHistoryMaxEntries));let cn=[...Qe],Ie=new Un({history:Ea(Ft,cn)});K=Ie;let $i=!1,ln=(g,y)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let x=(y??g).replace(/\n+$/,""),C=oo(Qe,I),P=C!==Qe;Qe=C,cn=oo(cn,x);let D=oo(Ft,I,e.tui.promptHistoryMaxEntries),$=D!==Ft;Ft=D,Ie.setHistory(Ea(Ft,cn)),P&&Ys(Es,Qe).catch(()=>{}),$&&hm(wr,I).catch(()=>{})};F>0&&Ie.setTurnRunning(!0);let $e=null,Ps=null;lw(uw(e.tui.ambiguousWidth,process.env)),lg(e.tui.diffContextLines);let Ms=!1,k,Ho=()=>{Ms&&(Ms=!1,k.start())},rt=()=>{Ms||(Ms=!0,k.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Ho),k=new qd({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"?rt:void 0,onBlockClick:(g,y)=>{fb(g,y)},onBlockDoubleClick:(g,y)=>ub(g,y),onBlockVisible:g=>{db(g)},onMouse:g=>{if(g.kind!=="press"||g.button!=="middle")return;let y={type:"attachment-request",source:"primary"};s.readonly===!0&&Fw(y)||Fs(y)},onKey:g=>{for(let y of g){if(H&&Xd(y)||Re&&Li(y)||Gn(y)||Ve(y)||Fi(y)||jo(y)||qo(y))continue;if(y.type==="key"&&y.name==="escape"&&k.isScrolledBack()){k.scrollToBottom();continue}if(y.type==="attachment-paths"){At(y.paths);continue}let I=Ie.feed(y);for(let x of I)s.readonly===!0&&Fw(x)||Fs(x)}br(),k.setBannerSearchIndicator(Ie.state().historySearchQuery),k.setAttachments(Ie.state().attachments),k.refreshPrompt()}}),pe=k,k.setStickyBottomKey("plan");let un=[{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>"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],_s=yr??[],Tn=Jn??[],Yn=_i??[],Oi=()=>Yn.find(g=>g.id==="agent"),Uo=()=>{let g=new Set,y=[];for(let I of[...un,..._s])g.has(I.name)||(g.add(I.name),y.push(I));return y},Vn=()=>{let g=Ie.state().buffer,y=g[0]??"";if(!y.startsWith("/"))return[];if(g.length>1)return[];let I=y.indexOf(" "),x=I===-1?y:y.slice(0,I);if(x.lastIndexOf("/")>0)return[];let C=Uo().filter(P=>P.name.startsWith(x));return C.length===1&&C[0]?.name===x?[]:C},qt=[],br=()=>{let g=Vn();if(g.length>0){qt=[],k.setCompletions(g);return}k.setCompletions(qt)},jo=g=>{if(g.type!=="key"||g.name!=="tab")return qt.length>0&&(qt=[]),!1;let y=Vn();if(k.isOverlayOpen()&&y.length===0)return k.toggleFocusedPane(),!0;if(y.length>0){qt=[];let I=Ie.state().buffer[0]??"",x=yw({matches:y.map(C=>C.name),firstLine:I});return x===null||Ie.replaceFirstLine(x),!0}return Gd()},Gd=()=>{let g=Ie.state(),y=g.buffer[g.row]??"",I=Aw(y,g.col);if(I===null)return!1;let x=Rw(I.token,bt);return x===null?!1:(x.replacement!==I.token&&Ie.replaceRangeOnCurrentLine(I.start,g.col,x.replacement),qt=x.candidates.length>1?x.candidates.map(C=>({name:C})):[],!0)},qo=g=>!k.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(O&&(O.cancel(),O=null,z=null),k.closeBtwOverlay(),!0),Fi=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 y=k.scrollbackSearchTerm()+g.ch;return k.updateScrollbackSearchTerm(y),!0}if(g.type==="paste"){let y=k.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return k.updateScrollbackSearchTerm(y),!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 y=k.scrollbackSearchTerm();return y.length===0?k.cancelScrollbackSearch():k.updateScrollbackSearchTerm(y.slice(0,-1)),!0}case"enter":return k.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return k.cancelScrollbackSearch(),!0;default:return!0}return!0},Li=g=>{if(!Re)return!1;let y=Re.options;if(g.type==="key")switch(g.name){case"up":return Re.selectedIndex=Math.max(0,Re.selectedIndex-1),mr(),!0;case"down":return Re.selectedIndex=Math.min(y.length-1,Re.selectedIndex+1),mr(),!0;case"enter":{let I=y[Re.selectedIndex];return I&&hr(I.optionId),!0}case"escape":case"ctrl-c":return hr(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,x=y[I];return x&&hr(x.optionId),!0}return!0},vr=wt||Do||"?",it={...Kn??{}};d.finalize(),k.start({skipFullscreen:!0}),k.setHideThoughts(!i.showThoughts),k.setSessionbar({agent:vr,cwd:bt,sessionId:be,title:gr,model:Ts,usage:{...it}}),Rn&&k.setBanner({currentMode:Rn}),Eo().then(g=>{g&&k.notify(`\u2728 ${Po(g)}`,3e4)}).catch(()=>{});let Xe=null,Sr=new Promise(g=>{Xe=g}),Bi=()=>{h.notify("session/cancel",{sessionId:be}).catch(()=>{})},kr=()=>{pe!==null&&F===1&&(Z=!0,pe.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},$s=()=>{if($e){$e.cancel(),kr();return}if(F>0){Bi(),kr();return}Ni()},Ni=()=>{vt(0)},Di=()=>{let g="enqueue prompt (sends now, or queues during a turn)",y="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",y]],...GR]},Qd=()=>{if(k.isHelpPromptActive()){k.setHelpPrompt(null);return}k.setHelpPrompt({title:"Hotkeys",entries:Di(),hint:"any key dismisses \xB7 /help lists commands"})},Hi=()=>{H=!1,k.setCompactionPrompt(null),k.setCompactionIndicator("compaction queued...");let g=be;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},Wo=()=>{H=!1,k.setCompactionPrompt(null)},zo=g=>{let y=k.compactionPromptSpec();if(!y)return;let I=y.options.length;if(I===0)return;let x=((y.selectedIndex+g)%I+I)%I;x!==y.selectedIndex&&k.setCompactionPrompt({...y,selectedIndex:x})},Xd=g=>{if(!H)return!1;if(g.type==="key"){if(g.name==="escape")return Wo(),!0;if(g.name==="up")return zo(-1),!0;if(g.name==="down")return zo(1),!0;if(g.name==="enter"){let y=k.compactionPromptSpec();return y?.options[y.selectedIndex]?.key==="y"?Hi():Wo(),!0}}if(g.type==="char"){let y=g.ch.toLowerCase();if(y==="y"||y==="1")return Hi(),!0;if(y==="n"||y==="2")return Wo(),!0}return!0},Gn=g=>k.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",k.setHelpPrompt(null),!0):!1,Wt=["tools","plan","thoughts","diffs","mouse","enter"],Ye=0,Ir=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}},Qn=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"}},R=()=>({title:"Session options",options:Wt.map(g=>({label:Qn(g),value:Ir(g)})),selectedIndex:Ye}),E=()=>{k.isOptionsPromptActive()&&k.setOptionsPrompt(R())},L=()=>{if(k.isOptionsPromptActive()){k.setOptionsPrompt(null);return}Ye=0,k.setOptionsPrompt(R())},ee=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,ue.clear(),j.clear(),rb();break;case"plan":i.planExpanded=!i.planExpanded,lt=null,Vu();break;case"thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",_n.clear(),cb();break;case"mouse":{let y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}E()},oe=g=>{(async()=>{try{switch(g){case"tools":case"plan":k.notify(`${Qn(g)} is session-only \u2014 not saved`);return;case"thoughts":await Wi("showThoughts",i.showThoughts);break;case"diffs":await Wi("showFileUpdates",i.showFileUpdates);break;case"mouse":await Wi("mouse",i.mouseEnabled);break;case"enter":await Wi("defaultEnterAction",i.defaultEnterAction);break}k.notify(`saved default: ${Qn(g)} ${Ir(g)}`)}catch(y){k.notify(`save failed: ${y instanceof Error?y.message:String(y)}`)}})()},Ve=g=>{if(!k.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Ye=Math.max(0,Ye-1),E(),!0;case"down":return Ye=Math.min(Wt.length-1,Ye+1),E(),!0;case"enter":{let y=Wt[Ye];return y&&ee(y),!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 y=parseInt(g.ch,10)-1,I=Wt[y];return I&&(Ye=y,ee(I)),!0}if(g.ch==="s"||g.ch==="S"){let y=Wt[Ye];return y&&oe(y),!0}}return!0},Te=()=>{v=!0,O?(O.cancel(),O=null,z=null):z!==null&&(xn(n,z).catch(()=>{}),z=null),process.off("SIGINT",$s),process.platform!=="win32"&&process.off("SIGCONT",Ho),Y!==null&&(clearInterval(Y),Y=null);for(let g of Ot.values())clearTimeout(g);Ot.clear(),k.clearWindowTitle(),k.stop({keepFullscreen:!0}),Ys(Es,Qe).catch(()=>{}),m.close().catch(()=>{})},vt=(g=0)=>{Te(),Xe&&(Xe(null),Xe=null),g!==0&&process.exit(g)},Lt=async()=>{if(!Xe)return;O?(O.cancel(),O=null,z=null):z!==null&&(xn(n,z).catch(()=>{}),z=null);let g=Ie.state().buffer.join(`
189
- `);g.replace(/\s+$/,"").length>0&&ln(g),k.pauseRepaint(),k.stop({keepFullscreen:!0}),Ys(Es,Qe).catch(()=>{});let y=null,I=null;for(;y===null;){let D=await In(n,{includeNonInteractive:!0}),$=await Wu(t,{cwd:bt,sessions:D,config:e,target:n,currentSessionId:be,prefs:o});if($.kind==="abort"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if($.kind==="exit"){vt(0);return}if($.kind==="new"){y={choice:$,sessions:D};break}if($.kind==="fork"){let le=await Hw(t,n,$,D);if(le.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(le.kind==="back")continue;y={choice:{kind:"attach",sessionId:le.ctx.sessionId,...le.ctx.agentId?{agentId:le.ctx.agentId}:{}},sessions:D},I={readonly:!1,cwd:le.ctx.cwd},le.ctx.resumeHint!==void 0&&(I.resumeHint=le.ctx.resumeHint);break}let Q=D.find(le=>le.sessionId===$.sessionId);if(!(Q!==void 0&&!!Q.importedFromMachine&&!Q.upstreamSessionId&&$.readonly!==!0)){if(n.isLocal&&Q&&!Q.importedFromMachine&&$.readonly!==!0&&!(await _o(Q.cwd)).ok){let Le=await ur(t,Q,{defaultCwd:We(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Le.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(Le.kind==="back")continue;y={choice:$,sessions:D},I={readonly:!1,cwd:Le.path,resumeHint:{agentId:$.agentId??Q.agentId??"",cwd:Le.path,upstreamSessionId:""}};break}y={choice:$,sessions:D};break}let Ee={...s,readonly:!1},ce=await Dw(t,Q,$,Ee);if(ce.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}ce.kind!=="back"&&(y={choice:$,sessions:D},I={readonly:Ee.readonly===!0,cwd:ce.ctx.cwd},ce.ctx.resumeHint!==void 0&&(I.resumeHint=ce.ctx.resumeHint))}let{choice:x}=y,C=Xe;if(Xe=null,process.off("SIGINT",$s),m.close().catch(()=>{}),x.kind==="new"){let{sessionId:D,...$}=s,Q={...$,cwd:x.cwd??bt,forceNew:!0,readonly:!1};x.prompt!==void 0&&(Q.initialPrompt=x.prompt),C(Q);return}if(x.kind!=="attach")return;let P={...s,sessionId:x.sessionId,cwd:I?.cwd??bt,readonly:I?.readonly??x.readonly===!0};x.agentId!==void 0&&(P.agentId=x.agentId),I?.resumeHint!==void 0?P.resumeHint=I.resumeHint:delete P.resumeHint,C(P)},xr=async(g="next")=>{if(!Xe)return;let I=(await In(n)).filter(Ee=>Ee.status==="live");if(I.length<=1)return;let x=I.findIndex(Ee=>Ee.sessionId===be),D=((x===-1?0:x)+(g==="prev"?-1:1)+I.length)%I.length,$=I[D],Q=Xe;Xe=null,process.off("SIGINT",$s),m.close().catch(()=>{});let Be={...s,sessionId:$.sessionId,cwd:bt,readonly:!1};$.agentId!==void 0&&(Be.agentId=$.agentId),Q(Be)},Os=async g=>{if(!Xe)return;let y=await In(n,{includeNonInteractive:!0}),I=g.trim();if(!I){k.notify("usage: /session <id|next|prev>");return}let x=I.startsWith(Jt)?[I]:[I,Jt+I],C=y.find($=>x.includes($.sessionId));if(!C){let $=y.filter(Q=>x.some(Be=>Q.sessionId.startsWith(Be)));if($.length===1)C=$[0];else if($.length>1){k.notify(`ambiguous session id: ${I} (${$.length} matches)`);return}}if(!C){k.notify(`no session matches: ${I}`);return}if(C.sessionId===be){k.notify("already on that session");return}let P=Xe;Xe=null,process.off("SIGINT",$s),m.close().catch(()=>{});let D={...s,sessionId:C.sessionId,cwd:C.cwd??bt,readonly:C.status!=="live"};C.agentId!==void 0&&(D.agentId=C.agentId),delete D.resumeHint,P(D)},Fs=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ko(g.text,g.attachments,g.displayText):Ui(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ui(g.text,g.attachments,g.displayText):Ko(g.text,g.attachments,g.displayText);return;case"queue-edit":{let y=Jo(g.index);if(!y)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let x of g.attachments)I.push({type:"image",data:x.data,mimeType:x.mimeType});h.request("hydra-acp/prompt/update",{sessionId:be,messageId:y,prompt:I}).then(x=>{let C=x;!C.updated&&C.reason!=="ok"&&k.notify(`queue edit skipped (${C.reason})`)}).catch(x=>{k.notify(`queue edit failed: ${x.message}`)});return}case"queue-remove":{let y=Jo(g.index);if(!y)return;h.request("hydra-acp/prompt/cancel",{sessionId:be,messageId:y}).then(I=>{let x=I;!x.cancelled&&x.reason!=="ok"&&k.notify(`queue cancel skipped (${x.reason})`)}).catch(I=>{k.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(k.isOverlayOpen()){O&&(O.cancel(),O=null,z=null),k.closeBtwOverlay();return}if(g.prefill&&$e){let y=kt.size===0,I=Ie.state().buffer.every(x=>x==="");y&&I&&(Ps={text:$e.text,attachments:$e.attachments})}$e?$e.cancel():F>0&&Bi(),kr();return}case"exit":Ni();return;case"plan-toggle":Zd(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":Lt().catch(()=>{});return;case"next-live-session":xr().catch(()=>{});return;case"toggle-options":L();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 y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y,k.notify(y?"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":Qd();return;case"escalate-search":k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Xn(g.source);return}},At=async g=>{if(!yt){k.notify("agent does not accept image attachments");return}let y=0;for(let I of g){if(I.startsWith("data:")){let C=ku(I);if(!C){k.notify("unsupported data: URI");continue}if(C.sizeBytes>An){k.notify(`image too large (${Vt(C.sizeBytes)}, max ${Vt(An)})`);continue}Ie.addAttachment({mimeType:C.mimeType,data:C.data,name:"pasted image",sizeBytes:C.sizeBytes}),y++;continue}let x=$o(I);if(!x){k.notify(`unsupported image type: ${fr.basename(I)}`);continue}try{let C=await zu.readFile(I);if(C.length>An){k.notify(`image too large (${Vt(C.length)}, max ${Vt(An)})`);continue}Ie.addAttachment({mimeType:x,data:C.toString("base64"),name:fr.basename(I),sizeBytes:C.length}),y++}catch(C){k.notify(`cannot read ${fr.basename(I)}: ${C.message}`)}}y>0&&(k.setAttachments(Ie.state().attachments),k.refreshPrompt())},Xn=async(g="clipboard")=>{let y=g==="primary"?await Yy():await Ky();if(!y.ok){k.notify(y.reason);return}if(y.kind==="image"){if(!yt){k.notify("agent does not accept image attachments");return}Ie.addAttachment(y.attachment),k.setAttachments(Ie.state().attachments),k.refreshPrompt();return}let I=Ie.feed({type:"paste",text:y.text});for(let x of I)Fs(x);k.refreshPrompt()},St=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,En=(g,y)=>{let I=Array.isArray(y)?y:[],x="",C=0;for(let P of I){if(!P||typeof P!="object")continue;let D=P;D.type==="text"&&typeof D.text=="string"?x+=D.text:D.type==="image"&&(C+=1)}return{messageId:g,text:Se(x),attachmentCount:C}},kt=new Map,Rt=[],Pn=new Map,fn=new Set,pn=null,Ls=()=>{let g=[...kt.values()],y=g.map(St);k.setQueuedPrompts(y),k.setBanner({queued:g.length}),Ie.setQueue(g.map(I=>I.text))},Jo=g=>[...kt.values()][g]?.messageId;if(ke&&ke.length>0){for(let g of ke){if(g.position===0){G=g.messageId;continue}kt.set(g.messageId,En(g.messageId,g.prompt))}kt.size>0&&Ls()}let Ui=(g,y,I)=>{k.scrollToBottom(),!Tt(g)&&(ln(g,I),ji(g,y,I))},Ko=(g,y,I)=>{if(k.scrollToBottom(),Tt(g))return;if(ln(g,I),!Rs||G===void 0){ji(g,y,I);return}let x=G,C=[];g.length>0&&C.push({type:"text",text:g});for(let $ of y)C.push({type:"image",data:$.data,mimeType:$.mimeType});let P={text:g,displayText:I??g,attachments:y,flushed:!1};Rt.push(P);let D=()=>{let $=Rt.indexOf(P);$>=0&&Rt.splice($,1),P.messageId!==void 0&&Pn.delete(P.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:be,targetMessageId:x,prompt:C}).then($=>{let Q=$;if(Q.amended&&Q.reason==="ok"){et(1);return}if(D(),Q.reason==="target_completed"){k.notify("previous response finished \u2014 press Enter to send as a new turn"),Ie.setBuffer(g,y),k.refreshPrompt();return}if(Q.reason==="target_cancelled"){k.notify("amend skipped \u2014 previous turn was cancelled"),Ie.setBuffer(g,y),k.refreshPrompt();return}if(Q.reason==="target_not_found"){k.notify("amend skipped \u2014 no matching prompt"),Ie.setBuffer(g,y),k.refreshPrompt();return}}).catch($=>{D(),k.notify(`amend failed: ${$.message}`),Ie.setBuffer(g,y),k.refreshPrompt()})},Zd=async g=>{if(Tn.length===0){k.notify("no modes advertised by agent");return}let y=k.currentModeId(),I=Tn.findIndex(P=>P.id===y),x=I===-1?0:(I+1)%Tn.length,C=Tn[x]?.id;if(C){k.setBanner({currentMode:C});try{await h.request("session/set_mode",{sessionId:be,modeId:C})}catch(P){k.notify(`set_mode failed: ${P.message}`)}}},Tt=g=>{let y=g.replace(/\s+$/,"");if(!y.startsWith("/")||y.includes(`
190
- `))return!1;let I=y.indexOf(" ");switch(I===-1?y:y.slice(0,I)){case"/quit":case"/exit":return Ni(),!0;case"/clear":return ot.clear(),Zn.clear(),Qt.length=0,he=null,Fe=null,Ze=null,Mn.clear(),_n.clear(),W.clear(),ue.clear(),ae.clear(),xe.clear(),k.clearScrollback(),!0;case"/help":{let C=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let P of un)C.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"});if(_s.length>0){C.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let P of _s)C.push({prefix:" ",body:` ${P.name.padEnd(12)} ${P.description??""}`,bodyStyle:"info"})}return k.appendLines(C),!0}case"/agent":{let C=I===-1?"":y.slice(I+1).trim(),P=Oi();if(!P)return k.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!C){let D=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let $ of P.options){let Q=$.value===P.currentValue?"* ":" ";D.push({prefix:" ",body:`${Q}${$.value.padEnd(16)} ${$.name}`,bodyStyle:"info"})}return k.appendLines(D),!0}return P.options.some(D=>D.value===C)?C===P.currentValue?(k.notify(`already on agent ${C}`),!0):(k.notify(`switching to ${C}\u2026`),h.request("session/set_config_option",{sessionId:be,configId:"agent",value:C}).catch(D=>{k.notify(`set_config_option failed: ${D.message}`)}),!0):(k.notify(`unknown agent: ${C}`),!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 Lt().catch(()=>{}),!0;case"/session":{let C=I===-1?"":y.slice(I+1).trim();return C?C==="next"||C==="prev"?(xr(C).catch(P=>{k.notify(`session ${C} failed: ${P.message}`)}),!0):(Os(C).catch(P=>{k.notify(`session switch failed: ${P.message}`)}),!0):(Lt().catch(()=>{}),!0)}case"/rename":{let C=I===-1?"":y.slice(I+1).trim(),P=C.length>0?`/hydra title ${C}`:"/hydra title";return ln(y,y),ji(P,[],y),!0}case"/btw":{let C=I===-1?"":y.slice(I+1).trim();if(!C)return k.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(be==="__new__")return k.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;N+=1;let P=N;O&&(O.cancel(),O=null);let D=null;z!==null&&!V?D=z:z!==null&&(xn(n,z).catch(()=>{}),z=null),V=!1,k.openBtwOverlay(),k.setBtwOverlayStatus({label:"busy",style:"busy"});let $=new Fd({getMaxWidth:()=>{let ce=k.width();return ce>0?ce:void 0}});$.on("changed",()=>{k.setBtwOverlayContent($.getLines())});let Q={};$.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:C}]});let Be=ce=>{$.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ce}})},Ee={};return D!==null&&(Ee.reuseSessionId=D),By(n,be,C,Ee).then(ce=>{if(P!==N){ce.cancel();return}O=ce,z=ce.sessionId,k.setBtwOverlayMeta({sessionId:ce.sessionId}),ce.on("event",le=>{if(P===N)if(le.kind==="update"){$.append(le.update);let Le=Sn(le.update);if(Le&&Le.kind==="usage-update"){let Ns=!1;Le.used!==void 0&&Q.used!==Le.used&&(Q.used=Le.used,Ns=!0),Le.size!==void 0&&Q.size!==Le.size&&(Q.size=Le.size,Ns=!0),Le.costAmount!==void 0&&Q.costAmount!==Le.costAmount&&(Q.costAmount=Le.costAmount,Ns=!0),Le.costCurrency!==void 0&&Q.costCurrency!==Le.costCurrency&&(Q.costCurrency=Le.costCurrency,Ns=!0),Ns&&k.setBtwOverlayMeta({usage:{...Q}})}}else le.kind==="completed"?(k.setBtwOverlayStatus({label:"done",style:"done"}),O=null):le.kind==="cancelled"?(k.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),O=null,z=null):le.kind==="errored"&&(k.setBtwOverlayStatus({label:"errored",style:"errored"}),Be(`btw errored: ${le.error.message}`),z!==null&&xn(n,z).catch(()=>{}),O=null,z=null)})}).catch(ce=>{if(P!==N)return;let le=ce instanceof Error?ce.message:String(ce);k.setBtwOverlayStatus({label:"errored",style:"errored"}),Be(`btw startup failed: ${le}`),k.appendLines([{prefix:" ",body:`btw startup failed: ${le}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(be==="__new__")return k.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let C=I===-1?"":y.slice(I+1).trim(),P=be;return(async()=>{try{let D=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(P)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!D.ok){let le=await D.text().catch(()=>"");k.appendLines([{prefix:" ",body:`/export failed: HTTP ${D.status} ${le}`.trim(),bodyStyle:"info"}]);return}let $=await D.text(),Q=new Date().toISOString().replace(/[:.]/g,"-"),Be=`hydra-${Ge(P)}-${Q}.md`,Ee=C.length>0?We(C):Be,ce=fr.resolve(Ee);await zu.mkdir(fr.dirname(ce),{recursive:!0}),await zu.writeFile(ce,$,{encoding:"utf8",mode:384}),k.appendLines([{prefix:" ",body:`Wrote ${ce}`,bodyStyle:"system"}])}catch(D){k.appendLines([{prefix:" ",body:`/export failed: ${D.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},ji=async(g,y,I)=>{let x=[];g.length>0&&x.push({type:"text",text:g});for(let Ee of y)x.push({type:"image",data:Ee.data,mimeType:Ee.mimeType});et(1);let C={text:g,displayText:I??g,attachments:y,flushed:!1};Rt.push(C),an=!1;let P=!1,D=null,$=Ee=>{typeof pe<"u"&&pe!==null&&pe.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Ee,bodyStyle:"tool-status-fail"}])},Q=!1;$e={text:g,attachments:y,cancel:()=>{if(an){an=!1,Q=!0,$("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:be}).catch(ce=>{$(`force-stop failed: ${ce.message}`)});return}if(P)return;P=!0,h.notify("session/cancel",{sessionId:be}).catch(()=>{});let Ee=Date.now();D=setTimeout(()=>{$e!==null&&(pr>=Ee||(an=!0,$("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Mi)}};let Be;try{let Ee=await h.request("session/prompt",{sessionId:be,prompt:x});Ee&&typeof Ee.stopReason=="string"&&(Be=Ee.stopReason)}catch(Ee){let ce=Rt.indexOf(C);ce>=0&&Rt.splice(ce,1),C.messageId!==void 0&&Pn.delete(C.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:Ee.message,bodyStyle:"tool-status-fail"}])}finally{if($e=null,D!==null&&(clearTimeout(D),D=null),et(-1),C.flushed&&pn===C){let Ee=C.messageId!==void 0&&fn.has(C.messageId);Ee&&C.messageId!==void 0&&fn.delete(C.messageId);let ce={kind:"turn-complete"};Be!==void 0&&(ce.stopReason=Be),Ee&&(ce.amended=!0),A(ce),pn=null}if(Ps!==null){let{text:Ee,attachments:ce}=Ps;Ps=null,Ie.state().buffer.every(Le=>Le==="")&&(Ie.setBuffer(Ee,ce),k.refreshPrompt())}}},ot=new Map,Mn=new Map,_n=new Map,Zn=new Map,Qt=[],es=0,M=`tools:${es}`,W=new Map,ue=new Map,j=new Set,se=new Map,ae=new Map,xe=new Map,he=null,Fe=null,Ze=null,Oe=null,lt=null,ec=e.tui.maxToolItems,Qw=e.tui.maxPlanItems,tc=()=>({maxPlanItems:lt??i.planExpanded?1/0:Qw}),Vu=()=>{if(Oe===null)return;let g=gs(Oe,tc());g.length>0&&k.upsertLines("plan",[{body:""},...g])},Yo="",Cr=null,Gu=0,Xw=()=>{if(Cr===null)return;let g=k.width(),y=ys(Yo,g>0?{maxWidth:g}:void 0);y.length!==0&&k.upsertLines(Cr,y)},Zw=g=>{g.length!==0&&(Cr===null&&(k.ensureSeparator(),Cr=`agent:${Gu}`,Gu+=1,Yo=""),Yo+=g,Xw())},ts=()=>{Cr=null,Yo=""},Ar="",Bs=null,Qu=0,eb=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),tb=()=>{if(Bs===null||Ar.length===0)return;let g=gi(Ar);g.length!==0&&k.upsertLines(Bs,g)},nb=g=>{let y=ae.get(g);if(y===void 0)return[];let I=gi(y.text);return y.workerTaskId&&I.unshift({prefix:" ",body:`[T${y.workerTaskId}] `,bodyStyle:"dim"}),I},sb=(g,y)=>{g.length!==0&&(Bs===null&&(k.ensureSeparator("thought"),Bs=`thought:${Qu}`,Qu+=1,Ar=""),Ar+=g,ae.set(Bs,{text:Ar,workerTaskId:y}),tb())},ns=()=>{Bs=null,Ar=""},Xu=g=>XR({...g,collapsedLimit:ec}),Zu=g=>ue.get(g)??i.toolsExpanded,Xt=()=>{if(he===null)return;let{lines:g,rowOwners:y}=Xu({order:Qt,states:ot,startedAt:he,endedAt:Fe,stopReason:Ze,expanded:Zu(M),perToolExpanded:j});k.upsertLines(M,g),se.set(M,y)},Vo=g=>{let y=W.get(g);if(!y)return;let{lines:I,rowOwners:x}=Xu({order:y.order,states:y.states,startedAt:y.startedAt,endedAt:y.endedAt,stopReason:y.stopReason,expanded:Zu(g),perToolExpanded:j});k.upsertLines(g,I),se.set(g,x)},rb=()=>{he!==null&&!W.has(M)&&Xt();for(let g of W.keys())Vo(g)},nc=()=>{he!==null&&W.set(M,{order:[...Qt],states:new Map(ot),startedAt:he,endedAt:Fe??Date.now(),stopReason:Ze,rowOwners:se.get(M)??[]})},ef=()=>{es+=1,M=`tools:${es}`,he=Date.now(),Fe=null,Ze=null,Xt()};function ib(g){if(!g||typeof g!="object")return null;let y=g,I=Array.isArray(y.content)?y.content:void 0;if(!I)return null;let x=[],C=P=>{if(typeof P=="string"){x.push({text:tt(P)});return}if(P&&typeof P=="object"){let D=P;typeof D.__hydraBlob=="string"&&x.push({hash:D.__hydraBlob})}};for(let P of I){if(!P||typeof P!="object")continue;let D=P;if(D.type==="content"&&D.content&&typeof D.content=="object"){let $=D.content;if($.text!==void 0){C($.text);continue}}if(D.type==="text"&&D.text!==void 0){C(D.text);continue}D.text!==void 0&&C(D.text)}return x.length>0?x:null}let tf=(g,y)=>{let I=y.map(P=>"text"in P?P.text:"").join(`
191
- `);if(I.length===0)return;let{text:x,truncated:C}=ag(I);g.resultText=x,g.resultTruncated=C},Go=new Set,ob=(g,y)=>{!y.some(x=>"hash"in x)||Go.has(g)||(Go.add(g),(async()=>{let x=await Promise.all(y.map(async P=>"text"in P?P:{text:await sc(P.hash)??""}));Go.delete(g);let C=ot.get(g);if(!C)for(let P of W.values()){let D=P.states.get(g);if(D){C=D;break}}if(C){tf(C,x),ot.has(g)&&Xt();for(let[P,D]of W)D.states.has(g)&&Vo(P);k.repaintNow()}})().catch(()=>{Go.delete(g)}))},nf=(g,y,I,x,C,P,D,$,Q,Be)=>{let Ee=!ot.has(g),ce=ot.get(g),le=ce??{initialTitle:y??"tool",latestTitle:y??"tool",status:I??"pending",startedAt:Date.now()};if(!ce&&Q!==void 0&&(le.workerTaskId=Q),ce&&y!==void 0&&(le.latestTitle=y),P!==void 0&&le.detail===void 0&&(le.detail=P),D!==void 0&&le.detailFull===void 0&&(le.detailFull=D),$!==void 0&&$.length>0&&(le.locations=$),ce&&I!==void 0&&(le.status=I),ce||(le.status=I??"pending"),le.endedAt===void 0&&Gl(le.status)&&(le.endedAt=Date.now()),x!==void 0&&(le.errorText=x),C!==void 0&&(le.editDiff=C),Be!==void 0){let Le=ib(Be);Le!==null&&(tf(le,Le),Le.some(Ns=>"hash"in Ns)&&ob(g,Le))}ot.set(g,le),Ee&&(he===null&&(es+=1,M=`tools:${es}`,he=Date.now(),Fe=null,Ze=null),Qt.push(g))},sc=async g=>{try{let y=await h.request("hydra-acp/session/tool_content",{sessionId:be,hash:g});return typeof y?.content=="string"?y.content:null}catch{return null}},Qo=new Set,ab=(g,y)=>{Qo.has(g)||y.oldRef===void 0&&y.newRef===void 0||(Qo.add(g),(async()=>{let[I,x]=await Promise.all([y.oldRef?sc(y.oldRef.hash):Promise.resolve(y.oldText),y.newRef?sc(y.newRef.hash):Promise.resolve(y.newText)]);if(y.oldRef!==void 0&&I===null||y.newRef!==void 0&&x===null){Qo.delete(g);let Be=Yl(y,"diff",{deferredStatus:"error"});Be.length>0&&(k.upsertLines(`editdiff:${g}`,Be),k.repaintNow());return}let P={...y.path!==void 0?{path:y.path}:{},oldText:I??"",newText:x??""};Mn.set(g,P);let D=ot.get(g);D?.editDiff&&(D.editDiff=P),Qo.delete(g);let $=_n.get(g),Q=$===void 0?i.showFileUpdates:$?"diff":"edit";Q!=="none"&&(Xo(g,P,Q==="diff"?"diff":"edit"),k.repaintNow())})())},Xo=(g,y,I)=>{let x=`editdiff:${g}`,C=Yl(y,I);if(C.length===0){k.removeKey(x);return}k.upsertLines(x,C),I==="diff"&&(y.oldRef!==void 0||y.newRef!==void 0)&&k.notifyWhenVisible(x)},db=g=>{if(!g.startsWith("editdiff:"))return;let y=g.slice(9),I=Mn.get(y);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&ab(y,I)},sf=g=>{let y=`editdiff:${g}`,I=i.showFileUpdates,x=ot.get(g),C;if(I==="none"||!x?.editDiff||x.status!=="completed")C=null;else{let D=_n.get(g);C=D!==void 0?D?"diff":"edit":I==="diff"?"diff":"edit"}if(C===null){k.removeKey(y);return}let P=x.editDiff;Mn.set(g,P),Xo(g,P,C)},cb=()=>{let g=i.showFileUpdates;for(let[y,I]of Mn){let x=`editdiff:${y}`,C=_n.get(y),P=C===void 0?g:C?"diff":"edit";if(P==="none"){k.removeKey(x);continue}Xo(y,I,P==="diff"?"diff":"edit")}},lb=g=>{if(!g.path)return null;let y=tt(g.oldText).split(`
182
+ `)})};ne();let oe=new AbortController,Me={onKey:He=>{if(He==="ESCAPE"||He==="CTRL_C"){oe.abort(),Tt();return}},onResize:()=>ne()};$t(Me),(async()=>{try{let He=await Ht(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(E.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:oe.signal});if(!He.ok)throw new Error(`daemon returned HTTP ${He.status}`);let et=await He.json(),St=ln(et),Oe=iu(St,E.status);W=Ad(Oe,!1).replace(/\n$/,"").split(`
183
+ `)}catch(He){if(oe.signal.aborted)return;ie=`failed to load info: ${He.message}`}finally{q=!1,!P&&Se[Se.length-1]===Me&&ne()}})()},Fr=()=>{if(a.length===0){de="no sessions to search",ue();return}$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,st=0,j=null,X=!1,F="input",T=!0,Ns(),tn(),$t({onKey:(W,ie,q)=>{if(F==="input"){if(X)return;if(W==="ESCAPE"||W==="CTRL_C"){Yi();return}if(W==="ENTER"||W==="KP_ENTER"){if($r().trim().length===0)return;sc();return}if((W==="DOWN"||W==="TAB"||W==="CTRL_N")&&H.length>0){F="results",B=0,N=0,De(()=>{Ji(),rs(0,!0),_r(),t.hideCursor()});return}let ne=$.state(),oe=null;if(W==="")oe={type:"key",name:"ctrl-underscore"};else if(W==="\x1B_"||W==="\x1B")oe={type:"key",name:"alt-underscore"};else if(q?.isCharacter)oe={type:"char",ch:W};else{let St=Gd(W);St!==null&&(oe={type:"key",name:St})}if(oe===null){t.moveTo(Ds(),Hs());return}$.feed(oe);let Me=$.state();if(ne.buffer.length===Me.buffer.length&&ne.buffer.every((St,Oe)=>St===Me.buffer[Oe])&&ne.row===Me.row&&ne.col===Me.col){t.moveTo(Ds(),Hs());return}let et=ut;Ns(),ut!==et?tn():_t();return}if(F==="results"){if(W==="ESCAPE"||W==="CTRL_C"){Yi();return}if(W==="CTRL_F"){F="input",Ki(),_r(),Ji();return}if(W==="ENTER"||W==="KP_ENTER"){let oe=H[B];if(!oe)return;let Me=a.find(et=>et.sessionId===oe.sessionId);if(!!Me?.importedFromMachine&&!Me.upstreamSessionId){Ze();let et={kind:"attach",sessionId:oe.sessionId};Me.agentId!==void 0&&(et.agentId=Me.agentId),R(et);return}(async()=>{let et=await yw(t,{sessionId:oe.sessionId,title:oe.title,cwd:oe.cwd},bt);if(et==="cancel"){Ze(),R({kind:"abort"});return}if(et==="back")return;Ze();let St={kind:"attach",sessionId:oe.sessionId,readonly:et==="view"};Me?.agentId!==void 0&&(St.agentId=Me.agentId),R(St)})();return}if(q?.isCharacter&&(W==="n"||W==="N")){let oe=H[B];if(!oe||oe.snippets.length<=1)return;N=(N+1)%oe.snippets.length,rs(B,!0);return}if(q?.isCharacter&&(W==="p"||W==="P")){let oe=H[B];if(!oe||oe.snippets.length<=1)return;N=(N-1+oe.snippets.length)%oe.snippets.length,rs(B,!0);return}let ne=oe=>{if(oe<0&&B===0){F="input",De(()=>{rs(0,!1),_r(),Ji()});return}let Me=Math.min(H.length-1,Math.max(0,B+oe));if(Me===B)return;let He=B,et=st;B=Me,N=0,Ln(),st!==et?Ki():(De(()=>{rs(He,!1),rs(B,!0)}),_r())};switch(W){case"UP":case"SHIFT_TAB":case"CTRL_P":ne(-1);return;case"DOWN":case"TAB":case"CTRL_N":ne(1);return;case"PAGE_UP":ne(-yn());return;case"PAGE_DOWN":ne(yn());return;case"HOME":ne(-B);return;case"END":ne(H.length);return}return}},onResize:()=>tn()})},Js=(E,W,ie)=>{if(S!=="busy"){if(E==="CTRL_O"){bn();return}if(E==="CTRL_L"){Bs();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let q=Y.trim();if(q.length===0){S="normal",x=null,Y="",ue();return}Qi(q);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",x=null,Y="",Ct(),ue();return}if(E==="BACKSPACE"){Y.length>0&&(ge(),Y=Y.slice(0,-1),ue());return}if(E==="CTRL_U"){Y.length>0&&(ge(),Y="",ue());return}if(E==="CTRL_W"){let q=Y.replace(/\s+$/,""),ne=q.lastIndexOf(" "),oe=ne>=0?q.slice(0,ne):"";oe!==Y&&(ge(),Y=oe,ue());return}if(E===""){Je(),ue();return}if(E==="\x1B_"||E==="\x1B"){Ms(),ue();return}if(ie?.isCharacter){ge(),Y+=E,ue();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(E==="y"||E==="Y")){as(S==="confirm-kill"?"kill":"delete");return}if(E==="ESCAPE"||E==="CTRL_C"||E==="ENTER"||E==="KP_ENTER"||ie?.isCharacter&&(E==="n"||E==="N")){S="normal",x=null,ue();return}return}if(sn(),E==="CTRL_F"){Fr();return}if(u===0&&!m){if(E==="ESCAPE"){Bn();return}if(E==="ENTER"||E==="KP_ENTER"){Ze();let Oe=$e.expandedText(),Wt=Ot();Oe.trim().length>0&&(Wt.prompt=Oe),R(Wt);return}if(E==="UP"&&b){let Oe=Date.now(),Wt=Oe-v;if(v=Oe,Wt<w){Ge();return}b=!1}if(E==="DOWN"){let Oe=$e.state(),Wt=Oe.historyIndex!==-1||Oe.queueIndex!==-1,ic=Qt.length===0||ve===Qt.length-1;if(!Wt&&ic&&a.length>0){ct(1);return}}if(E==="PAGE_DOWN"&&(Qt.length===0||ve===Qt.length-1)&&a.length>0){ct(1);return}if(E==="CTRL_P"){a.length>0&&ct(1);return}b=!1;let q=$e.state(),ne=null;if(E==="")ne={type:"key",name:"ctrl-underscore"};else if(E==="\x1B_"||E==="\x1B")ne={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)ne={type:"char",ch:E};else{let Oe=Gd(E);Oe!==null&&(ne={type:"key",name:Oe})}if(ne===null){Ge();return}let oe=$e.feed(ne),Me=$e.state(),He=q.buffer.length===Me.buffer.length&&q.buffer.every((Oe,Wt)=>Oe===Me.buffer[Wt])&&q.row===Me.row&&q.col===Me.col;if(oe.some(Oe=>Oe.type==="exit")){Bn();return}if(He){Ge();return}let et=Zn(Me.buffer,Gt);if(Es(et,Me,Zd).rendered!==Ut){Qe();return}qt();return}if(!m&&ie?.isCharacter&&E==="?"){Un();return}if(m){if(ie?.isCharacter){h+=E,at(),Qe();return}if(E==="BACKSPACE"){h.length>0?(h=h.slice(0,-1),at(),Qe()):(m=!1,at(),Qe());return}if(E==="ESCAPE"||E==="CTRL_C"){m=!1,h="",at(),Qe();return}}if(ie?.isCharacter){if(E==="/"){m=!0,h="",at(),Qe();return}if(E==="n"||E==="N"){ct(1);return}if(E==="p"||E==="P"){ct(-1);return}if(E==="c"||E==="C"){let q=u>0?a[u-1]:void 0,ne=Ot();q?.cwd&&(ne.cwd=q.cwd),Ze(),R(ne);return}if(E==="q"||E==="Q"){Bn();return}if(E==="o"||E==="O"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,at(),ns(q),Qe();return}if(E==="h"||E==="H"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=BR(s.filters.hostFilter,i),at(),ns(q),Qe();return}if(E==="i"&&u>0){let q=a[u-1];if(!q)return;zs(q);return}if(E==="I"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,at(),ns(q),Qe();return}if(E==="r"||E==="R"){let q=u>0?a[u-1]?.sessionId:void 0;os(q);return}if(E==="s"||E==="S"){Dn();return}if((E==="v"||E==="V")&&u>0){let q=a[u-1];if(!q)return;Ze();let ne={kind:"attach",sessionId:q.sessionId,readonly:!0};q.agentId!==void 0&&(ne.agentId=q.agentId),R(ne);return}if((E==="f"||E==="F")&&u>0){let q=a[u-1];if(!q)return;Ze();let ne={kind:"fork",sourceSessionId:q.sessionId,sourceCwd:q.cwd};q.agentId!==void 0&&(ne.sourceAgentId=q.agentId),q.importedFromMachine!==void 0&&(ne.sourceImportedFromMachine=q.importedFromMachine),q.upstreamSessionId!==void 0&&(ne.sourceUpstreamSessionId=q.upstreamSessionId),R(ne);return}if((E==="k"||E==="K")&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-kill",ue();return}if(E==="t"&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},Y=q.title??"",S="rename",ue();return}if(E==="T"&&u>0){let q=a[u-1];if(!q)return;rt({sessionId:q.sessionId});return}if(E==="*"&&u>0){let q=a[u-1];if(!q)return;Nn(q);return}if((E==="d"||E==="D")&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-delete",ue();return}return}switch(E){case"UP":case"SHIFT_TAB":case"CTRL_P":E==="UP"&&(u===1&&(b=!0),v=Date.now()),ct(-1);return;case"DOWN":case"TAB":case"CTRL_N":ct(1);return;case"PAGE_UP":ct(-Xe);return;case"PAGE_DOWN":ct(Xe);return;case"HOME":ct(1-u);return;case"END":ct(f);return;case"ENTER":case"KP_ENTER":{if(Ze(),u===0){R(Ot());return}let q=a[u-1];if(!q){R({kind:"abort"});return}let ne={kind:"attach",sessionId:q.sessionId};q.agentId!==void 0&&(ne.agentId=q.agentId),R(ne);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Bn();return}}};$t({onKey:(E,W,ie)=>Js(E,W,ie),onResize:()=>{P||Qe()}});let jn=()=>{t.grabInput({});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Rt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",Or),process.stdout.write(Ed)),t.on("key",dt),t.on("resize",vt)},Ks=()=>{process.stdout.write(Yn);let E=t;E.stdin&&Rt&&(E.stdin.removeListener("data",Or),E.stdin.on("data",Rt),Rt=null),nn=!1,is="",t.off("key",dt),t.off("resize",vt),t.grabInput(!1),t.hideCursor(!1)};if(jn(),process.platform!=="win32"){let E=!1,W=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),jn(),P||Bs())};Gi=()=>{E||P||(E=!0,Ks(),t.fullscreen(!1),process.stdout.write(`${Fo}${Pd}
184
+ `),process.once("SIGCONT",W),process.kill(process.pid,"SIGTSTP"))}}L=setInterval(qs,3e3)})}function FR(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+Mo(Ue(t),s)}function ec(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 LR(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function BR(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 NR(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[Ve(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ue(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Ju,Zd,_R,vw,$R,OR,Sw=K(()=>{"use strict";Sd();pe();xn();Po();La();xu();qu();Wu();zu();Oi();Cu();Mu();Lo();or();ou();Ju=2,Zd=4,_R=4,vw=4,$R=20,OR=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],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 jR(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function kw(t,e,n){Vn();let s=jR(e,n??DR),r=0,i=()=>{let l=wr(t)-8;return Math.max(1,Math.min(HR,e.length,l))},o=()=>{let l=i();s<r?r=s:s>=r+l&&(r=s-l+1);let f=Math.max(0,e.length-l);r>f&&(r=f),r<0&&(r=0)},a=()=>{o();let l=i(),f=l+4,u=Math.min(UR,Math.max(40,fn(t)-8)),p=Gn(t,{contentHeight:f,contentWidth:u,title:"Select agent"}),m=p.contentW,h=0;t.moveTo(p.contentX,p.contentY+h),t.noFormat(" Which agent should this session use?"),h+=2;let w=Math.min(e.length,r+l);for(let v=r;v<w;v++){let S=e[v];if(!S)continue;let x=v===s?"\u276F":" ",T=S.description??S.name,F=` ${x} ${S.id}`;if(t.moveTo(p.contentX,p.contentY+h),v===s){let $=`${F} ${T}`;t.brightWhite.bgBlue.noFormat(_d(nt($,m),m))}else{t.noFormat(F);let $=m-F.length-2;$>1&&t.dim.noFormat(` ${nt(T,$)}`)}h++}h++,t.moveTo(p.contentX,p.contentY+h);let b=e.length>l?` (${s+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${b}`),p},c=()=>{s<e.length-1&&(s++,a())},d=()=>{s>0&&(s--,a())};return Cs({term:t,render:a,onKey:(l,f,u,p)=>{if(l==="CTRL_C"||l==="CTRL_D"){p({kind:"cancel"});return}if(l==="ESCAPE"){p({kind:"back"});return}if(l==="ENTER"||l==="KP_ENTER"){let m=e[s];m&&p({kind:"select",agentId:m.id,persist:!1});return}if(l==="UP"||l==="SHIFT_TAB"){d();return}if(l==="DOWN"||l==="TAB"){c();return}if(u?.isCharacter){let m=l.toLowerCase();if(m==="s"){let h=e[s];h&&p({kind:"select",agentId:h.id,persist:!0});return}if(m==="j"){c();return}if(m==="k"){d();return}}}})}var DR,HR,UR,Iw=K(()=>{"use strict";Oi();DR="opencode",HR=20,UR=88});import*as Cw from"fs";import*as Aw from"os";import*as tc from"path";function Rw(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 qR(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function WR(t){return t.replace(/\\ /g," ")}function xw(t){return t.replace(/ /g,"\\ ")}function zR(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function JR(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Aw.homedir()+n.slice(1)),tc.isAbsolute(n)?n:tc.resolve(e,n)}function KR(t){let e;try{e=Cw.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Tw(t,e,n=KR){if(!qR(t))return null;let s=WR(t),{dirPrefix:r,base:i}=zR(s),o=JR(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(u=>u.name.startsWith(i)&&(c||!u.name.startsWith(".")));if(d.length===0)return null;let l=d.map(u=>u.isDir?u.name+"/":u.name);if(d.length===1){let u=d[0],p=u.isDir?u.name+"/":u.name;return{replacement:xw(r+p),candidates:l}}let f=Jo(d.map(u=>u.name));return{replacement:xw(r+f),candidates:l}}var Ew=K(()=>{"use strict";Xd()});function Pw(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 Mw(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function _w(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 $w=K(()=>{"use strict"});import{appendFileSync as YR,readFileSync as VR,statSync as GR,renameSync as QR}from"fs";import{nanoid as Ow}from"nanoid";import XR from"terminal-kit";import Vu from"fs/promises";import Ir from"path";function Fw(t){if(!Array.isArray(t))return;let e=Rn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Lw(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 t0(t,e){e.has(t)?e.delete(t):e.add(t)}async function Dw(t){let e=await ye(),n=t.target??await Et(e);jw=e.tui.logMaxBytes,n.isLocal&&!t.target&&await vs(e);let s=XR.terminal;mw(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:hf(e),defaultEnterAction:e.tui.defaultEnterAction},o=Ku(),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 f=t;try{for(;f!==null;)f=await s0(s,e,n,f,r,i,o)}finally{d(),process.off("exit",l)}let u=await No();if(u&&process.stderr.write(`\u2728 ${Do(u)}
186
+ `),process.stdout.isTTY){let p=await cr(e);if(p?.version!==void 0){let m=p.version!==fe,h=gs(e),w=p.configDigest!==void 0&&p.configDigest!==h;if(m||w){let b=m?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${vn()} daemon restart\` to apply.`)+`
187
+ `)}}}if(r.sessionId&&process.stdout.isTTY){let p=Ve(r.sessionId),m=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${vn()} --session ${p}${m}
188
+ `)}}function n0(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 J=Math.max(0,c-a),B=e.slice(J),N=[];for(let j=0;j<J;j++){let X=e[j];if(X===void 0)continue;let Y=n.get(X);Y&&!eu(Y.status)&&N.push(X)}l=[...N,...B]}let f=c-l.length,u=r===null,p=r??Date.now(),m=p-s,h=!u&&i!==null&&i!=="end_turn"?i:null,w=h==="amended",b=w?`amended \xB7 ${Mn(m)}`:`stopped (${h}) \xB7 ${Mn(m)}`,v;if(c===0)h!==null?v=b:v=u?`thinking \xB7 ${Mn(m)}`:`thought \xB7 ${Mn(m)}`;else{let J=c===1?"tool":"tools",B=h!==null?b:u?Mn(m):`took ${Mn(m)}`,N=[`${c} ${J}`,B];u&&d&&f>0&&N.push(`${f} hidden`),v=N.join(" \xB7 ")}let S=c===0&&u,x=w?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":h!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":h!==null?x:"dim"}],H=[null];for(let J of l){let B=n.get(J);if(B){let N=$o(B,p);if($.push(...N),H.push(...N.map(()=>J)),o?.has(J)){let j=cg(B);$.push(...j),H.push(...j.map(()=>J))}}}return{lines:$,rowOwners:H}}async function s0(t,e,n,s,r,i,o){let a=await r0(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",d=a0(t,c);d.write(c);let l=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,m=new Fi({url:l,subprotocols:f,onConnect:async g=>{g||u&&await u()},onDisconnect:g=>{p&&p(g)},log:()=>{}}),h=new Pt(m);await m.start(),h.onNotification(ka,g=>{let y=vp.safeParse(g);y.success&&d.applyProgress(y.data)});let w=[],b=null,v=!1,S=!1,x=(g,y)=>{g&&(b?b(g,y):w.push({event:g,rawUpdate:y}))},T,F=g=>{g!==T&&(T=g,g!==void 0&&k.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},$=null,H=null,J=!1,B=0,N=0,j=!1,X=!1,Y,be=null,V=null,ge=null,Je=()=>setInterval(()=>{if(be===null||de===null)return;let g=ge===null?0:Date.now()-ge;de.setBanner({elapsedMs:Date.now()-be,stalled:g>=ZR}),rn()},1e3),Ms=!1,Ct=g=>{let y=N;N=Math.max(0,N+g);let I=typeof de<"u"&&de!==null;y===0&&N>0?(X=!1,be=Date.now(),ge=Date.now(),ee?.setTurnRunning(!0),I&&de.setBanner({status:"busy",elapsedMs:0,stalled:!1}),V===null&&I&&(V=Je())):y>0&&N===0?(X=!1,be=null,ge=null,ee?.setTurnRunning(!1),V!==null&&(clearInterval(V),V=null),I&&de.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):N>0&&X&&(X=!1,I&&de.setBanner({status:"busy",stalled:!1}))},de=null,ee=null,$e,pn=null,Ce=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]),$n=g=>{let{update:y}=g??{},I=Rn(y,{cwd:gt});i0(y,I),ge=Date.now();let C=y?.sessionUpdate;if(typeof C=="string"&&!Ce.has(C)){let A=y??{};typeof A.messageId=="string"&&($e=A.messageId)}if(C==="prompt_received"?Ct(1):I?.kind==="turn-complete"&&(Ct(-1),J=!0),C==="permission_resolved"){es(y);return}if(C==="hydra_compaction"){Ut(y);return}x(I,y),Ar(y)};h.onNotification("session/update",g=>{if(!v){if(pn!==null){pn.push(g);return}$n(g)}}),h.onNotification("hydra-acp/session/closed",()=>{if(v)return;N>0&&Ct(-N),typeof de<"u"&&de!==null&&de.setBanner({status:"cold",elapsedMs:void 0})});let Ke=new Map,Xe=200,xr=0,Gt=!1,Qt=4e3;h.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;if(typeof y._meta?.["hydra-acp"]?.amending=="string"){let C=y.messageId,A=y.prompt,M=setTimeout(()=>{v||(Ke.delete(C),bt.set(C,Tt(C,A)),de&&ee&&Ze())},Xe);Ke.set(C,M)}else bt.set(y.messageId,Tt(y.messageId,y.prompt)),de&&ee&&Ze();if(at!==void 0&&y.originator?.clientId===at){let C=Ot.shift();C&&(C.messageId=y.messageId,bn.set(y.messageId,C))}}),h.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string"||!bt.has(y.messageId))return;bt.set(y.messageId,Tt(y.messageId,y.prompt));let I=bn.get(y.messageId);if(I){let C=Array.isArray(y.prompt)?y.prompt:[],A="",M=[];for(let U of C){if(!U||typeof U!="object")continue;let O=U;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}de&&ee&&Ze()}),h.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;y.reason==="started"&&(Y=y.messageId);let I=Ke.get(y.messageId);I!==void 0&&(clearTimeout(I),Ke.delete(y.messageId)),bt.delete(y.messageId)&&de&&ee&&Ze();let A=bn.get(y.messageId);A&&(bn.delete(y.messageId),y.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),vt=A))}),h.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let y=g??{};if(!(typeof de<"u"&&de!==null))return;xr=Date.now(),Gt=!0;let C=typeof y.code=="number"?` (${y.code})`:"",A=typeof y.message=="string"&&y.message.length>0?`: ${y.message}`:"";de.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"}])}),h.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let y=g??{};if(typeof y.cancelledMessageId!="string")return;let I=y.cancelledMessageId;dt.add(I),vt!==null&&vt.messageId!==void 0&&vt.messageId===I&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),vt=null,dt.delete(I))});let Ut=g=>{let y=g??{},I=typeof y.phase=="string"?y.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 y.error=="string"?y.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;k.notify(`compaction failed: ${A}`,5e3)}},es=g=>{let y=g??{},I=typeof y.toolCallId=="string"?y.toolCallId:void 0,C;y.outcome&&typeof y.outcome=="object"?C=y.outcome:typeof y.chosenOptionId=="string"&&(C={kind:"selected",optionId:y.chosenOptionId}),Cr(I,C?{outcome:C}:void 0)},ve=null,Cr=(g,y)=>{if(!ve||ve.toolCallId&&g&&ve.toolCallId!==g)return;let I=ve.resolve;ve=null,k.setPermissionPrompt(null),I(y??{outcome:{outcome:"cancelled"}})},Ar=g=>{if(!ve?.toolCallId)return;let y=g??{};y.sessionUpdate!=="tool_call"&&y.sessionUpdate!=="tool_call_update"||y.toolCallId===ve.toolCallId&&(!y.status||y.status==="pending"||Cr(y.toolCallId,void 0))},_s=()=>{if(!ve){k.setPermissionPrompt(null);return}k.setPermissionPrompt({title:ve.title,detail:ve.detail,options:ve.options.map(g=>({label:g.name})),selectedIndex:ve.selectedIndex})},mn=g=>{if(!ve)return;let{options:y,resolve:I}=ve;if(ve=null,k.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};h.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return br(g);let y=g??{},C=(Array.isArray(y.options)?y.options:[]).map(G=>({optionId:G.optionId,name:Ie(G.name??""),...G.kind!==void 0?{kind:G.kind}:{}})),A=y.toolCall?.title??y.toolCall?.name??"tool",M=Ie(A),U=Ie(hy(my(g))),O=y.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(G=>{ve={title:M,detail:U,options:C,selectedIndex:0,resolve:G,toolCallId:O},_s()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let $s,Rr,ut=!0,ts=!1;try{let g=await h.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}});Rr=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ut=!1),ts=Bt(g?._meta??void 0).prompt?.amending===!0}catch{}let Pe=a.sessionId,Xt=a.agentId,gt=a.cwd,Ui,at,ns,Zt,hn,Tr,Er,ss,Os,jt,ji=!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 y={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[mt]:g}}:{}},I=await iy({request:()=>h.request("session/new",y),showBanner:(M,U,O)=>oy(t,M,U,O,{authenticate:G=>h.request("authenticate",{methodId:G})}),resolveOnboarding:async M=>{if(M)try{return(await Wl(n)).find(G=>G.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId});if(I.kind==="cancel")return t.grabInput(!1),m.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),m.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),Pe=C.sessionId,r.sessionId=Pe,r.readonly=!1;let A=Bt(C._meta??void 0);A.clientId&&(at=A.clientId),$s=A.upstreamSessionId,A.agentId&&(Xt=A.agentId),A.cwd&&(gt=A.cwd),A.title&&(Ui=A.title),ns=A.currentModel,Zt=A.currentMode,Os=A.currentUsage,jt=A.turnStartedAt,A.availableCommands&&(hn=Xa(A.availableCommands)),A.availableModes&&(Tr=A.availableModes),Er=Fw(C.configOptions),ss=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 y=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:fe},...Object.keys(g).length>0?{_meta:{[mt]:g}}:{}});Pe=y.sessionId,y.clientId&&(at=y.clientId),r.sessionId=Pe,r.readonly=s.readonly===!0;let I=Bt(y._meta??void 0);ji=I.resurrected===!0,$s=I.upstreamSessionId,I.agentId&&(Xt=I.agentId),I.cwd&&(gt=I.cwd),I.title&&(Ui=I.title),ns=I.currentModel,Zt=I.currentMode,Os=I.currentUsage,jt=I.turnStartedAt,I.availableCommands&&(hn=Xa(I.availableCommands)),I.availableModes&&(Tr=I.availableModes),Er=Fw(y.configOptions),ss=I.queue}let gn=_.tuiHistoryFile(Pe),Ko=_.globalTuiHistoryFile(),ue=await ho(gn).catch(()=>[]),yt=await ho(Ko).catch(()=>[]);yt.length>e.tui.promptHistoryMaxEntries&&(yt=yt.slice(yt.length-e.tui.promptHistoryMaxEntries));let en=[...ue],me=new Qn({history:Fa(yt,en)});ee=me;let Yo=!1,On=(g,y)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let C=(y??g).replace(/\n+$/,""),A=go(ue,I),M=A!==ue;ue=A,en=go(en,C);let U=go(yt,I,e.tui.promptHistoryMaxEntries),O=U!==yt;yt=U,me.setHistory(Fa(yt,en)),M&&ir(gn,ue).catch(()=>{}),O&&gm(Ko,I).catch(()=>{})};N>0&&me.setTurnRunning(!0);let Ge=null,Fs=null;uw(fw(e.tui.ambiguousWidth,process.env)),ug(e.tui.diffContextLines);let Ls=!1,k,qi=()=>{Ls&&(Ls=!1,k.start())},Pr=()=>{Ls||(Ls=!0,k.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",qi),k=new Vd({term:t,dispatcher:me,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"?Pr:void 0,onBlockClick:(g,y)=>{ub(g,y)},onBlockDoubleClick:(g,y)=>lb(g,y),onBlockVisible:g=>{ab(g)},onMouse:g=>{if(g.kind!=="press"||g.button!=="middle")return;let y={type:"attachment-request",source:"primary"};s.readonly===!0&&Lw(y)||re(y)},onKey:g=>{for(let y of g){if(j&&sc(y)||ve&&Hs(y)||Yi(y)||Zo(y)||Ds(y)||Ns(y)||Vo(y))continue;if(y.type==="key"&&y.name==="escape"&&k.isScrolledBack()){k.scrollToBottom();continue}if(y.type==="attachment-paths"){Ye(y.paths);continue}let I=me.feed(y);for(let C of I)s.readonly===!0&&Lw(C)||re(C)}Wi(),k.setBannerSearchIndicator(me.state().historySearchQuery),k.setAttachments(me.state().attachments),k.refreshPrompt()}}),de=k,k.setStickyBottomKey("plan");let Qe=[{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>"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],Bs=hn??[],Fn=Tr??[],At=Er??[],nc=()=>At.find(g=>g.id==="agent"),st=()=>{let g=new Set,y=[];for(let I of[...Qe,...Bs])g.has(I.name)||(g.add(I.name),y.push(I));return y},yn=()=>{let g=me.state().buffer,y=g[0]??"";if(!y.startsWith("/"))return[];if(g.length>1)return[];let I=y.indexOf(" "),C=I===-1?y:y.slice(0,I);if(C.lastIndexOf("/")>0)return[];let A=st().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Ln=[],Wi=()=>{let g=yn();if(g.length>0){Ln=[],k.setCompletions(g);return}k.setCompletions(Ln)},Ns=g=>{if(g.type!=="key"||g.name!=="tab")return Ln.length>0&&(Ln=[]),!1;let y=yn();if(k.isOverlayOpen()&&y.length===0)return k.toggleFocusedPane(),!0;if(y.length>0){Ln=[];let I=me.state().buffer[0]??"",C=ww({matches:y.map(A=>A.name),firstLine:I});return C===null||me.replaceFirstLine(C),!0}return zi()},zi=()=>{let g=me.state(),y=g.buffer[g.row]??"",I=Rw(y,g.col);if(I===null)return!1;let C=Tw(I.token,gt);return C===null?!1:(C.replacement!==I.token&&me.replaceRangeOnCurrentLine(I.start,g.col,C.replacement),Ln=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},Vo=g=>!k.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,H=null),k.closeBtwOverlay(),!0),Ds=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 y=k.scrollbackSearchTerm()+g.ch;return k.updateScrollbackSearchTerm(y),!0}if(g.type==="paste"){let y=k.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return k.updateScrollbackSearchTerm(y),!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 y=k.scrollbackSearchTerm();return y.length===0?k.cancelScrollbackSearch():k.updateScrollbackSearchTerm(y.slice(0,-1)),!0}case"enter":return k.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return k.cancelScrollbackSearch(),!0;default:return!0}return!0},Hs=g=>{if(!ve)return!1;let y=ve.options;if(g.type==="key")switch(g.name){case"up":return ve.selectedIndex=Math.max(0,ve.selectedIndex-1),_s(),!0;case"down":return ve.selectedIndex=Math.min(y.length-1,ve.selectedIndex+1),_s(),!0;case"enter":{let I=y[ve.selectedIndex];return I&&mn(I.optionId),!0}case"escape":case"ctrl-c":return mn(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,C=y[I];return C&&mn(C.optionId),!0}return!0},Ji=Xt||Rr||"?",_t={...Os??{}};d.finalize(),k.start({skipFullscreen:!0}),k.setHideThoughts(!i.showThoughts),k.setSessionbar({agent:Ji,cwd:gt,sessionId:Pe,title:Ui,model:ns,usage:{..._t}}),Zt&&k.setBanner({currentMode:Zt}),No().then(g=>{g&&k.notify(`\u2728 ${Do(g)}`,3e4)}).catch(()=>{});let wt=null,Go=new Promise(g=>{wt=g}),Mr=()=>{h.notify("session/cancel",{sessionId:Pe}).catch(()=>{})},Us=()=>{de!==null&&N===1&&(X=!0,de.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},wn=()=>{if(Ge){Ge.cancel(),Us();return}if(N>0){Mr(),Us();return}tn()},tn=()=>{R(0)},rs=()=>{let g="enqueue prompt (sends now, or queues during a turn)",y="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",y]],...e0]},_r=()=>{if(k.isHelpPromptActive()){k.setHelpPrompt(null);return}k.setHelpPrompt({title:"Hotkeys",entries:rs(),hint:"any key dismisses \xB7 /help lists commands"})},Ki=()=>{j=!1,k.setCompactionPrompt(null),k.setCompactionIndicator("compaction queued...");let g=Pe;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},$r=()=>{j=!1,k.setCompactionPrompt(null)},Qo=g=>{let y=k.compactionPromptSpec();if(!y)return;let I=y.options.length;if(I===0)return;let C=((y.selectedIndex+g)%I+I)%I;C!==y.selectedIndex&&k.setCompactionPrompt({...y,selectedIndex:C})},sc=g=>{if(!j)return!1;if(g.type==="key"){if(g.name==="escape")return $r(),!0;if(g.name==="up")return Qo(-1),!0;if(g.name==="down")return Qo(1),!0;if(g.name==="enter"){let y=k.compactionPromptSpec();return y?.options[y.selectedIndex]?.key==="y"?Ki():$r(),!0}}if(g.type==="char"){let y=g.ch.toLowerCase();if(y==="y"||y==="1")return Ki(),!0;if(y==="n"||y==="2")return $r(),!0}return!0},Yi=g=>k.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",k.setHelpPrompt(null),!0):!1,js=["tools","plan","thoughts","diffs","mouse","enter"],qt=0,rc=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}},Vi=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"}},Xo=()=>({title:"Session options",options:js.map(g=>({label:Vi(g),value:rc(g)})),selectedIndex:qt}),nn=()=>{k.isOptionsPromptActive()&&k.setOptionsPrompt(Xo())},is=()=>{if(k.isOptionsPromptActive()){k.setOptionsPrompt(null);return}qt=0,k.setOptionsPrompt(Xo())},Rt=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,zs.clear(),Fr.clear(),sb();break;case"plan":i.planExpanded=!i.planExpanded,ne=null,et();break;case"thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Dn.clear(),db();break;case"mouse":{let y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}nn()},Gi=g=>{(async()=>{try{switch(g){case"tools":case"plan":k.notify(`${Vi(g)} is session-only \u2014 not saved`);return;case"thoughts":await Zi("showThoughts",i.showThoughts);break;case"diffs":await Zi("showFileUpdates",i.showFileUpdates);break;case"mouse":await Zi("mouse",i.mouseEnabled);break;case"enter":await Zi("defaultEnterAction",i.defaultEnterAction);break}k.notify(`saved default: ${Vi(g)} ${rc(g)}`)}catch(y){k.notify(`save failed: ${y instanceof Error?y.message:String(y)}`)}})()},Zo=g=>{if(!k.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return qt=Math.max(0,qt-1),nn(),!0;case"down":return qt=Math.min(js.length-1,qt+1),nn(),!0;case"enter":{let y=js[qt];return y&&Rt(y),!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 y=parseInt(g.ch,10)-1,I=js[y];return I&&(qt=y,Rt(I)),!0}if(g.ch==="s"||g.ch==="S"){let y=js[qt];return y&&Gi(y),!0}}return!0},Or=()=>{v=!0,$?($.cancel(),$=null,H=null):H!==null&&(Pn(n,H).catch(()=>{}),H=null),process.off("SIGINT",wn),process.platform!=="win32"&&process.off("SIGCONT",qi),V!==null&&(clearInterval(V),V=null);for(let g of Ke.values())clearTimeout(g);Ke.clear(),k.clearWindowTitle(),k.stop({keepFullscreen:!0}),ir(gn,ue).catch(()=>{}),m.close().catch(()=>{})},R=(g=0)=>{Or(),wt&&(wt(null),wt=null),g!==0&&process.exit(g)},P=async()=>{if(!wt)return;$?($.cancel(),$=null,H=null):H!==null&&(Pn(n,H).catch(()=>{}),H=null);let g=me.state().buffer.join(`
189
+ `);g.replace(/\s+$/,"").length>0&&On(g),k.pauseRepaint(),k.stop({keepFullscreen:!0}),ir(gn,ue).catch(()=>{});let y=null,I=null;for(;y===null;){let U=await En(n,{includeNonInteractive:!0}),O=await Yu(t,{cwd:gt,sessions:U,config:e,target:n,currentSessionId:Pe,prefs:o});if(O.kind==="abort"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(O.kind==="exit"){R(0);return}if(O.kind==="new"){y={choice:O,sessions:U};break}if(O.kind==="fork"){let le=await Uw(t,n,O,U);if(le.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(le.kind==="back")continue;y={choice:{kind:"attach",sessionId:le.ctx.sessionId,...le.ctx.agentId?{agentId:le.ctx.agentId}:{}},sessions:U},I={readonly:!1,cwd:le.ctx.cwd},le.ctx.resumeHint!==void 0&&(I.resumeHint=le.ctx.resumeHint);break}let G=U.find(le=>le.sessionId===O.sessionId);if(!(G!==void 0&&!!G.importedFromMachine&&!G.upstreamSessionId&&O.readonly!==!0)){if(n.isLocal&&G&&!G.importedFromMachine&&O.readonly!==!0&&!(await Uo(G.cwd)).ok){let _e=await kr(t,G,{defaultCwd:je(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(_e.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(_e.kind==="back")continue;y={choice:O,sessions:U},I={readonly:!1,cwd:_e.path,resumeHint:{agentId:O.agentId??G.agentId??"",cwd:_e.path,upstreamSessionId:""}};break}y={choice:O,sessions:U};break}let Ae={...s,readonly:!1},ce=await Hw(t,G,O,Ae);if(ce.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}ce.kind!=="back"&&(y={choice:O,sessions:U},I={readonly:Ae.readonly===!0,cwd:ce.ctx.cwd},ce.ctx.resumeHint!==void 0&&(I.resumeHint=ce.ctx.resumeHint))}let{choice:C}=y,A=wt;if(wt=null,process.off("SIGINT",wn),m.close().catch(()=>{}),C.kind==="new"){let{sessionId:U,...O}=s,G={...O,cwd:C.cwd??gt,forceNew:!0,readonly:!1};C.prompt!==void 0&&(G.initialPrompt=C.prompt),A(G);return}if(C.kind!=="attach")return;let M={...s,sessionId:C.sessionId,cwd:I?.cwd??gt,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)},L=async(g="next")=>{if(!wt)return;let I=(await En(n)).filter(Ae=>Ae.status==="live");if(I.length<=1)return;let C=I.findIndex(Ae=>Ae.sessionId===Pe),U=((C===-1?0:C)+(g==="prev"?-1:1)+I.length)%I.length,O=I[U],G=wt;wt=null,process.off("SIGINT",wn),m.close().catch(()=>{});let Fe={...s,sessionId:O.sessionId,cwd:gt,readonly:!1};O.agentId!==void 0&&(Fe.agentId=O.agentId),G(Fe)},Z=async g=>{if(!wt)return;let y=await En(n,{includeNonInteractive:!0}),I=g.trim();if(!I){k.notify("usage: /session <id|next|prev>");return}let C=I.startsWith(Jt)?[I]:[I,Jt+I],A=y.find(O=>C.includes(O.sessionId));if(!A){let O=y.filter(G=>C.some(Fe=>G.sessionId.startsWith(Fe)));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===Pe){k.notify("already on that session");return}let M=wt;wt=null,process.off("SIGINT",wn),m.close().catch(()=>{});let U={...s,sessionId:A.sessionId,cwd:A.cwd??gt,readonly:A.status!=="live"};A.agentId!==void 0&&(U.agentId=A.agentId),delete U.resumeHint,M(U)},re=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Bn(g.text,g.attachments,g.displayText):Ws(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ws(g.text,g.attachments,g.displayText):Bn(g.text,g.attachments,g.displayText);return;case"queue-edit":{let y=qs(g.index);if(!y)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});h.request("hydra-acp/prompt/update",{sessionId:Pe,messageId:y,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 y=qs(g.index);if(!y)return;h.request("hydra-acp/prompt/cancel",{sessionId:Pe,messageId:y}).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()){$&&($.cancel(),$=null,H=null),k.closeBtwOverlay();return}if(g.prefill&&Ge){let y=bt.size===0,I=me.state().buffer.every(C=>C==="");y&&I&&(Fs={text:Ge.text,attachments:Ge.attachments})}Ge?Ge.cancel():N>0&&Mr(),Us();return}case"exit":tn();return;case"plan-toggle":ea(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":L().catch(()=>{});return;case"toggle-options":is();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 y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y,k.notify(y?"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":_r();return;case"escalate-search":k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Se(g.source);return}},Ye=async g=>{if(!ut){k.notify("agent does not accept image attachments");return}let y=0;for(let I of g){if(I.startsWith("data:")){let A=Au(I);if(!A){k.notify("unsupported data: URI");continue}if(A.sizeBytes>_n){k.notify(`image too large (${Vt(A.sizeBytes)}, max ${Vt(_n)})`);continue}me.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),y++;continue}let C=jo(I);if(!C){k.notify(`unsupported image type: ${Ir.basename(I)}`);continue}try{let A=await Vu.readFile(I);if(A.length>_n){k.notify(`image too large (${Vt(A.length)}, max ${Vt(_n)})`);continue}me.addAttachment({mimeType:C,data:A.toString("base64"),name:Ir.basename(I),sizeBytes:A.length}),y++}catch(A){k.notify(`cannot read ${Ir.basename(I)}: ${A.message}`)}}y>0&&(k.setAttachments(me.state().attachments),k.refreshPrompt())},Se=async(g="clipboard")=>{let y=g==="primary"?await Vy():await Yy();if(!y.ok){k.notify(y.reason);return}if(y.kind==="image"){if(!ut){k.notify("agent does not accept image attachments");return}me.addAttachment(y.attachment),k.setAttachments(me.state().attachments),k.refreshPrompt();return}let I=me.feed({type:"paste",text:y.text});for(let C of I)re(C);k.refreshPrompt()},$t=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Tt=(g,y)=>{let I=Array.isArray(y)?y:[],C="",A=0;for(let M of I){if(!M||typeof M!="object")continue;let U=M;U.type==="text"&&typeof U.text=="string"?C+=U.text:U.type==="image"&&(A+=1)}return{messageId:g,text:Ie(C),attachmentCount:A}},bt=new Map,Ot=[],bn=new Map,dt=new Set,vt=null,Ze=()=>{let g=[...bt.values()],y=g.map($t);k.setQueuedPrompts(y),k.setBanner({queued:g.length}),me.setQueue(g.map(I=>I.text))},qs=g=>[...bt.values()][g]?.messageId;if(ss&&ss.length>0){for(let g of ss){if(g.position===0){Y=g.messageId;continue}bt.set(g.messageId,Tt(g.messageId,g.prompt))}bt.size>0&&Ze()}let Ws=(g,y,I)=>{k.scrollToBottom(),!os(g)&&(On(g,I),Qi(g,y,I))},Bn=(g,y,I)=>{if(k.scrollToBottom(),os(g))return;if(On(g,I),!ts||Y===void 0){Qi(g,y,I);return}let C=Y,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of y)A.push({type:"image",data:O.data,mimeType:O.mimeType});let M={text:g,displayText:I??g,attachments:y,flushed:!1};Ot.push(M);let U=()=>{let O=Ot.indexOf(M);O>=0&&Ot.splice(O,1),M.messageId!==void 0&&bn.delete(M.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Pe,targetMessageId:C,prompt:A}).then(O=>{let G=O;if(G.amended&&G.reason==="ok"){Ct(1);return}if(U(),G.reason==="target_completed"){k.notify("previous response finished \u2014 press Enter to send as a new turn"),me.setBuffer(g,y),k.refreshPrompt();return}if(G.reason==="target_cancelled"){k.notify("amend skipped \u2014 previous turn was cancelled"),me.setBuffer(g,y),k.refreshPrompt();return}if(G.reason==="target_not_found"){k.notify("amend skipped \u2014 no matching prompt"),me.setBuffer(g,y),k.refreshPrompt();return}}).catch(O=>{U(),k.notify(`amend failed: ${O.message}`),me.setBuffer(g,y),k.refreshPrompt()})},ea=async g=>{if(Fn.length===0){k.notify("no modes advertised by agent");return}let y=k.currentModeId(),I=Fn.findIndex(M=>M.id===y),C=I===-1?0:(I+1)%Fn.length,A=Fn[C]?.id;if(A){k.setBanner({currentMode:A});try{await h.request("session/set_mode",{sessionId:Pe,modeId:A})}catch(M){k.notify(`set_mode failed: ${M.message}`)}}},os=g=>{let y=g.replace(/\s+$/,"");if(!y.startsWith("/")||y.includes(`
190
+ `))return!1;let I=y.indexOf(" ");switch(I===-1?y:y.slice(0,I)){case"/quit":case"/exit":return tn(),!0;case"/clear":return rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null,Nn.clear(),Dn.clear(),Un.clear(),zs.clear(),jn.clear(),Ks.clear(),k.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of Qe)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(Bs.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of Bs)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return k.appendLines(A),!0}case"/agent":{let A=I===-1?"":y.slice(I+1).trim(),M=nc();if(!M)return k.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let U=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of M.options){let G=O.value===M.currentValue?"* ":" ";U.push({prefix:" ",body:`${G}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return k.appendLines(U),!0}return M.options.some(U=>U.value===A)?A===M.currentValue?(k.notify(`already on agent ${A}`),!0):(k.notify(`switching to ${A}\u2026`),h.request("session/set_config_option",{sessionId:Pe,configId:"agent",value:A}).catch(U=>{k.notify(`set_config_option failed: ${U.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?"":y.slice(I+1).trim();return A?A==="next"||A==="prev"?(L(A).catch(M=>{k.notify(`session ${A} failed: ${M.message}`)}),!0):(Z(A).catch(M=>{k.notify(`session switch failed: ${M.message}`)}),!0):(P().catch(()=>{}),!0)}case"/rename":{let A=I===-1?"":y.slice(I+1).trim(),M=A.length>0?`/hydra title ${A}`:"/hydra title";return On(y,y),Qi(M,[],y),!0}case"/btw":{let A=I===-1?"":y.slice(I+1).trim();if(!A)return k.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(Pe==="__new__")return k.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;B+=1;let M=B;$&&($.cancel(),$=null);let U=null;H!==null&&!J?U=H:H!==null&&(Pn(n,H).catch(()=>{}),H=null),J=!1,k.openBtwOverlay(),k.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new Ud({getMaxWidth:()=>{let ce=k.width();return ce>0?ce:void 0}});O.on("changed",()=>{k.setBtwOverlayContent(O.getLines())});let G={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Fe=ce=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ce}})},Ae={};return U!==null&&(Ae.reuseSessionId=U),Ny(n,Pe,A,Ae).then(ce=>{if(M!==B){ce.cancel();return}$=ce,H=ce.sessionId,k.setBtwOverlayMeta({sessionId:ce.sessionId}),ce.on("event",le=>{if(M===B)if(le.kind==="update"){O.append(le.update);let _e=Rn(le.update);if(_e&&_e.kind==="usage-update"){let Vs=!1;_e.used!==void 0&&G.used!==_e.used&&(G.used=_e.used,Vs=!0),_e.size!==void 0&&G.size!==_e.size&&(G.size=_e.size,Vs=!0),_e.costAmount!==void 0&&G.costAmount!==_e.costAmount&&(G.costAmount=_e.costAmount,Vs=!0),_e.costCurrency!==void 0&&G.costCurrency!==_e.costCurrency&&(G.costCurrency=_e.costCurrency,Vs=!0),Vs&&k.setBtwOverlayMeta({usage:{...G}})}}else le.kind==="completed"?(k.setBtwOverlayStatus({label:"done",style:"done"}),$=null):le.kind==="cancelled"?(k.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,H=null):le.kind==="errored"&&(k.setBtwOverlayStatus({label:"errored",style:"errored"}),Fe(`btw errored: ${le.error.message}`),H!==null&&Pn(n,H).catch(()=>{}),$=null,H=null)})}).catch(ce=>{if(M!==B)return;let le=ce instanceof Error?ce.message:String(ce);k.setBtwOverlayStatus({label:"errored",style:"errored"}),Fe(`btw startup failed: ${le}`),k.appendLines([{prefix:" ",body:`btw startup failed: ${le}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Pe==="__new__")return k.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=I===-1?"":y.slice(I+1).trim(),M=Pe;return(async()=>{try{let U=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!U.ok){let le=await U.text().catch(()=>"");k.appendLines([{prefix:" ",body:`/export failed: HTTP ${U.status} ${le}`.trim(),bodyStyle:"info"}]);return}let O=await U.text(),G=new Date().toISOString().replace(/[:.]/g,"-"),Fe=`hydra-${Ve(M)}-${G}.md`,Ae=A.length>0?je(A):Fe,ce=Ir.resolve(Ae);await Vu.mkdir(Ir.dirname(ce),{recursive:!0}),await Vu.writeFile(ce,O,{encoding:"utf8",mode:384}),k.appendLines([{prefix:" ",body:`Wrote ${ce}`,bodyStyle:"system"}])}catch(U){k.appendLines([{prefix:" ",body:`/export failed: ${U.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Qi=async(g,y,I)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Ae of y)C.push({type:"image",data:Ae.data,mimeType:Ae.mimeType});Ct(1);let A={text:g,displayText:I??g,attachments:y,flushed:!1};Ot.push(A),Gt=!1;let M=!1,U=null,O=Ae=>{typeof de<"u"&&de!==null&&de.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Ae,bodyStyle:"tool-status-fail"}])},G=!1;Ge={text:g,attachments:y,cancel:()=>{if(Gt){Gt=!1,G=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Pe}).catch(ce=>{O(`force-stop failed: ${ce.message}`)});return}if(M)return;M=!0,h.notify("session/cancel",{sessionId:Pe}).catch(()=>{});let Ae=Date.now();U=setTimeout(()=>{Ge!==null&&(xr>=Ae||(Gt=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Qt)}};let Fe;try{let Ae=await h.request("session/prompt",{sessionId:Pe,prompt:C});Ae&&typeof Ae.stopReason=="string"&&(Fe=Ae.stopReason)}catch(Ae){let ce=Ot.indexOf(A);ce>=0&&Ot.splice(ce,1),A.messageId!==void 0&&bn.delete(A.messageId),G?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:Ae.message,bodyStyle:"tool-status-fail"}])}finally{if(Ge=null,U!==null&&(clearTimeout(U),U=null),Ct(-1),A.flushed&&vt===A){let Ae=A.messageId!==void 0&&dt.has(A.messageId);Ae&&A.messageId!==void 0&&dt.delete(A.messageId);let ce={kind:"turn-complete"};Fe!==void 0&&(ce.stopReason=Fe),Ae&&(ce.amended=!0),x(ce),vt=null}if(Fs!==null){let{text:Ae,attachments:ce}=Fs;Fs=null,me.state().buffer.every(_e=>_e==="")&&(me.setBuffer(Ae,ce),k.refreshPrompt())}}},rt=new Map,Nn=new Map,Dn=new Map,as=new Map,Hn=[],ct=0,sn=`tools:${ct}`,Un=new Map,zs=new Map,Fr=new Set,Js=new Map,jn=new Map,Ks=new Map,E=null,W=null,ie=null,q=null,ne=null,oe=e.tui.maxToolItems,Me=e.tui.maxPlanItems,He=()=>({maxPlanItems:ne??i.planExpanded?1/0:Me}),et=()=>{if(q===null)return;let g=Is(q,He());g.length>0&&k.upsertLines("plan",[{body:""},...g])},St="",Oe=null,Wt=0,ic=()=>{if(Oe===null)return;let g=k.width(),y=xs(St,g>0?{maxWidth:g}:void 0);y.length!==0&&k.upsertLines(Oe,y)},Xw=g=>{g.length!==0&&(Oe===null&&(k.ensureSeparator(),Oe=`agent:${Wt}`,Wt+=1,St=""),St+=g,ic())},ds=()=>{Oe=null,St=""},Lr="",Ys=null,Zu=0,Zw=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),eb=()=>{if(Ys===null||Lr.length===0)return;let g=Ai(Lr);g.length!==0&&k.upsertLines(Ys,g)},tb=g=>{let y=jn.get(g);if(y===void 0)return[];let I=Ai(y.text);return y.workerTaskId&&I.unshift({prefix:" ",body:`[T${y.workerTaskId}] `,bodyStyle:"dim"}),I},nb=(g,y)=>{g.length!==0&&(Ys===null&&(k.ensureSeparator("thought"),Ys=`thought:${Zu}`,Zu+=1,Lr=""),Lr+=g,jn.set(Ys,{text:Lr,workerTaskId:y}),eb())},cs=()=>{Ys=null,Lr=""},ef=g=>n0({...g,collapsedLimit:oe}),tf=g=>zs.get(g)??i.toolsExpanded,rn=()=>{if(E===null)return;let{lines:g,rowOwners:y}=ef({order:Hn,states:rt,startedAt:E,endedAt:W,stopReason:ie,expanded:tf(sn),perToolExpanded:Fr});k.upsertLines(sn,g),Js.set(sn,y)},ta=g=>{let y=Un.get(g);if(!y)return;let{lines:I,rowOwners:C}=ef({order:y.order,states:y.states,startedAt:y.startedAt,endedAt:y.endedAt,stopReason:y.stopReason,expanded:tf(g),perToolExpanded:Fr});k.upsertLines(g,I),Js.set(g,C)},sb=()=>{E!==null&&!Un.has(sn)&&rn();for(let g of Un.keys())ta(g)},oc=()=>{E!==null&&Un.set(sn,{order:[...Hn],states:new Map(rt),startedAt:E,endedAt:W??Date.now(),stopReason:ie,rowOwners:Js.get(sn)??[]})},nf=()=>{ct+=1,sn=`tools:${ct}`,E=Date.now(),W=null,ie=null,rn()};function rb(g){if(!g||typeof g!="object")return null;let y=g,I=Array.isArray(y.content)?y.content:void 0;if(!I)return null;let C=[],A=M=>{if(typeof M=="string"){C.push({text:tt(M)});return}if(M&&typeof M=="object"){let U=M;typeof U.__hydraBlob=="string"&&C.push({hash:U.__hydraBlob})}};for(let M of I){if(!M||typeof M!="object")continue;let U=M;if(U.type==="content"&&U.content&&typeof U.content=="object"){let O=U.content;if(O.text!==void 0){A(O.text);continue}}if(U.type==="text"&&U.text!==void 0){A(U.text);continue}U.text!==void 0&&A(U.text)}return C.length>0?C:null}let sf=(g,y)=>{let I=y.map(M=>"text"in M?M.text:"").join(`
191
+ `);if(I.length===0)return;let{text:C,truncated:A}=dg(I);g.resultText=C,g.resultTruncated=A},na=new Set,ib=(g,y)=>{!y.some(C=>"hash"in C)||na.has(g)||(na.add(g),(async()=>{let C=await Promise.all(y.map(async M=>"text"in M?M:{text:await ac(M.hash)??""}));na.delete(g);let A=rt.get(g);if(!A)for(let M of Un.values()){let U=M.states.get(g);if(U){A=U;break}}if(A){sf(A,C),rt.has(g)&&rn();for(let[M,U]of Un)U.states.has(g)&&ta(M);k.repaintNow()}})().catch(()=>{na.delete(g)}))},rf=(g,y,I,C,A,M,U,O,G,Fe)=>{let Ae=!rt.has(g),ce=rt.get(g),le=ce??{initialTitle:y??"tool",latestTitle:y??"tool",status:I??"pending",startedAt:Date.now()};if(!ce&&G!==void 0&&(le.workerTaskId=G),ce&&y!==void 0&&(le.latestTitle=y),M!==void 0&&le.detail===void 0&&(le.detail=M),U!==void 0&&le.detailFull===void 0&&(le.detailFull=U),O!==void 0&&O.length>0&&(le.locations=O),ce&&I!==void 0&&(le.status=I),ce||(le.status=I??"pending"),le.endedAt===void 0&&eu(le.status)&&(le.endedAt=Date.now()),C!==void 0&&(le.errorText=C),A!==void 0&&(le.editDiff=A),Fe!==void 0){let _e=rb(Fe);_e!==null&&(sf(le,_e),_e.some(Vs=>"hash"in Vs)&&ib(g,_e))}rt.set(g,le),Ae&&(E===null&&(ct+=1,sn=`tools:${ct}`,E=Date.now(),W=null,ie=null),Hn.push(g))},ac=async g=>{try{let y=await h.request("hydra-acp/session/tool_content",{sessionId:Pe,hash:g});return typeof y?.content=="string"?y.content:null}catch{return null}},sa=new Set,ob=(g,y)=>{sa.has(g)||y.oldRef===void 0&&y.newRef===void 0||(sa.add(g),(async()=>{let[I,C]=await Promise.all([y.oldRef?ac(y.oldRef.hash):Promise.resolve(y.oldText),y.newRef?ac(y.newRef.hash):Promise.resolve(y.newText)]);if(y.oldRef!==void 0&&I===null||y.newRef!==void 0&&C===null){sa.delete(g);let Fe=Xl(y,"diff",{deferredStatus:"error"});Fe.length>0&&(k.upsertLines(`editdiff:${g}`,Fe),k.repaintNow());return}let M={...y.path!==void 0?{path:y.path}:{},oldText:I??"",newText:C??""};Nn.set(g,M);let U=rt.get(g);U?.editDiff&&(U.editDiff=M),sa.delete(g);let O=Dn.get(g),G=O===void 0?i.showFileUpdates:O?"diff":"edit";G!=="none"&&(ra(g,M,G==="diff"?"diff":"edit"),k.repaintNow())})())},ra=(g,y,I)=>{let C=`editdiff:${g}`,A=Xl(y,I);if(A.length===0){k.removeKey(C);return}k.upsertLines(C,A),I==="diff"&&(y.oldRef!==void 0||y.newRef!==void 0)&&k.notifyWhenVisible(C)},ab=g=>{if(!g.startsWith("editdiff:"))return;let y=g.slice(9),I=Nn.get(y);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&ob(y,I)},of=g=>{let y=`editdiff:${g}`,I=i.showFileUpdates,C=rt.get(g),A;if(I==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let U=Dn.get(g);A=U!==void 0?U?"diff":"edit":I==="diff"?"diff":"edit"}if(A===null){k.removeKey(y);return}let M=C.editDiff;Nn.set(g,M),ra(g,M,A)},db=()=>{let g=i.showFileUpdates;for(let[y,I]of Nn){let C=`editdiff:${y}`,A=Dn.get(y),M=A===void 0?g:A?"diff":"edit";if(M==="none"){k.removeKey(C);continue}ra(y,I,M==="diff"?"diff":"edit")}},cb=g=>{if(!g.path)return null;let y=tt(g.oldText).split(`
192
192
  `),I=tt(g.newText).split(`
193
- `),x=0,C=Math.min(y.length,I.length);for(;x<C&&y[x]===I[x];)x++;let P=I[x];if(!P)return null;let D=fr.isAbsolute(g.path)?g.path:fr.resolve(bt,g.path),$;try{$=zR(D,"utf8")}catch{return null}let Q=$.split(`
194
- `);for(let Be=0;Be<Q.length;Be++)if(Q[Be]===P)return Be+1;return null},ub=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),x=Mn.get(I),P=ot.get(I)?.locations?.[0],D=P?.path??x?.path;if(!D)return!1;let $=null;P?.line!==void 0?$=P.line:x&&($=lb(x));let Q=$===null?"":`:${$}`;return k.tryOpenPathString(D+Q)}if(g.startsWith("tools:")){if(y===0)return!1;let I=se.get(g),x=I?I[y]:void 0;if(!x)return!1;let C=ot.get(x),P=C?.locations?.[0];if(P){let $=P.line===void 0?"":`:${P.line}`;if(k.tryOpenPathString(P.path+$))return!0}let D=C?.detailFull??C?.detail;if(D)return k.tryOpenPathString(D)}return!1},fb=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),x=Mn.get(I);if(!x)return;let C=_n.get(I)??i.showFileUpdates==="diff";_n.set(I,!C),Xo(I,x,C?"edit":"diff"),k.repaintNow();return}if(g==="plan"){if(Oe===null)return;lt=!(lt??i.planExpanded),Vu(),k.repaintNow();return}if(g.startsWith("tools:")){if(y===0){let C=ue.get(g)??i.toolsExpanded;ue.set(g,!C),g===M&&he!==null?Xt():Vo(g),k.repaintNow();return}let I=se.get(g);if(!I)return;let x=I[y];if(!x)return;QR(x,j),Vo(g),k.repaintNow();return}if(g.startsWith("thought:")){if(!ae.has(g))return;let I=xe.get(g);if(I!==void 0){xe.delete(g),k.setRunCollapsed(I,!1,nb(g)),k.repaintNow();return}let x=k.contiguousRun(g,new Set(ae.keys()));if(x.length===0)return;let C=x[0];xe.set(C,x),k.setRunCollapsed(x,!0,[eb()]),k.repaintNow();return}};b=(g,y)=>{if(g.kind==="available-commands"){_s=g.commands,br();return}if(g.kind==="available-modes"){Tn=g.modes;return}if(g.kind==="config-options"){Yn=g.options;let x=g.options.find(P=>P.id==="agent");x&&x.currentValue&&x.currentValue!==wt&&(wt=x.currentValue,k.setSessionbar({agent:x.currentValue}));let C=g.options.find(P=>P.id==="mode");C&&(Tn=C.options.map(P=>({id:P.value,name:P.name??P.value,...P.description!==void 0?{description:P.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!==wt&&(wt=g.agentId,k.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let x=!1;g.used!==void 0&&it.used!==g.used&&(it.used=g.used,x=!0),g.size!==void 0&&it.size!==g.size&&(it.size=g.size,x=!0),g.costAmount!==void 0&&it.costAmount!==g.costAmount&&(it.costAmount=g.costAmount,x=!0),g.costCurrency!==void 0&&it.costCurrency!==g.costCurrency&&(it.costCurrency=g.costCurrency,x=!0),x&&k.setSessionbar({usage:{...it}});return}if(g.kind==="user-text"){$i&&ln(g.text),ts(),ns(),he!==null&&(Fe=Date.now(),Xt()),pn=null,k.ensureSeparator();let x=gs(g);x.length>0&&k.appendLines(x),nc(),k.clearKey("plan"),Oe=null,lt=null,ot.clear(),Zn.clear(),Qt.length=0,Fe=null,ef(),k.redraw();return}if(g.kind==="agent-text"){ns(),Cr===null&&U(g.workerTaskId),Zw(g.text);return}if(g.kind==="agent-thought"){ts(),Bs===null&&U(g.workerTaskId),sb(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){ts(),ns();let x=Zn.get(g.toolCallId),C={plan:g.plan??x?.plan??"",status:g.status??x?.status};if(Zn.set(g.toolCallId,C),C.plan.length===0)return;let P=pg(C);P.length>0&&k.upsertLines(g.toolCallId,P);return}if(g.kind==="tool-call"){ts(),ns(),ot.has(g.toolCallId)||U(g.workerTaskId),nf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),Xt(),sf(g.toolCallId);return}if(g.kind==="plan"){ts(),ns(),Oe=g;let x=gs(g,tc());x.length>0&&k.upsertLines("plan",[{body:""},...x]);let C=g.entries.length>0&&g.entries.every(P=>(P.status??"pending")==="completed");k.setStickyBottomKey(C?null:"plan");return}if(g.kind==="tool-call-update"){ts(),ns(),nf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),g.upstreamInterrupted&&(Ae=!0),Xt(),sf(g.toolCallId);return}g.kind==="model-changed"&&k.setSessionbar({model:g.model});let I=gs(g);if(I.length>0&&k.appendLines(I),g.kind==="turn-complete"){G=void 0,ts(),ns();let x=g.amended?"amended":g.stopReason;if(!g.amended&&Ae&&(x===void 0||x==="end_turn")&&(x="error"),Oe!==null&&x!==void 0&&x!=="end_turn"){let C=gs({...Oe,stopped:!0,amended:g.amended===!0},tc());C.length>0&&k.upsertLines("plan",[{body:""},...C])}Oe=null,lt=null,k.clearKey("plan"),k.setStickyBottomKey("plan"),he!==null?(Fe=Date.now(),Ze=x??null,Xt(),nc()):x!==void 0&&x!=="end_turn"&&x!=="amended"&&k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${x}`,bodyStyle:"tool-status-fail"}]),ot.clear(),Zn.clear(),Qt.length=0,he=null,Fe=null,Ze=null,Ae=!1,k.ensureSeparator(),Pw({pendingTurns:F,queueSize:kt.size,ownTurnInFlight:$e!==null,hasInFlightHead:G!==void 0,replayDraining:S,amended:g.amended===!0})&&et(-F)}};let rf=w;w=[];let Zo=[];for(let{event:g}of rf)g.kind==="user-text"&&typeof g.text=="string"&&Zo.push(g.text);k.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:y}of rf)b(g,y)}finally{S=!1,k.resumeRepaint()}if(Zo.length>0){let g=fl(Qe,Zo);g!==Qe&&(Qe=g,cn=fl(cn,Zo),Ie.setHistory(Ea(Ft,cn)),Ys(Es,Qe).catch(()=>{}))}$i=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(be)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let y=await g.json(),I=y.compactionState?.status;if(I==="requested"||I==="running"?k.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&k.setCompactionIndicator("compaction queued (waiting for idle)"),!dn||y.shouldCompact!==!0)return;let x=y.approxTokens??0;H=!0,k.setCompactionPrompt({message:`This session has ~${Fm(x)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),Gt!==void 0&&F>0?(re=Gt,k.setBanner({status:"busy",elapsedMs:Date.now()-Gt}),Y===null&&(Y=je()),he===null&&ef(),he=Gt,Xt()):Gt===void 0&&F>0&&et(-F);let pb=()=>{if(Re){let g=Re.resolve;Re=null,k.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}ts(),ns()},of=()=>{he!==null&&(Fe=Date.now(),Ze="reconnect-recovery-failed",Xt(),nc(),ot.clear(),Zn.clear(),Qt.length=0,he=null,Fe=null,Ze=null)};return p=()=>{k.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{pb();let g={jsonrpc:"2.0",id:`tui-reinit-${$w()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}}};try{await m.request(g)}catch{}let y=st!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${$w()}`,method:"session/attach",params:{sessionId:be,historyPolicy:y?"after_message":"none",...y?{afterMessageId:st}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let $={};return As!==void 0&&($.resume={upstreamSessionId:As,agentId:wt,cwd:bt}),e.tui.toolContent==="references"&&($.toolContent="references"),Object.keys($).length>0?{_meta:{[pt]:$}}:{}})()}};_t=[];let x,C,P;try{let $=await m.request(I);if($.error)throw new Error($.error.message);P=Ew($.result),x=P.appliedPolicy,P.clientId!==void 0&&(zn=P.clientId)}catch($){C=$}let D=_t??[];if(_t=null,C)of(),k.appendLines([{prefix:" ",body:`reattach failed: ${C.message}`,bodyStyle:"tool-status-fail"}]);else if(y&&x!=="after_message")of(),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 $ of D)$t($)}finally{S=!1}}if(P){let $=Mw({daemonTurnStartedAt:P.turnStartedAt,pendingTurns:F});$.pendingTurnsDelta!==0&&et($.pendingTurnsDelta),$.banner==="busy"&&$.busySince!==void 0?(re=$.busySince,k.setBanner({status:"busy",elapsedMs:Date.now()-$.busySince}),Y===null&&(Y=je())):k.setBanner({status:"ready",elapsedMs:void 0})}else k.setBanner({status:F>0?"busy":"ready",elapsedMs:F>0?0:void 0})},h.onClose(g=>{g&&t.red(`
193
+ `),C=0,A=Math.min(y.length,I.length);for(;C<A&&y[C]===I[C];)C++;let M=I[C];if(!M)return null;let U=Ir.isAbsolute(g.path)?g.path:Ir.resolve(gt,g.path),O;try{O=VR(U,"utf8")}catch{return null}let G=O.split(`
194
+ `);for(let Fe=0;Fe<G.length;Fe++)if(G[Fe]===M)return Fe+1;return null},lb=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=Nn.get(I),M=rt.get(I)?.locations?.[0],U=M?.path??C?.path;if(!U)return!1;let O=null;M?.line!==void 0?O=M.line:C&&(O=cb(C));let G=O===null?"":`:${O}`;return k.tryOpenPathString(U+G)}if(g.startsWith("tools:")){if(y===0)return!1;let I=Js.get(g),C=I?I[y]:void 0;if(!C)return!1;let A=rt.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 U=A?.detailFull??A?.detail;if(U)return k.tryOpenPathString(U)}return!1},ub=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=Nn.get(I);if(!C)return;let A=Dn.get(I)??i.showFileUpdates==="diff";Dn.set(I,!A),ra(I,C,A?"edit":"diff"),k.repaintNow();return}if(g==="plan"){if(q===null)return;ne=!(ne??i.planExpanded),et(),k.repaintNow();return}if(g.startsWith("tools:")){if(y===0){let A=zs.get(g)??i.toolsExpanded;zs.set(g,!A),g===sn&&E!==null?rn():ta(g),k.repaintNow();return}let I=Js.get(g);if(!I)return;let C=I[y];if(!C)return;t0(C,Fr),ta(g),k.repaintNow();return}if(g.startsWith("thought:")){if(!jn.has(g))return;let I=Ks.get(g);if(I!==void 0){Ks.delete(g),k.setRunCollapsed(I,!1,tb(g)),k.repaintNow();return}let C=k.contiguousRun(g,new Set(jn.keys()));if(C.length===0)return;let A=C[0];Ks.set(A,C),k.setRunCollapsed(C,!0,[Zw()]),k.repaintNow();return}};b=(g,y)=>{if(g.kind==="available-commands"){Bs=g.commands,Wi();return}if(g.kind==="available-modes"){Fn=g.modes;return}if(g.kind==="config-options"){At=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==Xt&&(Xt=C.currentValue,k.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(Fn=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!==Xt&&(Xt=g.agentId,k.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&_t.used!==g.used&&(_t.used=g.used,C=!0),g.size!==void 0&&_t.size!==g.size&&(_t.size=g.size,C=!0),g.costAmount!==void 0&&_t.costAmount!==g.costAmount&&(_t.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&_t.costCurrency!==g.costCurrency&&(_t.costCurrency=g.costCurrency,C=!0),C&&k.setSessionbar({usage:{..._t}});return}if(g.kind==="user-text"){Yo&&On(g.text),ds(),cs(),E!==null&&(W=Date.now(),rn()),vt=null,k.ensureSeparator();let C=Is(g);C.length>0&&k.appendLines(C),oc(),k.clearKey("plan"),q=null,ne=null,rt.clear(),as.clear(),Hn.length=0,W=null,nf(),k.redraw();return}if(g.kind==="agent-text"){cs(),Oe===null&&F(g.workerTaskId),Xw(g.text);return}if(g.kind==="agent-thought"){ds(),Ys===null&&F(g.workerTaskId),nb(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){ds(),cs();let C=as.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(as.set(g.toolCallId,A),A.plan.length===0)return;let M=mg(A);M.length>0&&k.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){ds(),cs(),rt.has(g.toolCallId)||F(g.workerTaskId),rf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),rn(),of(g.toolCallId);return}if(g.kind==="plan"){ds(),cs(),q=g;let C=Is(g,He());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"){ds(),cs(),rf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),g.upstreamInterrupted&&(Ms=!0),rn(),of(g.toolCallId);return}g.kind==="model-changed"&&k.setSessionbar({model:g.model});let I=Is(g);if(I.length>0&&k.appendLines(I),g.kind==="turn-complete"){Y=void 0,ds(),cs();let C=g.amended?"amended":g.stopReason;if(!g.amended&&Ms&&(C===void 0||C==="end_turn")&&(C="error"),q!==null&&C!==void 0&&C!=="end_turn"){let A=Is({...q,stopped:!0,amended:g.amended===!0},He());A.length>0&&k.upsertLines("plan",[{body:""},...A])}q=null,ne=null,k.clearKey("plan"),k.setStickyBottomKey("plan"),E!==null?(W=Date.now(),ie=C??null,rn(),oc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null,Ms=!1,k.ensureSeparator(),Mw({pendingTurns:N,queueSize:bt.size,ownTurnInFlight:Ge!==null,hasInFlightHead:Y!==void 0,replayDraining:S,amended:g.amended===!0})&&Ct(-N)}};let af=w;w=[];let ia=[];for(let{event:g}of af)g.kind==="user-text"&&typeof g.text=="string"&&ia.push(g.text);k.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:y}of af)b(g,y)}finally{S=!1,k.resumeRepaint()}if(ia.length>0){let g=gl(ue,ia);g!==ue&&(ue=g,en=gl(en,ia),me.setHistory(Fa(yt,en)),ir(gn,ue).catch(()=>{}))}Yo=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Pe)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let y=await g.json(),I=y.compactionState?.status;if(I==="requested"||I==="running"?k.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&k.setCompactionIndicator("compaction queued (waiting for idle)"),!ji||y.shouldCompact!==!0)return;let C=y.approxTokens??0;j=!0,k.setCompactionPrompt({message:`This session has ~${Lm(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),jt!==void 0&&N>0?(be=jt,k.setBanner({status:"busy",elapsedMs:Date.now()-jt}),V===null&&(V=Je()),E===null&&nf(),E=jt,rn()):jt===void 0&&N>0&&Ct(-N);let fb=()=>{if(ve){let g=ve.resolve;ve=null,k.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}ds(),cs()},df=()=>{E!==null&&(W=Date.now(),ie="reconnect-recovery-failed",rn(),oc(),rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null)};return p=()=>{k.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{fb();let g={jsonrpc:"2.0",id:`tui-reinit-${Ow()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}}};try{await m.request(g)}catch{}let y=$e!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Ow()}`,method:"session/attach",params:{sessionId:Pe,historyPolicy:y?"after_message":"none",...y?{afterMessageId:$e}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let O={};return $s!==void 0&&(O.resume={upstreamSessionId:$s,agentId:Xt,cwd:gt}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[mt]:O}}:{}})()}};pn=[];let C,A,M;try{let O=await m.request(I);if(O.error)throw new Error(O.error.message);M=Pw(O.result),C=M.appliedPolicy,M.clientId!==void 0&&(at=M.clientId)}catch(O){A=O}let U=pn??[];if(pn=null,A)df(),k.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(y&&C!=="after_message")df(),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 U)$n(O)}finally{S=!1}}if(M){let O=_w({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:N});O.pendingTurnsDelta!==0&&Ct(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(be=O.busySince,k.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),V===null&&(V=Je())):k.setBanner({status:"ready",elapsedMs:void 0})}else k.setBanner({status:N>0?"busy":"ready",elapsedMs:N>0?0:void 0})},h.onClose(g=>{g&&t.red(`
195
195
  connection lost: ${g.message}
196
- `),vt(g?1:0)}),process.on("SIGINT",$s),s.initialPrompt&&a.sessionId==="__new__"&&Ui(s.initialPrompt,[]),await Sr}async function e0(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 Bw(t,n,s)!=="ok"?null:Lw(s,i,e);if(s.resume){let o=await In(n,{cwd:i,all:!0}),a=fd(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 In(n,{includeNonInteractive:!0}),a=await Wu(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 Bw(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return Lw(s,i,e)}if(a.kind==="fork"){let l=await Hw(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 Dw(t,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 _o(c.cwd)).ok){let f=await ur(t,c,{defaultCwd:We(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 u=a.agentId??c.agentId??"";return{sessionId:a.sessionId,agentId:u,cwd:f.path,resumeHint:{agentId:u,cwd:f.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Dw(t,e,n,s){for(;;){let r=await mw(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await ur(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function Hw(t,e,n,s){let r=s.find(c=>c.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let c=await ur(t,r);if(c.kind==="cancel")return{kind:"cancel"};if(c.kind==="back")return{kind:"back"};o=c.path}let a;try{a=await ud(e,n.sourceSessionId,i?{cwd:o}:{})}catch(c){return t.red(`
196
+ `),R(g?1:0)}),process.on("SIGINT",wn),s.initialPrompt&&a.sessionId==="__new__"&&Ws(s.initialPrompt,[]),await Go}async function r0(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 Nw(t,n,s)!=="ok"?null:Bw(s,i,e);if(s.resume){let o=await En(n,{cwd:i,all:!0}),a=wd(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 En(n,{includeNonInteractive:!0}),a=await Yu(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 Nw(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return Bw(s,i,e)}if(a.kind==="fork"){let l=await Uw(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 Hw(t,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 Uo(c.cwd)).ok){let f=await kr(t,c,{defaultCwd:je(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 u=a.agentId??c.agentId??"";return{sessionId:a.sessionId,agentId:u,cwd:f.path,resumeHint:{agentId:u,cwd:f.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Hw(t,e,n,s){for(;;){let r=await hw(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await kr(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function Uw(t,e,n,s){let r=s.find(c=>c.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let c=await kr(t,r);if(c.kind==="cancel")return{kind:"cancel"};if(c.kind==="back")return{kind:"back"};o=c.path}let a;try{a=await yd(e,n.sourceSessionId,i?{cwd:o}:{})}catch(c){return t.red(`
198
198
  fork failed: ${c.message}
199
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function Lw(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Bw(t,e,n){if(n.agentId||await bf())return"ok";let s;try{s=await Hl(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await ye(),i=await Sw(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 na(i.agentId)}catch{}return"ok"}function t0(t,e){n0({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function n0(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{r0(n);let s=JSON.stringify({t:new Date().toISOString(),...t});WR(n,`${s}
200
- `)}catch{}}function s0(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,f=c.totalBytes??0,u=(l/1e6).toFixed(1);if(f>0){let p=(f/1e6).toFixed(1),m=Math.min(100,Math.floor(l/f*100));return`${e} downloading ${d} ${u}/${p} MB (${m}%)`}return`${e} downloading ${d} ${u} 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 r0(t){try{if(JR(t).size<Uw)return;KR(t,`${t}.0`)}catch{}}var VR,GR,Uw,jw=J(()=>{"use strict";Js();xt();uu();He();gu();Ws();Zs();ho();Ji();wn();me();Ht();Pd();mu();Pa();So();Ny();Dy();vw();Uu();Hu();kw();lu();Du();xl();vu();Nd();Au();Jd();Tw();_w();ls();yi();VR=12e4;GR=[["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"]];Uw=5*1024*1024});var qw={};af(qw,{runTui:()=>Nw});var Ww=J(()=>{"use strict";jw()});import{readFileSync as i0}from"fs";import{fileURLToPath as o0}from"url";import{dirname as a0,resolve as d0}from"path";var df=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"]),hb=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function cf(t){for(let e of Object.keys(t))if(!df.has(e)&&!hb.has(e))return e}function rc(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(df.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 gb(t,e){let n=t[e];if(typeof n=="string")return n}function Rr(t,e){return t[e]===!0||t[e]==="true"}var yb="HYDRA_ACP_";function wb(t){return yb+t.toUpperCase().replace(/-/g,"_")}function at(t,e){let n=gb(t,e);return n!==void 0?n:process.env[wb(e)]}He();Ws();async function Bf(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=lc(n);return{target:await Ff(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await ye();return{target:await Et(s),sessionId:n,fromUrl:!1}}function Sc(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}me();He();$n();import*as Nf from"fs/promises";async function Df(t){if(await Nf.mkdir(_.home(),{recursive:!0}),await ta(),!await Pr()){let n=Er();await Mr(n),process.stdout.write(`Initialized ${_.authToken()}
199
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function Bw(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Nw(t,e,n){if(n.agentId||await Sf())return"ok";let s;try{s=await Wl(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await ye(),i=await kw(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 da(i.agentId)}catch{}return"ok"}function i0(t,e){o0({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function o0(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{d0(n);let s=JSON.stringify({t:new Date().toISOString(),...t});YR(n,`${s}
200
+ `)}catch{}}function a0(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,f=c.totalBytes??0,u=(l/1e6).toFixed(1);if(f>0){let p=(f/1e6).toFixed(1),m=Math.min(100,Math.floor(l/f*100));return`${e} downloading ${d} ${u}/${p} MB (${m}%)`}return`${e} downloading ${d} ${u} 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 d0(t){try{if(GR(t).size<jw)return;QR(t,`${t}.0`)}catch{}}var ZR,e0,jw,qw=K(()=>{"use strict";sr();It();hu();Ne();vu();tr();lr();xo();to();xn();pe();Nt();Ld();wu();La();Po();Dy();Hy();Sw();zu();Wu();Iw();mu();qu();Tl();xu();Wd();Pu();Xd();Ew();$w();ys();Ri();ZR=12e4;e0=[["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"]];jw=5*1024*1024});var Ww={};cf(Ww,{runTui:()=>Dw});var zw=K(()=>{"use strict";qw()});import{readFileSync as c0}from"fs";import{fileURLToPath as l0}from"url";import{dirname as u0,resolve as f0}from"path";var lf=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"]),mb=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function uf(t){for(let e of Object.keys(t))if(!lf.has(e)&&!mb.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(lf.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 hb(t,e){let n=t[e];if(typeof n=="string")return n}function Br(t,e){return t[e]===!0||t[e]==="true"}var gb="HYDRA_ACP_";function yb(t){return gb+t.toUpperCase().replace(/-/g,"_")}function it(t,e){let n=hb(t,e);return n!==void 0?n:process.env[yb(e)]}Ne();tr();async function Nf(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=mc(n);return{target:await Lf(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await ye();return{target:await Et(s),sessionId:n,fromUrl:!1}}function Cc(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}pe();Ne();qn();import*as Df from"fs/promises";async function Hf(t){if(await Df.mkdir(_.home(),{recursive:!0}),await aa(),!await Hr()){let n=Dr();await Ur(n),process.stdout.write(`Initialized ${_.authToken()}
202
202
  Service token: ${n}
203
- `);return}if(Rr(t,"rotate-token")){let n=Er();await Mr(n),process.stdout.write(`Rotated token in ${_.authToken()}
203
+ `);return}if(Br(t,"rotate-token")){let n=Dr();await Ur(n),process.stdout.write(`Rotated token in ${_.authToken()}
204
204
  New token: ${n}
205
205
  `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
206
206
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
207
- `)}me();$r();He();$n();import{setTimeout as tx}from"timers/promises";import Eh from"chalk";import*as Ih from"fs";import*as ri from"fs/promises";import*as xh from"net";import*as Ch from"tls";import WI from"fastify";import zI from"@fastify/websocket";var Hf="acp.v1";function Uf(t,e){return t.has(Hf)?Hf:!1}He();import kh from"pino";import JI from"pino-roll";me();import*as ft from"fs/promises";import{createHash as Vb}from"crypto";import{gzip as Gb,gunzip as Qb}from"zlib";import{promisify as jf}from"util";var qf=jf(Gb),Xb=jf(Qb),Wf=/^[A-Za-z0-9_-]+$/,Zb=/^[a-f0-9]{64}$/,kc=!0;function zf(t){kc=t}function aa(t,e){return Wf.test(t)?e===void 0||Zb.test(e):!1}function da(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function Ic(t,e){if(!aa(t))return null;let n=Vb("sha256").update(e,"utf8").digest("hex"),s=da(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await ft.access(a),n}catch{}await ft.mkdir(_.toolsDir(t),{recursive:!0});let i=kc?s:r,o=kc?await qf(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await ft.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function ca(t,e){if(!aa(t,e))return null;try{let n=await ft.readFile(da(t,e));return(await Xb(n)).toString("utf8")}catch{}try{return await ft.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Jf(t,e){if(!aa(t,e))return null;try{return await ft.readFile(da(t,e))}catch{}try{let n=await ft.readFile(_.toolBlobFile(t,e));return await qf(n)}catch{return null}}async function Kf(t,e,n){if(!aa(t,e))return;let s=da(t,e);try{await ft.access(s);return}catch{}await ft.mkdir(_.toolsDir(t),{recursive:!0}),await ft.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Yf(t){Wf.test(t)&&await ft.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}me();He();Hs();import*as ip from"fs/promises";import*as ua from"path";import{z as ne}from"zod";me();import*as Gf from"fs";import*as It from"fs/promises";import*as rs from"path";import{spawn as Qf}from"child_process";import{Readable as ev}from"stream";function hn(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function Ac(t,e=hn()){if(e)return t[e]}var Or=t=>{process.stderr.write(t+`
208
- `)};function Rc(t){Or=t??(e=>process.stderr.write(e+`
209
- `))}async function Xf(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${hn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentInstallDir(t.agentId,e,t.version),s=rs.resolve(n,t.target.cmd);if(await Cc(s))return s;if(await tv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Cc(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await It.chmod(s,493).catch(()=>{}),s}async function tv(t){await It.mkdir(rs.dirname(t.installDir),{recursive:!0});let e=await It.mkdtemp(`${t.installDir}.partial-`);try{Or(`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});Or(`hydra-acp: extracting ${t.agentId}`),Fr(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await rv(n,e),await It.unlink(n).catch(()=>{});try{await It.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Cc(t.installDir)){await It.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Fr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Or(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Fr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await It.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Fr(t,e){if(t)try{t(e)}catch{}}async function nv(t){let e=sv(t.url),n=rs.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=Gf.createWriteStream(n),o=ev.fromWeb(s.body);Fr(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-d>=f&&(d=p,Fr(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Or(Vf(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),Or(Vf(t.agentId,a,r,!0)),Fr(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Vf(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 sv(t){let e=new URL(t);return rs.posix.basename(e.pathname)||"archive"}async function rv(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await xc("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await iv("unzip")){await xc("unzip",["-q",t,"-d",e]);return}await xc("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function xc(t,e){return new Promise((n,s)=>{let r=Qf(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 iv(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Qf(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Cc(t){try{return await It.access(t),!0}catch{return!1}}me();import*as Nt from"fs/promises";import*as gn from"path";import{spawn as ov}from"child_process";var Ec=t=>{process.stderr.write(t+`
210
- `)};function Pc(t){Ec=t??(e=>process.stderr.write(e+`
211
- `))}async function ep(t){let e=hn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentNpmInstallDir(t.agentId,e,t.version),s=uv(t.packageSpec),r=fv(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=gn.join(n,"node_modules",".bin",t.bin);if(await zs(o))return o;if(await zs(n)){let f=await Zf(i);if(f)return f.binPath}await av({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await Zf(i);if(a)return a.binPath;let c=await np(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 av(t){await Nt.mkdir(gn.dirname(t.installDir),{recursive:!0});let e=await Nt.mkdtemp(`${t.installDir}.partial-`);try{Ec(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),Tc(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await lv({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Nt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await zs(t.installDir)){await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Tc(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Ec(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),Tc(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Nt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function Tc(t,e){if(t)try{t(e)}catch{}}var dv=5,cv=25;function lv(t){return tp(t,0)}async function tp(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=ov("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<dv)return await new Promise(r=>setTimeout(r,cv*(e+1))),tp(t,e+1);throw n}}function uv(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 fv(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function np(t,e){let n=gn.join(t,"node_modules",e,"package.json");try{let s=await Nt.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 Zf(t){let e=gn.join(t.installDir,"node_modules",".bin"),n=gn.join(e,t.hint);if(await zs(n))return{binName:t.hint,binPath:n};let s=await np(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=gn.join(e,i);if(await zs(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=gn.join(e,i);if(await zs(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=gn.join(e,t.basename);if(await zs(r))return{binName:t.basename,binPath:r}}}async function zs(t){try{return await Nt.access(t),!0}catch{return!1}}var pv=ne.object({package:ne.string(),bin:ne.string().optional(),args:ne.array(ne.string()).optional(),env:ne.record(ne.string()).optional()}),Lr=ne.object({archive:ne.string().url().optional(),cmd:ne.string().optional(),args:ne.array(ne.string()).optional(),env:ne.record(ne.string()).optional()}),mv=ne.object({"darwin-aarch64":Lr.optional(),"darwin-x86_64":Lr.optional(),"linux-aarch64":Lr.optional(),"linux-x86_64":Lr.optional(),"windows-x86_64":Lr.optional(),"windows-aarch64":Lr.optional()}),hv=ne.object({package:ne.string(),args:ne.array(ne.string()).optional(),env:ne.record(ne.string()).optional()}),gv=ne.object({command:ne.string(),args:ne.array(ne.string()).optional(),env:ne.record(ne.string()).optional()}),yv=ne.object({command:ne.string().optional(),url:ne.string().optional(),description:ne.string().optional()}),wv=ne.object({npx:pv.optional(),binary:mv.optional(),uvx:hv.optional(),exec:gv.optional()}),bv=ne.object({id:ne.string(),name:ne.string(),version:ne.string().optional(),description:ne.string().optional(),authors:ne.array(ne.string()).optional(),license:ne.string().optional(),icon:ne.string().optional(),repository:ne.string().optional(),website:ne.string().optional(),distribution:wv,onboarding:yv.optional(),requiredEnv:ne.array(ne.string().min(1)).optional()}),sp=ne.object({version:ne.string(),agents:ne.array(bv),extensions:ne.array(ne.unknown()).optional()}),la=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=>Mc(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:We(n.command??e),args:n.args?.map(We),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:vv(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=sp.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 zt(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=sp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Bt(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function vv(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 Mc(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 Br(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 _c(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function _c(t){let e=hn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Ac(t.distribution.binary,e);if(s?.cmd){let r=ua.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await rp(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Mc(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=ua.join(i,"node_modules",".bin",r);if(await rp(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function rp(t){try{return await ip.access(t),!0}catch{return!1}}async function nn(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??Mc(t)??r.package,a=n.onInstallProgress;return{command:await ep({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=Ac(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${hn()??"this platform"}.`);let i=n.onInstallProgress,o=await Xf({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 Cv}from"child_process";import*as wa from"fs";import*as Sp from"path";xt();function ya(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
- `);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 f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:q.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
207
+ `)}pe();qr();Ne();qn();import{setTimeout as rx}from"timers/promises";import Ph from"chalk";import*as xh from"fs";import*as mi from"fs/promises";import*as Ch from"net";import*as Ah from"tls";import KI from"fastify";import YI from"@fastify/websocket";var Uf="acp.v1";function jf(t,e){return t.has(Uf)?Uf:!1}Ne();import Ih from"pino";import VI from"pino-roll";pe();import*as pt from"fs/promises";import{createHash as Xb}from"crypto";import{gzip as Zb,gunzip as ev}from"zlib";import{promisify as qf}from"util";var Wf=qf(Zb),tv=qf(ev),zf=/^[A-Za-z0-9_-]+$/,nv=/^[a-f0-9]{64}$/,Ac=!0;function Jf(t){Ac=t}function pa(t,e){return zf.test(t)?e===void 0||nv.test(e):!1}function ma(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function Rc(t,e){if(!pa(t))return null;let n=Xb("sha256").update(e,"utf8").digest("hex"),s=ma(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await pt.access(a),n}catch{}await pt.mkdir(_.toolsDir(t),{recursive:!0});let i=Ac?s:r,o=Ac?await Wf(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await pt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function ha(t,e){if(!pa(t,e))return null;try{let n=await pt.readFile(ma(t,e));return(await tv(n)).toString("utf8")}catch{}try{return await pt.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Kf(t,e){if(!pa(t,e))return null;try{return await pt.readFile(ma(t,e))}catch{}try{let n=await pt.readFile(_.toolBlobFile(t,e));return await Wf(n)}catch{return null}}async function Yf(t,e,n){if(!pa(t,e))return;let s=ma(t,e);try{await pt.access(s);return}catch{}await pt.mkdir(_.toolsDir(t),{recursive:!0}),await pt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Vf(t){zf.test(t)&&await pt.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}pe();Ne();Qs();import*as op from"fs/promises";import*as ya from"path";import{z as se}from"zod";pe();import*as Qf from"fs";import*as kt from"fs/promises";import*as us from"path";import{spawn as Xf}from"child_process";import{Readable as sv}from"stream";function Sn(){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 Pc(t,e=Sn()){if(e)return t[e]}var Wr=t=>{process.stderr.write(t+`
208
+ `)};function Mc(t){Wr=t??(e=>process.stderr.write(e+`
209
+ `))}async function Zf(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Sn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Sn();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=us.resolve(n,t.target.cmd);if(await Ec(s))return s;if(await rv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Ec(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await kt.chmod(s,493).catch(()=>{}),s}async function rv(t){await kt.mkdir(us.dirname(t.installDir),{recursive:!0});let e=await kt.mkdtemp(`${t.installDir}.partial-`);try{Wr(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await iv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Wr(`hydra-acp: extracting ${t.agentId}`),zr(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await av(n,e),await kt.unlink(n).catch(()=>{});try{await kt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Ec(t.installDir)){await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),zr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Wr(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),zr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function zr(t,e){if(t)try{t(e)}catch{}}async function iv(t){let e=ov(t.url),n=us.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=Qf.createWriteStream(n),o=sv.fromWeb(s.body);zr(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-d>=f&&(d=p,zr(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Wr(Gf(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),Wr(Gf(t.agentId,a,r,!0)),zr(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Gf(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 ov(t){let e=new URL(t);return us.posix.basename(e.pathname)||"archive"}async function av(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Tc("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await dv("unzip")){await Tc("unzip",["-q",t,"-d",e]);return}await Tc("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Tc(t,e){return new Promise((n,s)=>{let r=Xf(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 dv(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Xf(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Ec(t){try{return await kt.access(t),!0}catch{return!1}}pe();import*as Lt from"fs/promises";import*as kn from"path";import{spawn as cv}from"child_process";var $c=t=>{process.stderr.write(t+`
210
+ `)};function Oc(t){$c=t??(e=>process.stderr.write(e+`
211
+ `))}async function tp(t){let e=Sn();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=mv(t.packageSpec),r=hv(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=kn.join(n,"node_modules",".bin",t.bin);if(await nr(o))return o;if(await nr(n)){let f=await ep(i);if(f)return f.binPath}await lv({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await ep(i);if(a)return a.binPath;let c=await sp(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 lv(t){await Lt.mkdir(kn.dirname(t.installDir),{recursive:!0});let e=await Lt.mkdtemp(`${t.installDir}.partial-`);try{$c(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),_c(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await pv({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Lt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await nr(t.installDir)){await Lt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),_c(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}$c(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),_c(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Lt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function _c(t,e){if(t)try{t(e)}catch{}}var uv=5,fv=25;function pv(t){return np(t,0)}async function np(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=cv("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<uv)return await new Promise(r=>setTimeout(r,fv*(e+1))),np(t,e+1);throw n}}function mv(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 hv(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function sp(t,e){let n=kn.join(t,"node_modules",e,"package.json");try{let s=await Lt.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 ep(t){let e=kn.join(t.installDir,"node_modules",".bin"),n=kn.join(e,t.hint);if(await nr(n))return{binName:t.hint,binPath:n};let s=await sp(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=kn.join(e,i);if(await nr(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=kn.join(e,i);if(await nr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=kn.join(e,t.basename);if(await nr(r))return{binName:t.basename,binPath:r}}}async function nr(t){try{return await Lt.access(t),!0}catch{return!1}}var gv=se.object({package:se.string(),bin:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),Jr=se.object({archive:se.string().url().optional(),cmd:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),yv=se.object({"darwin-aarch64":Jr.optional(),"darwin-x86_64":Jr.optional(),"linux-aarch64":Jr.optional(),"linux-x86_64":Jr.optional(),"windows-x86_64":Jr.optional(),"windows-aarch64":Jr.optional()}),wv=se.object({package:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),bv=se.object({command:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),vv=se.object({command:se.string().optional(),url:se.string().optional(),description:se.string().optional()}),Sv=se.object({npx:gv.optional(),binary:yv.optional(),uvx:wv.optional(),exec:bv.optional()}),kv=se.object({id:se.string(),name:se.string(),version:se.string().optional(),description:se.string().optional(),authors:se.array(se.string()).optional(),license:se.string().optional(),icon:se.string().optional(),repository:se.string().optional(),website:se.string().optional(),distribution:Sv,onboarding:vv.optional(),requiredEnv:se.array(se.string().min(1)).optional()}),rp=se.object({version:se.string(),agents:se.array(kv),extensions:se.array(se.unknown()).optional()}),ga=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(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=>Fc(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:je(n.command??e),args:n.args?.map(je),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:Iv(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=rp.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 zt(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=rp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Ft(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Iv(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 Fc(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 Kr(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 Lc(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Lc(t){let e=Sn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Pc(t.distribution.binary,e);if(s?.cmd){let r=ya.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await ip(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Fc(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=ya.join(i,"node_modules",".bin",r);if(await ip(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function ip(t){try{return await op.access(t),!0}catch{return!1}}async function cn(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??Fc(t)??r.package,a=n.onInstallProgress;return{command:await tp({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=Pc(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Sn()??"this platform"}.`);let i=n.onInstallProgress,o=await Zf({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 Tv}from"child_process";import*as xa from"fs";import*as kp from"path";It();function Ia(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
+ `);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 f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
214
214
  `)}}),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,f=>{if(f){l(f);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Js();me();var Av=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??Av,this.killEscalationMs=e.killEscalationMs??Rv,this.logger=e.logger,this.fileLog=Tv(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=ya(n.stdout,n.stdin);this.connection=new Pt(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()} ---
215
+ `;await new Promise((d,l)=>{e.write(c,f=>{if(f){l(f);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}sr();pe();var Ev=4096,ps=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??Ev,this.killEscalationMs=e.killEscalationMs??Pv,this.logger=e.logger,this.fileLog=Mv(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=Ia(n.stdout,n.stdin);this.connection=new Pt(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
217
  `),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
218
  `),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=Cv(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()} ---
219
+ stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=Tv(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
220
  `),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)})}},Rv=2e3;function Tv(t){try{let e=_.agentLogFile(t);wa.mkdirSync(Sp.dirname(e),{recursive:!0});let n=wa.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as Gs from"fs/promises";import*as $a from"os";import*as uo from"path";import{customAlphabet as LS}from"nanoid";Bc();wn();nl();me();Hs();import*as Ln from"fs/promises";import{z as bn}from"zod";var vS=bn.object({version:bn.literal(1),agentId:bn.string(),upstreamSessionId:bn.string(),deletedAt:bn.string(),upstreamUpdatedAt:bn.string().optional(),cwd:bn.string().optional(),title:bn.string().optional(),reason:bn.enum(["user","expired"]).optional(),interactive:bn.boolean().optional()}),Ca=class{async add(e){let n={version:1,...e};await Bt(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await Ln.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await zt(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 vS.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await Ln.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await Ln.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 Ln.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 Ln.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 Kp(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as am from"fs/promises";xt();Ht();Ia();ka();var IS=12e4;async function Vp(t,e,n){let s=t.timeoutMs??IS,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:fe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let m=CS(d);if(m.size===0||m.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",m=>{let h=xS(m);h.length>0&&f.push(h)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let u=f.join(""),p=n(u);if(!p){let m=JSON.stringify(u.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${u.length} preview=${m})`);let h=u.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${u.length} chars): ${h}${u.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 Gp(t){let e=jr(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}
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)})}},Pv=2e3;function Mv(t){try{let e=_.agentLogFile(t);xa.mkdirSync(kp.dirname(e),{recursive:!0});let n=xa.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as ar from"fs/promises";import*as Da from"os";import*as vo from"path";import{customAlphabet as DS}from"nanoid";Uc();xn();ol();pe();Qs();import*as Jn from"fs/promises";import{z as Cn}from"zod";var IS=Cn.object({version:Cn.literal(1),agentId:Cn.string(),upstreamSessionId:Cn.string(),deletedAt:Cn.string(),upstreamUpdatedAt:Cn.string().optional(),cwd:Cn.string().optional(),title:Cn.string().optional(),reason:Cn.enum(["user","expired"]).optional(),interactive:Cn.boolean().optional()}),Ma=class{async add(e){let n={version:1,...e};await Ft(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await Jn.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await zt(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 IS.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await Jn.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await Jn.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 Jn.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 Jn.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 Yp(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as dm from"fs/promises";It();Nt();Ea();Ta();var AS=12e4;async function Gp(t,e,n){let s=t.timeoutMs??AS,r,i,o=!1;try{let a=(async()=>{r=ps.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:fe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let m=TS(d);if(m.size===0||m.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",m=>{let h=RS(m);h.length>0&&f.push(h)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let u=f.join(""),p=n(u);if(!p){let m=JSON.stringify(u.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${u.length} preview=${m})`);let h=u.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${u.length} chars): ${h}${u.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 Qp(t){let e=Xr(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
222
 
223
223
  ${e}
224
224
 
225
- ${Yc}`:`${n}
225
+ ${Xc}`:`${n}
226
226
 
227
- ${Yc}`;return Vp(t,s,Wp)}async function Qp(t){let e=jr(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}
227
+ ${Xc}`;return Gp(t,s,zp)}async function Xp(t){let e=Xr(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
228
 
229
229
  ${e}
230
230
 
231
- ${Vc}`:`${n}
231
+ ${Zc}`:`${n}
232
232
 
233
- ${Vc}`;return Vp(t,s,zp)}function xS(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 CS(t){let e=new Set;Yp(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Yp(e,n.availableModels),e}function Yp(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)}}}il();me();var AS=2,Ra=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??AS}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 nn(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,f=_.sessionDir(e);if(await am.mkdir(f,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${r.length} model=${JSON.stringify(l??"(default)")} cwd=${f}`),n==="compaction"){let u=this.opts.compactionMaxIterations??3,p=0,m=i??0,h,w=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=${m}`);let S=await this.opts.histories.load(e,{maxEntries:1/0});if(S.length<=m)break;let A=await Qp({agentId:o,cwd:f,plan:c,history:S,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(U,O)=>{this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,iter:p,worker:{upstreamSessionId:U,pid:O??0}})},onFailure:U=>{b=U}});if(A){let U=rm(A.synopsis,S);U&&im(U)&&(await this.opts.persistSynopsis(e,U,S.length),h=U,w=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,U,w),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${p} fields=${om(U)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${p} returned no result`);if(m=S.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(p<u);if(h)p>=u&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${w} iterations=${p}`);else{p>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${u} 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 A=S instanceof Error?S.message:String(S);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${A}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:v,iter:p,lastError:A}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:A})}}else{let u=await Gp({agentId:o,cwd:f,plan:c,history:r,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!u){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let p=rm(u.synopsis,r);p&&im(p)?(await this.opts.persistSynopsis(e,p,r.length),u.title&&await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!u.title)} fields=${om(p)}`)):u.title&&(await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function rm(t,e){let n=tm(e),s=em(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 im(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 om(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(",")}]`}me();import*as Ct from"fs/promises";function dm(t){return t==="summary"?"summary":"inline"}var ol=256;function cm(t,e){return e!=="summary"?t:t.map(RS)}function RS(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(lm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=al(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function TS(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function lm(t){if(TS(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=al(e.text)),typeof e.content=="string"?n.content=al(e.content):e.content&&typeof e.content=="object"&&(n.content=lm(e.content)),n}function al(t){if(typeof t=="string"&&t.length>ol){let e=t.length-ol;return`${t.slice(0,ol)}\u2026[+${e} chars omitted from summary export]`}return t}var ES=2048;function um(t){let e=new Set,n=s=>{if(fm(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 fm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function PS(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 ll(t,e){if(!PS(t))return t;let n=t.params,s=n.update,r=await dl(s,e);return{...t,params:{...n,update:r}}}async function dl(t,e){if(typeof t=="string"){if(t.length<=ES)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 dl(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await dl(r,e);return n}return t}async function pm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await cl(n,e);return s===n?t:{...t,params:s}}async function cl(t,e){if(fm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await cl(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 cl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var so=/^[A-Za-z0-9_-]+$/,MS=1e3,Ta=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??MS}async append(e,n){if(so.test(e))return this.enqueue(e,async()=>{await Ct.mkdir(_.sessionDir(e),{recursive:!0});let s=await ll(n,i=>Ic(e,i)),r=JSON.stringify(s)+`
234
- `;await Ct.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(so.test(e))return this.enqueue(e,async()=>{await Ct.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await ll(i,o=>Ic(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
233
+ ${Zc}`;return Gp(t,s,Jp)}function RS(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 TS(t){let e=new Set;Vp(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Vp(e,n.availableModels),e}function Vp(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)}}}cl();pe();var ES=2,$a=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??ES}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 cn(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,f=_.sessionDir(e);if(await dm.mkdir(f,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${r.length} model=${JSON.stringify(l??"(default)")} cwd=${f}`),n==="compaction"){let u=this.opts.compactionMaxIterations??3,p=0,m=i??0,h,w=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=${m}`);let S=await this.opts.histories.load(e,{maxEntries:1/0});if(S.length<=m)break;let x=await Xp({agentId:o,cwd:f,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:F,pid:$??0}})},onFailure:F=>{b=F}});if(x){let F=im(x.synopsis,S);F&&om(F)&&(await this.opts.persistSynopsis(e,F,S.length),h=F,w=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,F,w),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${p} fields=${am(F)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${p} returned no result`);if(m=S.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(p<u);if(h)p>=u&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${w} iterations=${p}`);else{p>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${u} 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 u=await Qp({agentId:o,cwd:f,plan:c,history:r,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!u){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let p=im(u.synopsis,r);p&&om(p)?(await this.opts.persistSynopsis(e,p,r.length),u.title&&await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!u.title)} fields=${am(p)}`)):u.title&&(await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function im(t,e){let n=nm(e),s=tm(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 om(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 am(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(",")}]`}pe();import*as xt from"fs/promises";function cm(t){return t==="summary"?"summary":"inline"}var ll=256;function lm(t,e){return e!=="summary"?t:t.map(PS)}function PS(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(um));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=ul(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function MS(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function um(t){if(MS(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=ul(e.text)),typeof e.content=="string"?n.content=ul(e.content):e.content&&typeof e.content=="object"&&(n.content=um(e.content)),n}function ul(t){if(typeof t=="string"&&t.length>ll){let e=t.length-ll;return`${t.slice(0,ll)}\u2026[+${e} chars omitted from summary export]`}return t}var _S=2048;function fm(t){let e=new Set,n=s=>{if(pm(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 pm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function $S(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 ml(t,e){if(!$S(t))return t;let n=t.params,s=n.update,r=await fl(s,e);return{...t,params:{...n,update:r}}}async function fl(t,e){if(typeof t=="string"){if(t.length<=_S)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 fl(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await fl(r,e);return n}return t}async function mm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await pl(n,e);return s===n?t:{...t,params:s}}async function pl(t,e){if(pm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await pl(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 pl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var po=/^[A-Za-z0-9_-]+$/,OS=1e3,Oa=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??OS}async append(e,n){if(po.test(e))return this.enqueue(e,async()=>{await xt.mkdir(_.sessionDir(e),{recursive:!0});let s=await ml(n,i=>Rc(e,i)),r=JSON.stringify(s)+`
234
+ `;await xt.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(po.test(e))return this.enqueue(e,async()=>{await xt.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await ml(i,o=>Rc(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
235
235
  `)+`
236
- `;await Ct.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(so.test(e))return this.enqueue(e,async()=>{let s;try{s=await Ct.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 Ct.writeFile(_.historyFile(e),i.join(`
236
+ `;await xt.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(po.test(e))return this.enqueue(e,async()=>{let s;try{s=await xt.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 xt.writeFile(_.historyFile(e),i.join(`
238
238
  `)+`
239
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!so.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Ct.readFile(_.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
240
- `)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&o.push({method:m.method,params:m.params,recordedAt:m.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 u=>{let p=d.get(u);if(p!==void 0)return p;let m=await ca(e,u);return d.set(u,m),m},f=[];for(let u of c)f.push(await pm(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(so.test(e))return this.enqueue(e,async()=>{try{await Ct.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Yf(e);try{await Ct.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}};me();He();Pa();Vs();Sa();xt();Ht();qc();var gm=900*1e3,ym=5e3,wm=3,BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ma=LS(BS,16),_a=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>os.spawn(a)),this.store=s??new xa,this.tombstones=r.tombstones??new Ca,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Ta({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 Ra({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 u=this.compactionDeferrals.get(a)??0;if(u++,u>wm){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,u),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${u}`),l.broadcastCompactionPhase({phase:"deferred",attempts:u}),setTimeout(()=>{this.retrySwap(a)},ym).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(f){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${f instanceof Error?f.message:String(f)}, 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;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>wm){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)},ym).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 Br(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_${Ma()}`,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 Jr({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=q.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 h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=q.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await nn(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 h=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});o=h.agentCapabilities,i.authMethods=co(h.authMethods)}catch(h){throw await i.kill().catch(()=>{}),as(h,i)}let a;try{let h=bm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){if(h&&typeof h=="object"&&h.code===q.AuthRequired)throw await i.kill().catch(()=>{}),as(h,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
241
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=yl(a??{}),d=e.agentModes??ml(gl(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(h=>h.id))}`);let l=await Nr({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 f=pl(a??{}),u=ml(hl(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Dr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new Jr({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:h=>this.bootstrapAgent({...h,mcpServers:h.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(h,w)=>this.bootstrapAgentLoad(h,{...w,mcpServers:w.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:u,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,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(m.sessionId),getCompactionState:()=>this.getCompactionState(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:h=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:h}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}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 Nr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Dr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Jr({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,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),c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Gs.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:We(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=q.AgentNotInstalled,p}let s=await nn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:$a.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),as(p,r)}if(r.authMethods=co(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(),f=[],u=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(c.has(m)){u+=1;continue}if(NS(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!Kp(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let w=`${Jt}${Ma()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:w,lineageId:to(),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 A=tl(S);await this.store.write(A),f.push({version:1,...A})}return{synced:f,skipped:u}}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=q.AgentNotInstalled,i}let s=await nn(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:{},clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=co(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=pl(a),l=hl(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==d){let m=Ur(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,f,h)&&(d=f);else if(m.kind==="resolved")(m.modelId===d||await this.applySeedModel(r,c,m.modelId,`${h} resolved to ${JSON.stringify(m.modelId)}`))&&(d=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let w=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=gl(a),p=yl(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),as(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=q.AgentNotInstalled,o}let r=await nn(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:{},clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=co(o.authMethods);let c=bm(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=pl(d),f=ml(hl(d)),u=gl(d),p=yl(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),as(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=q.AgentNotInstalled,c}let i=await nn(r,[],{npmRegistry:this.npmRegistry}),o=n??We(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});a.authMethods=co(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),as(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=q.AgentNotInstalled,s}return nn(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 s=Vr({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);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",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});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:Sm(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(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=DS(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 ca(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:HS(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,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState}}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=Wr(r.update.prompt),o=Kc(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(Jt))return;let n=Jt+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=q.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,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 lo(n.sessionId),c=Vr({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,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 lo(s.sessionId),i=Vr(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,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=>lo(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=Vr({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let m=u.mtime??new Date(f.updatedAt).toISOString();n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"live",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState})}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=>lo(l.sessionId)));for(let l=0;l<c.length;l+=1){let f=c[l],u=d[l],p=Vr(f,u.hasContent);if(!r(p))continue;let m=u.mtime??f.updatedAt;n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState})}return n.sort((l,f)=>l.updatedAt<f.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=to(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await vm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of um(o)){let l=await Jf(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=q.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=`${Jt}${Ma()}`;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 m=new Error(`source session not found: ${e}`);throw m.code=q.SessionNotFound,m}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=q.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,c;if(n.forkAt!==void 0){if(a=Jc(o,n.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw m.code=q.InvalidParams,m}c=n.forkAt}else{let m=jS(o);m?(a=m.index,c=m.messageId):(a=-1,c="")}let d=o.slice(0,a+1),l=await vm(e),f={...s,lineageId:to(),agentId:r,interactive:!1,...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}:{}},u=ao({record:f,history:d,promptHistory:l.length>0?l:void 0,hydraVersion:fe,machine:$a.hostname()}),p=`${Jt}${Ma()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c}),{sessionId:p,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 Kf(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await Gs.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Ys(_.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,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,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await lo(e),r=Vr(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}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 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 $p(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<gm),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${gm/1e3}s)`),await Xi(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 Xi(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 NS(t,e){if(typeof t!="string"||t.length===0)return!1;let n=uo.resolve(t),s=uo.resolve(e);return n===s||n.startsWith(s+uo.sep)}function DS(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 f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return tl({sessionId:t.sessionId,lineageId:e?.lineageId??to(),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:Sm(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,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Sm(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 HS(t){return t?{...t}:void 0}function bm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Oa(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=US(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function pl(t){return Oa(t,{nestedKey:"models",configId:"model",fromObject:e=>vn(e.currentModelId)??vn(e.currentModel)??vn(e.modelId)??vn(e.model),fromConfig:e=>vn(e.currentValue)})}function as(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==q.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=q.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function co(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 vn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function US(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 ml(t){return t.length>0?t:void 0}function hl(t){return Oa(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=zr(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=zr(e.options);return n.length>0?n:void 0}})??[]}function gl(t){return Oa(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=Zi(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=Zi(e.options);return n.length>0?n:void 0}})??[]}function yl(t){return Oa(t,{nestedKey:"modes",configId:"mode",fromObject:e=>vn(e.currentModeId)??vn(e.currentMode)??vn(e.modeId)??vn(e.mode),fromConfig:e=>vn(e.currentValue)})}function jS(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 vm(t){try{let e=await Gs.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 lo(t){try{let e=await Gs.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Vr(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===Ks?!1:e?!0:void 0}import{spawn as qS}from"child_process";import*as Qr from"fs";import*as ds from"fs/promises";import*as km from"path";var Fa=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_}};He();var WS=1e3,zS=6e4,wl=3e3,Gr=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??WS,this.restartCapMs=r.restartCapMs??zS;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await ds.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},wl);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 fo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw fo(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 fo(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 fo(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 fo(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{}},wl);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 Fa(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await ds.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=km.join(this.adapter.paths.dir(),n),r;try{let i=await ds.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&bl(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+wl;for(;Date.now()<i&&bl(r);)await new Promise(o=>setTimeout(o,50));if(bl(r))try{process.kill(r,"SIGKILL")}catch{}}await ds.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Qr.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})
239
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!po.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await xt.readFile(_.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
240
+ `)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&o.push({method:m.method,params:m.params,recordedAt:m.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 u=>{let p=d.get(u);if(p!==void 0)return p;let m=await ha(e,u);return d.set(u,m),m},f=[];for(let u of c)f.push(await mm(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(po.test(e))return this.enqueue(e,async()=>{try{await xt.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Vf(e);try{await xt.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}};pe();Ne();La();or();Ra();It();Nt();Kc();var ym=900*1e3,wm=5e3,bm=3,HS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ba=DS(HS,16),Na=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>ps.spawn(a)),this.store=s??new Pa,this.tombstones=r.tombstones??new Ma,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Oa({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 $a({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 u=this.compactionDeferrals.get(a)??0;if(u++,u>bm){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,u),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${u}`),l.broadcastCompactionPhase({phase:"deferred",attempts:u}),setTimeout(()=>{this.retrySwap(a)},wm).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(f){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${f instanceof Error?f.message:String(f)}, 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;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>bm){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)},wm).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 Kr(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_${Ba()}`,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 ni({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 h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=z.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await cn(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 h=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});o=h.agentCapabilities,i.authMethods=wo(h.authMethods)}catch(h){throw await i.kill().catch(()=>{}),ms(h,i)}let a;try{let h=vm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){if(h&&typeof h=="object"&&h.code===z.AuthRequired)throw await i.kill().catch(()=>{}),ms(h,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
241
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Sl(a??{}),d=e.agentModes??wl(vl(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(h=>h.id))}`);let l=await Yr({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 f=yl(a??{}),u=wl(bl(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Vr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new ni({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:h=>this.bootstrapAgent({...h,mcpServers:h.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(h,w)=>this.bootstrapAgentLoad(h,{...w,mcpServers:w.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:u,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,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(m.sessionId),getCompactionState:()=>this.getCompactionState(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:h=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:h}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}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 Yr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Vr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new ni({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,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),c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await ar.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:je(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 cn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Da.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),ms(p,r)}if(r.authMethods=wo(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(),f=[],u=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(c.has(m)){u+=1;continue}if(US(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!Yp(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let w=`${Jt}${Ba()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:w,lineageId:uo(),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=il(S);await this.store.write(x),f.push({version:1,...x})}return{synced:f,skipped:u}}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 cn(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:{},clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=wo(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=bl(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==d){let m=Qr(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,f,h)&&(d=f);else if(m.kind==="resolved")(m.modelId===d||await this.applySeedModel(r,c,m.modelId,`${h} resolved to ${JSON.stringify(m.modelId)}`))&&(d=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let w=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=vl(a),p=Sl(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ms(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 cn(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:{},clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=wo(o.authMethods);let c=vm(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),f=wl(bl(d)),u=vl(d),p=Sl(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),ms(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 cn(r,[],{npmRegistry:this.npmRegistry}),o=n??je(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});a.authMethods=wo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),ms(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 cn(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 s=ii({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);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",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});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:km(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(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=jS(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:qS(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,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState}}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=ei(r.update.prompt),o=Qc(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(Jt))return;let n=Jt+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,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 bo(n.sessionId),c=ii({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,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 bo(s.sessionId),i=ii(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,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=>bo(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=ii({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let m=u.mtime??new Date(f.updatedAt).toISOString();n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"live",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState})}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=>bo(l.sessionId)));for(let l=0;l<c.length;l+=1){let f=c[l],u=d[l],p=ii(f,u.hasContent);if(!r(p))continue;let m=u.mtime??f.updatedAt;n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState})}return n.sort((l,f)=>l.updatedAt<f.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=uo(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Sm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of fm(o)){let l=await Kf(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=`${Jt}${Ba()}`;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 m=new Error(`source session not found: ${e}`);throw m.code=z.SessionNotFound,m}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=z.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,c;if(n.forkAt!==void 0){if(a=Gc(o,n.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw m.code=z.InvalidParams,m}c=n.forkAt}else{let m=zS(o);m?(a=m.index,c=m.messageId):(a=-1,c="")}let d=o.slice(0,a+1),l=await Sm(e),f={...s,lineageId:uo(),agentId:r,interactive:!1,...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}:{}},u=yo({record:f,history:d,promptHistory:l.length>0?l:void 0,hydraVersion:fe,machine:Da.hostname()}),p=`${Jt}${Ba()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c}),{sessionId:p,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 Yf(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await ar.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ir(_.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,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,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await bo(e),r=ii(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}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 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 Op(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<ym),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${ym/1e3}s)`),await ao(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 ao(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 US(t,e){if(typeof t!="string"||t.length===0)return!1;let n=vo.resolve(t),s=vo.resolve(e);return n===s||n.startsWith(s+vo.sep)}function jS(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 f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return il({sessionId:t.sessionId,lineageId:e?.lineageId??uo(),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:km(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,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function km(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 qS(t){return t?{...t}:void 0}function vm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ha(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=WS(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function yl(t){return Ha(t,{nestedKey:"models",configId:"model",fromObject:e=>An(e.currentModelId)??An(e.currentModel)??An(e.modelId)??An(e.model),fromConfig:e=>An(e.currentValue)})}function ms(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 wo(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 An(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function WS(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 wl(t){return t.length>0?t:void 0}function bl(t){return Ha(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=ti(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=ti(e.options);return n.length>0?n:void 0}})??[]}function vl(t){return Ha(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=co(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=co(e.options);return n.length>0?n:void 0}})??[]}function Sl(t){return Ha(t,{nestedKey:"modes",configId:"mode",fromObject:e=>An(e.currentModeId)??An(e.currentMode)??An(e.modeId)??An(e.mode),fromConfig:e=>An(e.currentValue)})}function zS(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 Sm(t){try{let e=await ar.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 bo(t){try{let e=await ar.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function ii(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===rr?!1:e?!0:void 0}import{spawn as JS}from"child_process";import*as ai from"fs";import*as hs from"fs/promises";import*as Im from"path";var Ua=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_}};Ne();var KS=1e3,YS=6e4,kl=3e3,oi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??KS,this.restartCapMs=r.restartCapMs??YS;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 hs.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()},kl);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 So(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw So(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 So(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 So(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 So(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{}},kl);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 Ua(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await hs.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=Im.join(this.adapter.paths.dir(),n),r;try{let i=await hs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Il(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+kl;for(;Date.now()<i&&Il(r);)await new Promise(o=>setTimeout(o,50));if(Il(r))try{process.kill(r,"SIGKILL")}catch{}}await hs.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=ai.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
243
  `);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 f=We(d),u=[...l,...r.args].map(We),p;try{p=qS(f,u,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){o.write(`[hydra-acp] failed to spawn ${r.name}: ${m.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{Qr.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
244
+ `),o.end();return}let f=je(d),u=[...l,...r.args].map(je),p;try{p=JS(f,u,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){o.write(`[hydra-acp] failed to spawn ${r.name}: ${m.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{ai.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
246
246
  `,{encoding:"utf8",mode:384})}catch(m){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${m.message}
247
247
  `)}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",m=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${m.message}
248
- `)}),p.on("exit",(m,h)=>{try{Qr.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${h??"null"}
248
+ `)}),p.on("exit",(m,h)=>{try{ai.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${h??"null"}
249
249
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof m=="number"?m:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let w=e.exitWaiters.splice(0);for(let v of w)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(m,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 bl(t){try{return process.kill(t,0),!0}catch{return!1}}function fo(t,e){return t.code=e,t}me();var JS={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},La=class extends Gr{constructor(e,n,s={}){super(e,JS,n,s)}};me();var KS={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},Ba=class extends Gr{connected=new Map;constructor(e,n,s={}){super(e,KS,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 Na=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{}}};me();$r();me();import*as mo from"fs/promises";import*as Da from"path";var po=t=>{process.stderr.write(t+`
251
- `)};function vl(t){po=t??(e=>process.stderr.write(e+`
252
- `))}async function Im(t,e){let n=hn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Da.join(_.agentsDir(),n),a;try{a=await mo.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;po(`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 f=i.get(d)??new Set,u=Da.join(o,d),p;try{p=await mo.readdir(u,{withFileTypes:!0})}catch(m){po(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let w=Da.join(u,h);try{await mo.rm(w,{recursive:!0,force:!0}),po(`hydra-acp: pruned stale ${d} ${h} (${w})`)}catch(b){po(`hydra-acp: prune: failed to remove ${w}: ${b.message}`)}}}}function xm(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 f of l.agents)await _c(f)==="yes"&&a.push(f.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:f}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${f}`)}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 Sl(t){let e=t.maxDeletions??200,n=(p,m)=>{t.logger&&t.logger[p](`session-gc: ${m}`)},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 h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.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)&&(d+=1)}catch(m){l+=1,n("warn",`delete ${p} failed: ${m.message}`)}let f=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 ${YS(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:d,failed:l,deferred:f};return c!==void 0&&(u.oldestLastUsedMs=c),u}function Cm(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Sl({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 YS(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`}Ht();ho();me();Hs();import*as Tm from"path";import{createHash as GS,randomBytes as QS,timingSafeEqual as XS}from"crypto";var Em="hydra_session_",ZS=3600*24*30,Am=12,ek=32,tk=50;function nk(){return Tm.join(_.home(),"session-tokens.json")}function Rm(t){return GS("sha256").update(t).digest("hex")}function Pm(t){return QS(t).toString("hex")}function sk(){return Pm(Am).slice(0,Am*2)}function rk(){return`${Em}${Pm(ek)}`}var Ha=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=nk(),s=await zt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(ik));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=rk(),s=Rm(n),r=sk(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ZS,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(Em))return;let n=Rm(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||!XS(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(()=>{})},tk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Bt(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 ik(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")}$n();var Mm="Bearer ",Ua=class{constructor(e){this.token=e}token;async validate(e){return ok(e,this.token)?"service":void 0}},ja=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},qa=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 _m(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Mm)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Mm.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function $m(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 Wa=class{tokens=new Map;mint(e,n){let s=Er();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 ok(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 za=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)}};me();He();xl();Vs();Ya();import*as Tl from"fs";import*as wo from"os";import*as Xm from"path";import*as El from"readline";ls();wn();function Va(t){let e=Ok(t),n=Fk(e),s=[];Lk(s,t),Bk(s,e,n);let r=s.join(`
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 Il(t){try{return process.kill(t,0),!0}catch{return!1}}function So(t,e){return t.code=e,t}pe();var VS={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},ja=class extends oi{constructor(e,n,s={}){super(e,VS,n,s)}};pe();var GS={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},qa=class extends oi{connected=new Map;constructor(e,n,s={}){super(e,GS,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 Wa=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{}}};pe();qr();pe();import*as Io from"fs/promises";import*as za from"path";var ko=t=>{process.stderr.write(t+`
251
+ `)};function xl(t){ko=t??(e=>process.stderr.write(e+`
252
+ `))}async function xm(t,e){let n=Sn();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=za.join(_.agentsDir(),n),a;try{a=await Io.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 f=i.get(d)??new Set,u=za.join(o,d),p;try{p=await Io.readdir(u,{withFileTypes:!0})}catch(m){ko(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let w=za.join(u,h);try{await Io.rm(w,{recursive:!0,force:!0}),ko(`hydra-acp: pruned stale ${d} ${h} (${w})`)}catch(b){ko(`hydra-acp: prune: failed to remove ${w}: ${b.message}`)}}}}function Cm(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 f of l.agents)await Lc(f)==="yes"&&a.push(f.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:f}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${f}`)}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 Cl(t){let e=t.maxDeletions??200,n=(p,m)=>{t.logger&&t.logger[p](`session-gc: ${m}`)},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 h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.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)&&(d+=1)}catch(m){l+=1,n("warn",`delete ${p} failed: ${m.message}`)}let f=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 ${QS(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:d,failed:l,deferred:f};return c!==void 0&&(u.oldestLastUsedMs=c),u}function Am(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Cl({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 QS(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`}Nt();xo();pe();Qs();import*as Em from"path";import{createHash as ZS,randomBytes as ek,timingSafeEqual as tk}from"crypto";var Pm="hydra_session_",nk=3600*24*30,Rm=12,sk=32,rk=50;function ik(){return Em.join(_.home(),"session-tokens.json")}function Tm(t){return ZS("sha256").update(t).digest("hex")}function Mm(t){return ek(t).toString("hex")}function ok(){return Mm(Rm).slice(0,Rm*2)}function ak(){return`${Pm}${Mm(sk)}`}var Ja=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=ik(),s=await zt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(dk));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=ak(),s=Tm(n),r=ok(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:nk,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(Pm))return;let n=Tm(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||!tk(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(()=>{})},rk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Ft(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 dk(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")}qn();var _m="Bearer ",Ka=class{constructor(e){this.token=e}token;async validate(e){return ck(e,this.token)?"service":void 0}},Ya=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Va=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 $m(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(_m)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(_m.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Om(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 Ga=class{tokens=new Map;mint(e,n){let s=Dr();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 ck(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 Qa=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)}};pe();Ne();Tl();or();ed();import*as _l from"fs";import*as Ro from"os";import*as Zm from"path";import*as $l from"readline";ys();xn();function td(t){let e=Bk(t),n=Nk(e),s=[];Dk(s,t),Hk(s,e,n);let r=s.join(`
253
253
  `);return r.endsWith(`
254
254
  `)||(r+=`
255
- `),r}function Ok(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=Sn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Fk(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 Lk(t,e){let n=e.session,s=Ge(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${Qs(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?`${Al(a.size)}`:void 0;c.push(d?`${Al(a.used)} / ${d} tokens`:`${Al(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 Bk(t,e,n){if(!e.some(d=>Nk(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(`> ${Qs(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 f of l)t.push(`> _${Qs(f)}_`);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(`- ${Hk(l.status)} ${Dk(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 f=l.status==="completed"?"[x]":"[ ]";t.push(`- ${f} ${Qs(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${Qs(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${Qs(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Nk(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Dk(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${Qs(t.title)}${n}`}function Hk(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 Qs(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Al(t){return t.toLocaleString("en-US")}xt();Ht();zi();ls();function Uk(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 f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>jk(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function jk(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:Wm(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:Wm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function Wm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function qk(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Wk=5,zk=200,zm=30;async function Ym(t,e,n={}){let s=Uk(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Wk,i=n.maxSessions??zk,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(f=>o.has(f.sessionId)):a,d=[],l=!1;for(let f of c){if(d.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Jk(u,s,r);if(p.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(m.title=f.title),d.push(m)}return{query:e,truncated:l,results:d}}function Jk(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=Kk(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 Kk(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=Yk(a).filter(d=>qk(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(i+=u,o.length<s){let p=l.indexOf(r),m={kind:d.kind,text:Zk(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(m.toolName=d.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Yk(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=Ga(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?tt(s.text):Ga(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Qk(s))return[];let i=Ga(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Xk(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Vk(s);default:return[]}}function Vk(t){let e=Jm(t,"name"),n=Jm(t,"title"),s=[];if(n!==void 0){let a=Se(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=Se(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Km(r);if(a.length>0){let c={kind:"tool-input",text:Se(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Km(i);if(a.length>0){let c={kind:"tool-input",text:Se(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Gk(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Gk(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=Se(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=Se(s);if(r.length>0)return r}}return null}function Qk(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 Ga(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?tt(e.text):""}function Xk(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=Ga(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 Km(t){try{return JSON.stringify(t)}catch{return""}}function Zk(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-zm),c=Math.min(s.length,o+i.length+zm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Gm}from"crypto";function Vm(t){let e=Gm(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 Rl(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(Vm({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Vm({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=ei(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function ei(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=Gm(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 Qa=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Qm(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!Us(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function Zm(t,e,n,s={}){t.get("/v1/sessions",async c=>{let d=c.query,l=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:l})}}),t.get("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.getOne(f);return u||(d.code(404).send({error:"session not found"}),d)}),t.post("/v1/sessions/search",async(c,d)=>{let l=c.body??{},f=typeof l.q=="string"?l.q:"";if(f.trim().length===0)return d.code(400).send({error:"q is required"}),d;let u=Array.isArray(l.sessionIds)?l.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Ym(e,f,{sessionIds:u})}),t.post("/v1/sessions",async(c,d)=>{let l=c.body??{},f=We(l.cwd??n.cwd),u=l.agentId??n.agentId,p=ei(s),m=p!==void 0?[...l.mcpServers??[],...p.descriptors]:l.mcpServers;try{let h=await e.create({cwd:f,agentId:u,mcpServers:m});p!==void 0&&p.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){p!==void 0&&p.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),t.post("/v1/sessions/collect",async(c,d)=>{let l=c.body??{},f=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,u=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,p=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let m=await Sl({manager:e,maxAgeMs:f,maxDeletions:u,selection:p,verbose:!1});d.code(200).send(m)}catch(m){d.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){u.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m={};(p.mode==="memory"||p.mode==="file")&&(m.mode=p.mode),typeof p.capacityBytes=="number"&&(m.capacityBytes=p.capacityBytes),typeof p.fileCapBytes=="number"&&(m.fileCapBytes=p.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=h=>Xm.join(wo.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return u.openStream(m)}catch(h){return d.code(409).send({error:h.message}),d}}),t.post("/v1/sessions/:id/stdin",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m=typeof p.chunk=="string"?p.chunk:"",h=p.eof===!0;try{return u.streamWrite(m,h)}catch(w){return d.code(409).send({error:w.message}),d}}),t.patch("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{};if(u.priority!==void 0){let m=u.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(u.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),d.code(202).send();return}if(typeof u.title!="string"||u.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,u.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.delete("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){await u.close({deleteRecord:!0}),d.code(204).send();return}if(!await e.deleteRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.get("/v1/sessions/:id/export",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.query?.tools,p=u==="references"?"references":dm(u),m=await e.exportBundle(f,p==="references"?{tools:"references"}:{});if(!m){d.code(404).send({error:"session not found"});return}let h=ao({record:m.record,history:p==="summary"?cm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:wo.hostname(),hydraHost:Qm(n)}),w=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),d.code(200).send(h)}),t.get("/v1/sessions/:id/diff",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=c.query??{},m=p.fold==="true"||p.fold==="1",h=typeof p.paths=="string"&&p.paths.length>0?new Set(p.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,w=Xr(u.history);h&&(w=w.filter(b=>h.has(b.path))),m&&(w=w.map(b=>({...b,hunks:Zr(b.hunks)}))),d.code(200).send(w)}),t.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let l=c.params,f=await e.resolveCanonicalId(l.id)??l.id,u=await e.loadToolBlob(f,l.hash);if(u===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(u)}),t.get("/v1/sessions/:id/transcript",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=ao({record:u.record,history:u.history,promptHistory:u.promptHistory.length>0?u.promptHistory:void 0,hydraVersion:fe,machine:wo.hostname(),hydraHost:Qm(n)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(Va(p))}),t.post("/v1/sessions/:id/fork",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{},p={};if(u.forkAt!==void 0){if(typeof u.forkAt!="string"||u.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}p.forkAt=u.forkAt}if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}p.cwd=We(u.cwd)}if(u.agentId!==void 0){if(typeof u.agentId!="string"||u.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}p.agentId=u.agentId}if(u.title!==void 0){if(typeof u.title!="string"){d.code(400).send({error:"title must be a string"});return}p.title=u.title}try{let m=await e.forkSession(f,p);d.code(201).send(m)}catch(m){let h=m;if(h.code===q.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===q.InvalidParams||h.code===q.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),t.post("/v1/sessions/import",async(c,d)=>{let l=c.body??{};if(l.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let f;if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}f=l.cwd}let u;try{u=sn(l.bundle)}catch(p){d.code(400).send({error:"invalid bundle",details:p.message});return}try{let p=await e.importBundle(u,{replace:l.replace===!0,...f!==void 0?{cwd:f}:{}});d.code(201).send(p)}catch(p){let m=p;if(m.code===q.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}d.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f),p;if(u?p=u.summarizedThroughEntry:p=await e.getSummarizedThroughEntry(f),p===void 0&&!await e.hasRecord(f))return d.code(404).send({error:"session not found"}),d;let m=await e.getCompactionState(f),h=await e.getRollbackBreadcrumb(f),w=!1,b,S=await e.getHistory(f).catch(()=>[])??[];if(S.length>0&&n.compaction){let A=p??0,T=S.length,O=S.slice(A).reduce((F,H)=>F+JSON.stringify(H.params).length,0);b=Il(O);let z=u?.currentModel,V=S.at(-1).recordedAt,N=u?.currentUsage;w=Om({summarizedThroughEntry:A,totalEntries:T,unsummarizedChars:O,compactionInFlight:e.getCompactionInFlight(),currentModel:z,lastActivityMs:V,nowMs:Date.now(),config:n.compaction,...typeof N?.used=="number"?{agentReportedUsed:N.used}:{},...typeof N?.size=="number"?{agentReportedSize:N.size}:{}})}return{summarizedThroughEntry:p??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),t.post("/v1/sessions/:id/compact",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(e.get(f)){e.scheduleCompaction(f),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),d.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),d.code(202).send({rolledBack:!0})}catch(u){let p=u instanceof Error?u.message:String(u);d.code(409).send({error:p})}}),t.get("/v1/sessions/:id/history",async(c,d)=>{let l=c.params.id,f=c.query,u=f?.follow==="1"||f?.follow==="true",p=await e.resolveCanonicalId(l)??l,m=e.get(p),h,w,b=!1,v=1e4,S=[];if(m){u&&(w=m.onBroadcast(T=>{d.raw.writableEnded||(b?d.raw.write(JSON.stringify(T)+`
259
- `):(S.push(T),S.length>v&&S.shift()))})),c.raw.on("close",()=>{w?.(),d.raw.writableEnded||d.raw.end()});try{h=await m.getHistorySnapshot()}catch(T){throw w?.(),T}}else{let T=await e.getHistory(p);if(T===void 0)return d.code(404).send({error:"session not found"}),d;h=T}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let A=new Set;for(let T of h??[]){d.raw.write(JSON.stringify(T)+`
260
- `);let U=T;typeof U.recordedAt=="number"&&A.add(String(U.recordedAt))}for(;S.length>0;){let T=S.splice(0,S.length);for(let U of T){let O=U,z=typeof O.recordedAt=="number"?String(O.recordedAt):"";z&&A.has(z)||d.raw.write(JSON.stringify(U)+`
261
- `)}}return b=!0,w||d.raw.end(),d});function r(c,d,l){let f=typeof c=="string"?c.trim():"";if(f.length===0)return null;let u;try{u=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!u||typeof u!="object"||Array.isArray(u))return console.debug("events endpoint: skipping non-object JSONL line"),null;let p=u;if(typeof p.recordedAt!="number"||l!==void 0&&p.recordedAt<l||typeof p.params!="object"||p.params===null||Array.isArray(p.params))return null;let m=p.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!d.has(w)?null:{recordedAt:p.recordedAt,entry:u}}function i(c,d,l){let u=d.params.update,p={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:l,update:u};return u.messageId!==void 0&&u.messageId!==null&&(p.messageId=u.messageId),p}async function o(c,d,l,f){let u=El.createInterface({input:Tl.createReadStream(d),crlfDelay:1/0}),p=null;for await(let m of u){let h=r(m,l,f);if(h){let w=h.entry.params.update.sessionUpdate;p={ts:h.recordedAt,row:i(c,h.entry,w)};break}}return{sessionId:c,rl:u,current:p,exhausted:p===null}}async function a(c,d,l){for await(let f of c.rl){let u=r(f,d,l);if(u){let p=u.entry.params.update.sessionUpdate;c.current={ts:u.recordedAt,row:i(c.sessionId,u.entry,p)};return}}c.exhausted=!0}t.get("/v1/sessions/events",async(c,d)=>{let l=c.query,f=l.kinds;if(!f||f.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let u=f.split(",").map(v=>v.trim());if(u.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let v of u)if(!Qa.has(v))return d.code(400).send({error:`kind "${v}" is not queryable; allowed kinds: ${[...Qa].join(", ")}`}),d;let p=new Set(u),m;if(l.since!==void 0&&l.since.trim().length>0){let v=new Date(l.since);if(isNaN(v.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;m=v.getTime()}let h=await e.list({includeNonInteractive:!0}),w=m!==void 0?h.filter(v=>new Date(v.updatedAt).getTime()>=m):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let b=[];for(let v of w)try{let S=_.historyFile(v.sessionId),A=await o(v.sessionId,S,p,m);A.exhausted||b.push(A)}catch(S){if(S.code==="ENOENT")continue;throw S}c.raw.on("close",()=>{for(let v of b)try{v.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;b.length>0;){let v=-1,S=1/0;for(let T=0;T<b.length;T++){let U=b[T];U.current!==null&&U.current.ts<S&&(S=U.current.ts,v=T)}if(v===-1)break;let A=b[v];if(d.raw.write(JSON.stringify(A.current.row)+`
262
- `),await a(A,p,m),A.exhausted){try{A.rl.close()}catch{}b.splice(v,1)}}}catch(v){for(let S of b)try{S.rl.close()}catch{}throw v}return d.raw.end(),d}),t.get("/v1/sessions/:id/events",async(c,d)=>{let l=c.params.id,f=c.query,u=await e.resolveCanonicalId(l)??l;if(!e.get(u)&&!await e.hasRecord(u))return d.code(404).send({error:"session not found"}),d;let m=f.kinds;if(!m||m.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=m.split(",").map(T=>T.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let T of h)if(!Qa.has(T))return d.code(400).send({error:`kind "${T}" is not queryable; allowed kinds: ${[...Qa].join(", ")}`}),d;let w=new Set(h),b;if(f.since!==void 0&&f.since.trim().length>0){let T=new Date(f.since);if(isNaN(T.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;b=T.getTime()}let v=_.historyFile(u),S=Tl.createReadStream(v),A=El.createInterface({input:S,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let T of A){let U=typeof T=="string"?T.trim():"";if(U.length===0)continue;let O;try{O=JSON.parse(U)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",v);continue}if(!O||typeof O!="object"||Array.isArray(O)){console.debug("events endpoint: skipping non-object JSONL line in %s",v);continue}let z=O;if(typeof z.recordedAt!="number"||typeof z.params!="object"||z.params===null||Array.isArray(z.params))continue;let V=z.params;if(typeof V.update!="object"||V.update===null||Array.isArray(V.update))continue;let N=V.update,F=N.sessionUpdate;if(typeof F!="string"||!w.has(F)||b!==void 0&&z.recordedAt<b)continue;let H={ts:new Date(z.recordedAt).toISOString(),kind:F,update:N};N.messageId!==void 0&&N.messageId!==null&&(H.messageId=N.messageId),d.raw.write(JSON.stringify(H)+`
263
- `)}}catch(T){if(T.code==="ENOENT")return d.raw.end(),d;throw T}return d.raw.end(),d})}xt();function eh(t,e,n,s={}){t.get("/v1/agents",async()=>Br(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 nn(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===q.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function th(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var eI=/^[A-Za-z0-9._-]+$/;function Xa(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=tI(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){bo(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){bo(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){bo(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){bo(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){bo(o,c)}})}function bo(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 tI(t){let e=t.name;if(typeof e!="string"||!eI.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 nh(t,e){Xa(t,"extension",e)}function sh(t,e){Xa(t,"transformer",e)}function rh(t,e){t.get("/v1/config",async()=>e)}import{z as ti}from"zod";me();import*as us from"fs/promises";import*as dh from"path";import{randomBytes as nI,scrypt as sI,timingSafeEqual as rI}from"crypto";import{promisify as iI}from"util";var ch=iI(sI);function Pl(){return dh.join(_.home(),"password-hash")}var ih=32768,oh=8,ah=1,oI=64,aI=16,lh=128*1024*1024;async function uh(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=nI(aI),n=await ch(t,e,oI,{N:ih,r:oh,p:ah,maxmem:lh}),s=`scrypt$${ih}$${oh}$${ah}$${e.toString("hex")}$${n.toString("hex")}
264
- `;await us.mkdir(_.home(),{recursive:!0}),await us.writeFile(Pl(),s,{encoding:"utf8",mode:384})}async function Za(){try{return(await us.readFile(Pl(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ed(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await us.readFile(Pl(),"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 ch(t,o,a.length,{N:s,r,p:i,maxmem:lh});return c.length!==a.length?!1:rI(c,a)}var dI=ti.object({password:ti.string().min(1),label:ti.string().min(1).max(256).optional(),ttlSec:ti.number().int().positive().optional()}),cI=ti.object({id:ti.string().optional()}).optional();function fh(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=lI(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=dI.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Za())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ed(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=cI.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 lI(t){return t.ip||"unknown"}Js();ni();import{nanoid as Fl}from"nanoid";Sa();xt();Ht();import{randomBytes as mh}from"crypto";import*as hh from"os";function we(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function hI(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 rn(t,e,n){let s=t.get(e);if(!s)throw we(q.SessionNotFound,n??`session ${e} not found`);return s}async function Ml(t,e){let n=ei(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=mh(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=Rl({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,f=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{f.unbind(l)})}return SI(d,t),d}function gh(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=$m({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=kn(n),a=new Pt(o),c={clientId:`hydra_client_${Fl(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let d=(f,u)=>{if(c.attached.get(f)?.readonly)throw we(q.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=op.parse(f??{});u.clientInfo?.name&&(c.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),vI()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let w=h;if(typeof w.verb!="string")return;let b={verb:w.verb};return typeof w.argsHint=="string"&&(b.argsHint=w.argsHint),typeof w.description=="string"&&(b.description=w.description),b}).filter(h=>h!==void 0):[];return f.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},m=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;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(w=>w!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,m=typeof u.method=="string"?u.method:void 0,h=u.envelope,w=u.route;if(!p||!m)throw we(-32602,"emit_message requires sessionId and method");let b=rn(e.manager,p),v=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(v)return b.dischargeClaim(v,h),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,h)};if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,h)};throw we(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(-32602,"hydra-acp/session/request_permission requires sessionId");return rn(e.manager,p).requestPermissionFromClients(u)}),a.onRequest("hydra-acp/transformer/attach",async f=>wI(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0,w=u._meta&&typeof u._meta=="object"?u._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["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(!m&&h){let U=e.manager.get(h);U&&(m=U.cwd)}if(!m)throw we(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:h,interactive:A,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(q.InvalidParams,"fork_session requires sessionId");let p=typeof u.forkAt=="string"?u.forkAt:void 0,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(q.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw we(q.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,m=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,18e5):3e5;if(!p)throw we(-32602,"await_child requires childSessionId");let w=rn(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let A=[],T=[],U=0,O=!1,z,V,N=!1,F=()=>{N||(N=!0,clearTimeout(H),z?.(),V?.(),b(O?{entries:A,truncated:!0}:{entries:A}))};z=w.onBroadcast(Z=>{let G=hI(Z);for(A.push(Z),T.push(G),U+=G;A.length>0&&(A.length>1e3||U>1048576);)A.shift(),U-=T.shift()??0,O=!0;m==="turn_complete"&&Z.params?.update?.sessionUpdate==="turn_complete"&&F()});let H=setTimeout(F,h);typeof H.unref=="function"&&H.unref(),V=w.onClose(()=>F())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw we(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,m=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw we(q.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(p,u.hash);if(m===null)throw we(q.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>gI(f,e)),a.onRequest("session/new",async f=>{let u=ap.parse(f),p=Dt(f?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(H=>typeof H=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],w,b,v=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){w=mh(32).toString("hex"),b=e.mcpTokenRegistry.reserve(w);let Z={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${w}`}]};v=[...u.mcpServers??[],Z]}let S,A,T=ei(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let U=Rl({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),O;try{O=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ph(a),transformChain:h,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...U?{mintMcpServersForSwap:U}:{}})}catch(H){throw b!==void 0&&b.abandon(H instanceof Error?H:void 0),A!==void 0&&A.abandon(H instanceof Error?H:void 0),T!==void 0&&T.abandon(H instanceof Error?H:void 0),H}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let H=w,Z=e.mcpTokenRegistry;b.complete(O),O.onClose(()=>{Z.unbind(H)})}if(S!==void 0&&A!==void 0&&e.mcpTokenRegistry!==void 0){let H=S,Z=e.mcpTokenRegistry;A.complete(O),O.onClose(()=>{Z.unbind(H)})}T!==void 0&&T.bindToSession(O);let z,V;try{z=td(a,O,c),{entries:V}=await O.attach(z,"full")}catch(H){throw await O.close({deleteRecord:!1}).catch(()=>{}),H}c.attached.set(O.sessionId,{sessionId:O.sessionId,clientId:z.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let H of V){if(a.isClosed())break;await a.notify(H.method,H.params).catch(()=>{})}})()});let N=_l(O),F=$l(O);return{sessionId:O.sessionId,...N?{modes:N}:{},...F?{models:F}:{},configOptions:O.buildConfigOptions(),_meta:Ol(e.manager,O,{clientId:z.clientId})}}),a.onRequest("session/attach",async f=>{let u=cp.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Dt(u._meta),h=m.resume,w=m.readonly===!0,b=m.env;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${w}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,S=e.manager.get(v);if(!S&&w){let F=await e.manager.loadFromDisk(v);if(!F)throw we(q.SessionNotFound,`session ${u.sessionId} not found`);let H=await e.manager.loadHistory(v),Z=u.clientId??`cli_${Fl(8)}`;c.attached.set(F.hydraSessionId,{sessionId:F.hydraSessionId,clientId:Z,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${F.hydraSessionId} clientId=${Z} attachedCount=${c.attached.size} replayed=${H.length}`);for(let G of H)await a.notify(G.method,G.params).catch(()=>{});return{sessionId:F.hydraSessionId,clientId:Z,connectedClients:[Z],historyPolicy:"full",replayed:H.length,_meta:bI(F)}}let A=!S;if(!S){let F=await e.manager.loadFromDisk(v),H=F;if(h&&(H={...F,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!H)throw we(q.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);let Z=H.originatingClient?H:{...H,originatingClient:c.clientInfo},G=b!==void 0?{...Z,forwardedEnv:b}:Z;S=await Ml(e,{...G,onInstallProgress:ph(a)})}let T=td(a,S,c,u.clientInfo,u.clientId),U=m.replayMode==="drip",{entries:O,appliedPolicy:z}=await S.attach(T,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:U,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:w}),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=${u.historyPolicy} appliedPolicy=${z} replayed=${O.length} readonly=${w}${U?" replayMode=drip":""}`),U){let F=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,H=750;(async()=>{let Z=null;for(let G of O){let re=typeof G.recordedAt=="number"?G.recordedAt:null;if(Z!==null&&re!==null){let Y=Math.min(H,Math.max(0,(re-Z)/F));Y>0&&await new Promise(de=>setTimeout(de,Y))}re!==null&&(Z=re);try{await a.notify(G.method,G.params)}catch{return}}})()}else for(let F=0;F<O.length&&!a.isClosed();F++){let H=O[F],Z=a.notify(H.method,H.params).catch(()=>{});(F+1)%200===0&&await Z}S.replayPendingPermissions(T);let V=_l(S),N=$l(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:z,replayed:O.length,...V?{modes:V}:{},...N?{models:N}:{},configOptions:S.buildConfigOptions(),_meta:Ol(e.manager,S,{resurrected:A})}}),a.onRequest("session/detach",async f=>{let u=lp.parse(f),p=c.attached.get(u.sessionId);if(!p)throw we(q.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(p.clientId),c.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[pt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=up.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(w=>w.originatingClient?.name!==Ks).map(fp)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw we(q.InternalError,"agent registry unavailable");return Br(e.registry)}),a.onRequest("session/prompt",async f=>{let u=pp.parse(f);d(u.sessionId,"session/prompt");let p=c.attached.get(u.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),we(q.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let h=await e.manager.loadFromDisk(u.sessionId);if(!h)throw we(q.SessionNotFound,`session ${u.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),m=await Ml(e,h);let w=td(a,m,c,void 0,p.clientId);await m.attach(w,"none")}return m.prompt(p.clientId,u)});let l=f=>{let u;try{u=ha.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=c.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=ha.parse(f);return d(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=hp.parse(f);return d(u.sessionId,"hydra-acp/prompt/cancel"),rn(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=ha.parse(f);return d(u.sessionId,"hydra-acp/session/force_cancel"),rn(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=gp.parse(f);return d(u.sessionId,"hydra-acp/prompt/update"),rn(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=yp.parse(f);d(u.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(u.sessionId);if(!p)throw we(q.SessionNotFound,"not attached to session");return rn(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(q.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let A=await e.manager.loadFromDisk(m);if(!A)throw we(q.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Ml(e,A)}let w=td(a,h,c),{entries:b}=await h.attach(w,"pending_only");c.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:w.clientId,readonly:!1});for(let A of b){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}h.replayPendingPermissions(w);let v=_l(h),S=$l(h);return{sessionId:h.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:h.buildConfigOptions(),_meta:Ol(e.manager,h,{clientId:w.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&d(u,"session/set_model");let p=yI(f,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),we(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:m}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:m});return p.session.applyModelChange(m),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw we(q.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw we(q.InvalidParams,"session/set_mode requires string modeId");let m=rn(e.manager,u.sessionId),h=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=b=>we(q.InvalidParams,b),m=u?.sessionId;if(typeof m=="string"&&d(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=rn(e.manager,u.sessionId),w=h.buildConfigOptions().find(b=>b.id===u.configId);if(!w)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!w.options.some(b=>b.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object")throw we(q.MethodNotFound,`Method not found: ${u}`);let p=f.sessionId;if(typeof p!="string")throw we(q.MethodNotFound,`Method not found: ${u}`);return d(p,u),rn(e.manager,p).forwardRequest(u,f)})})}async function gI(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw we(q.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 u=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(u)}let c=a.authMethods??[],d=c.find(u=>u.id===s);if(!d){let u=c.map(p=>p.id);throw we(q.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${u.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=d._meta?.type;if((d.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let u=d._meta?.args,p=[];if(u!==void 0){if(!Array.isArray(u))throw we(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${u===null?"null":typeof u}`);for(let b of u)if(typeof b!="string")throw we(q.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(b)}`);p=u}let m=await e.manager.planSpawnForAgent(a.agentId),h={};for(let[b,v]of Object.entries(process.env))typeof v=="string"&&(h[b]=v);Object.assign(h,m.env);let w=hh.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m.command,args:[...m.args,...p],env:h,cwd:w}}try{return await a.connection.request("authenticate",{methodId:s})}catch(u){throw as(u,a)}}function ph(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(ga,n).catch(()=>{})}}function _l(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 $l(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 yI(t,e){if(!t||typeof t!="object")return{kind:"error",code:q.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:q.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:q.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:q.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Ur(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:q.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 wI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw we(q.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw we(q.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw we(q.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return rn(n.manager,r).addTransformer(i),{ok:!0}}function bI(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,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{[pt]:pa(e,n)}}function Ol(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 Gi(e.agentMeta,pa(s,r))}function vI(){return{protocolVersion:1,agentInfo:{name:"hydra",version:fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Gi(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function SI(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 td(t,e,n,s,r){return{clientId:r??`cli_${Fl(8)}`,connection:t,clientInfo:s}}var nd=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as kI}from"crypto";import{McpServer as II}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as xI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as mt}from"zod";function*Ll(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 Ut(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var yh="Bearer ";function si(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(yh))return;let n=e.slice(yh.length).trim();return n.length>0?n:void 0}function CI(t){let e=new II({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:mt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return Ut(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:mt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return Ut(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:mt.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:mt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:mt.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 Ut(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:mt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:mt.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 Ut({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:mt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:mt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:mt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:mt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:mt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:mt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:mt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:mt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:mt.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 Ut(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 Ut(n)}),e}var AI=1e4;function wh(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=CI(a),l=new xI({sessionIdGenerator:()=>kI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),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=si(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 u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),AI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let f=await s(c,l);a.hijack(),await f.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)})}ka();import{randomUUID as RI}from"crypto";import{McpServer as TI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as EI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as fs}from"zod";function PI(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function MI(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 _I(t){let e=new TI({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 `recall_search` to find entries by keyword, `recall_range` to pull a contiguous slice verbatim, and `recall_tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("recall_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 recall_range. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:fs.string().min(1).describe("Case-insensitive substring to search for."),limit:fs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:fs.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 Ut({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. recall_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:f}of Ll(o)){if(f==="tool_call"&&!r)continue;let u=jr([l]),p=u.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let m=PI(f),h=MI(u,p),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:m,snippet:h,timestamp:w}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return Ut({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("recall_range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after recall_search narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:fs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:fs.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 Ut({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. recall_range retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`recall_range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`recall_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),f=jr(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:d}}}),e.registerTool("recall_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:fs.string().optional(),file_path:fs.string().optional(),limit:fs.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 Ut({calls:[],truncated:!1,note:"This session has no compacted history. recall_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("recall_tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[];for(let{entryId:f,entry:u,kind:p,update:m}of Ll(c)){if(p!=="tool_call")continue;let h;if(typeof m.name=="string"&&m.name.length>0?h=m.name:typeof m.title=="string"&&m.title.length>0?h=m.title:h="(unnamed)",n!==void 0&&h.toLowerCase()!==n.toLowerCase())continue;let w=m.rawInput,b={};if(w&&typeof w=="object"&&!Array.isArray(w))for(let[A,T]of Object.entries(w))typeof T=="string"?b[A]=T.length>500?T.slice(0,497)+"\u2026":T:(typeof T=="number"||typeof T=="boolean")&&(b[A]=T);if(a&&w&&typeof w=="object"&&!Array.isArray(w)){let A=s.toLowerCase(),T=["file_path","path"],U=!1;for(let O of T){let z=w[O];if(typeof z=="string"&&z.toLowerCase()===A){U=!0;break}}if(!U)continue}let v="in_progress";typeof m.status=="string"&&(v=m.status);let S=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(d.push({entryId:f,tool:h,args:b,status:v,timestamp:S}),d.length>=r)break}let l=d.length>=r;return Ut({calls:d,truncated:l})}),e}var $I=1e4;function bh(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=_I(a),l=new EI({sessionIdGenerator:()=>RI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),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=si(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 f=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),$I)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.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 sd=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 UI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as jI}from"crypto";import{Server as OI}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as FI,ListToolsRequestSchema as LI}from"@modelcontextprotocol/sdk/types.js";function vh(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new OI({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(LI,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(FI,async(o,a)=>{let c=o.params.name;if(!i.has(c))return rd(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=NI(d,a.sendNotification);try{let f=await s(),u=await DI(e.connection,t,c,o.params.arguments??{},f);return HI(u,c)}catch(f){return rd(f instanceof Error?f.message:String(f))}finally{l()}}),r}var BI=15e3;function NI(t,e,n=BI){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 DI(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function HI(t,e){if(t===null||typeof t!="object")return rd(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:rd(`extension ${e} omitted content array`)}function rd(t){return{content:[{type:"text",text:t}],isError:!0}}var qI=1e4;function Sh(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 f=l.get(d);f!==void 0&&(l.delete(d),r(f))}}n.onChange(d=>{i(d)});async function o(d,l){let f=s.get(d);f===void 0&&(f=new Map,s.set(d,f),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 u=f.get(l);if(u!==void 0)return u.transport;let p=n.lookup(l);if(p===void 0)return;let h=vh(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),qI)}),A=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),A===void 0)throw new Error("session not ready");return A.sessionId}),w=new UI({sessionIdGenerator:()=>jI()});return await h.connect(w),f.set(l,{server:h,transport:w}),w}async function a(d,l){let f=si(d);if(f===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,m=await o(f,p);if(m===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await m.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 Ah(t,e){VI(t);let n=t.daemon.tls?await ri.readFile(We(t.daemon.tls.key)):void 0,s=t.daemon.tls?await ri.readFile(We(t.daemon.tls.cert)):void 0;await ri.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await KI(t.daemon.logLevel),o=WI({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(zI,{options:{handleProtocols:Uf}}),Rc(K=>{o.log.info(K)}),Pc(K=>{o.log.info(K)});let a=await Ha.load(),c=new za,d=new Wa,l=new qa([new Ua(e),new ja(a),d]),f=_m({validator:l});o.addHook("onRequest",async(K,st)=>{K.routeOptions.config?.skipAuth||K.url==="/acp"||K.url?.startsWith("/acp?")||await f(K,st)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let m=new la(t,{onFetched:()=>{Im(m,v)}});vl(K=>o.log.info(K));let h={info:K=>o.log.info(K),warn:K=>o.log.warn(K)},w=K=>os.spawn({...K,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:h});zf(t.compressToolContent);let b=new Na,v=new _a(m,w,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:h,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new La(mf(t),void 0,{tokenRegistry:d}),A=new Ba(hf(t),void 0,{tokenRegistry:d});th(o,fe,cs(t));let T=new nd,U=new sd,O,z=()=>{if(O!==void 0)return O;let K=o.server.address();return O=`http://127.0.0.1:${K&&typeof K=="object"?K.port:t.daemon.port}`,O};Zm(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:U,mcpTokenRegistry:T,getDaemonOrigin:z}),eh(o,m,v,{npmRegistry:t.npmRegistry}),nh(o,S),sh(o,A),rh(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]}),fh(o,{store:a,rateLimiter:c}),wh(o,T),bh(o,T),Sh(o,T,U),gh(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(K,st)=>S.reportVersion(K,st),onTransformerVersion:(K,st)=>A.reportVersion(K,st),transformers:A,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:U,getDaemonOrigin:z,registry:m});let V=!!t.daemon.tls;await o.listen({host:V?"127.0.0.1":t.daemon.host,port:V?0:t.daemon.port});let N=o.server.address(),F=N&&typeof N=="object"?N.port:t.daemon.port,H,Z=t.daemon.host,G=F;if(V&&n&&s){H=YI({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:F,tlsOptions:{key:n,cert:s},logger:o.log});let K=H.address();K&&typeof K=="object"&&(G=K.port)}await ri.mkdir(_.home(),{recursive:!0}),await If({pid:process.pid,host:Z,port:G,loopbackPort:F,startedAt:new Date().toISOString()});let re={daemonUrl:`http://127.0.0.1:${F}`,daemonHost:"127.0.0.1",daemonPort:F,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${F}/acp`,hydraHome:_.home()};S.setContext(re),A.setContext(re),await S.start(),await A.start(),v.resurrectPendingQueues().catch(K=>{o.log.warn(`queue replay scan failed: ${K.message}`)}),v.resumePendingCompactions().catch(K=>{o.log.warn(`compaction resume scan failed: ${K.message}`)});let Y=t.daemon.agentSyncIntervalMinutes*60*1e3,de=Y>0?xm({registry:m,manager:v,intervalMs:Y,logger:h}):void 0,je=t.daemon.sessionGcIntervalMinutes*60*1e3,Ae=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,et=je>0?Cm({manager:v,intervalMs:je,maxAgeMs:Ae,logger:h}):void 0;return{app:o,manager:v,registry:m,extensions:S,transformers:A,mcpTokenRegistry:T,extensionMcp:U,processRegistry:d,shutdown:async()=>{et&&et(),de&&de(),clearInterval(u),clearInterval(p);let K=async(st,_t)=>{try{await _t()}catch(ht){o.log.warn(`shutdown step ${st} failed: ${ht instanceof Error?ht.message:String(ht)}`)}};await K("sessionTokenStore.flush",()=>a.flush()),await K("extensions.stop",()=>S.stop()),await K("transformers.stop",()=>A.stop()),await K("manager.closeAll",()=>v.closeAll()),await K("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await K("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await K("manager.flushMetaWrites",()=>v.flushMetaWrites()),await K("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Rc(null),Pc(null),vl(null),H&&await K("tlsTerminator.close",()=>new Promise(st=>H.close(()=>st()))),await K("app.close",()=>o.close());try{Ih.unlinkSync(_.pidFile())}catch{}await K("fileStream.flushSync",()=>i.flushSync())}}}async function KI(t){let e=await JI({file:_.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=kh.destination(2);return{stream:kh.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function YI(t){let e=Ch.createServer(t.tlsOptions,n=>{let s=xh.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 VI(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.`)}Zs();Ht();ho();import*as Th from"fs";import*as ii from"fs/promises";async function oi(t,e,n){let s=ex(e),r;try{r=await ii.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
265
- `),process.exit(1);return}throw c}let i=await ZI(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
266
- `);let o=!1,a=Th.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await ii.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await ii.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 ZI(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await ii.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let f=Buffer.alloc(l);await r.read(f,0,l,i),o=f.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
255
+ `),r}function Bk(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=Rn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Nk(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 Dk(t,e){let n=e.session,s=Ve(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${dr(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?`${Pl(a.size)}`:void 0;c.push(d?`${Pl(a.used)} / ${d} tokens`:`${Pl(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 Hk(t,e,n){if(!e.some(d=>Uk(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(`> ${dr(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 f of l)t.push(`> _${dr(f)}_`);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(`- ${qk(l.status)} ${jk(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 f=l.status==="completed"?"[x]":"[ ]";t.push(`- ${f} ${dr(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${dr(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${dr(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Uk(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function jk(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${dr(t.title)}${n}`}function qk(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 dr(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Pl(t){return t.toLocaleString("en-US")}It();Nt();eo();ys();function Wk(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 f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>zk(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function zk(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:zm(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:zm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function zm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Jk(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Kk=5,Yk=200,Jm=30;async function Vm(t,e,n={}){let s=Wk(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Kk,i=n.maxSessions??Yk,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(f=>o.has(f.sessionId)):a,d=[],l=!1;for(let f of c){if(d.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Vk(u,s,r);if(p.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(m.title=f.title),d.push(m)}return{query:e,truncated:l,results:d}}function Vk(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=Gk(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 Gk(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=Qk(a).filter(d=>Jk(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(i+=u,o.length<s){let p=l.indexOf(r),m={kind:d.kind,text:nI(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(m.toolName=d.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Qk(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=nd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?tt(s.text):nd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(eI(s))return[];let i=nd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=tI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Xk(s);default:return[]}}function Xk(t){let e=Km(t,"name"),n=Km(t,"title"),s=[];if(n!==void 0){let a=Ie(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=Ie(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Ym(r);if(a.length>0){let c={kind:"tool-input",text:Ie(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Ym(i);if(a.length>0){let c={kind:"tool-input",text:Ie(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Zk(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Zk(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=Ie(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=Ie(s);if(r.length>0)return r}}return null}function eI(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function nd(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?tt(e.text):""}function tI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=nd(n);s.length>0&&e.push(s)}return e.join("")}function Km(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Ym(t){try{return JSON.stringify(t)}catch{return""}}function nI(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-Jm),c=Math.min(s.length,o+i.length+Jm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Qm}from"crypto";function Gm(t){let e=Qm(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 Ml(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(Gm({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Gm({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=li(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function li(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=Qm(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 sd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Xm(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!Xs(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function eh(t,e,n,s={}){t.get("/v1/sessions",async c=>{let d=c.query,l=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:l})}}),t.get("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.getOne(f);return u||(d.code(404).send({error:"session not found"}),d)}),t.post("/v1/sessions/search",async(c,d)=>{let l=c.body??{},f=typeof l.q=="string"?l.q:"";if(f.trim().length===0)return d.code(400).send({error:"q is required"}),d;let u=Array.isArray(l.sessionIds)?l.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Vm(e,f,{sessionIds:u})}),t.post("/v1/sessions",async(c,d)=>{let l=c.body??{},f=je(l.cwd??n.cwd),u=l.agentId??n.agentId,p=li(s),m=p!==void 0?[...l.mcpServers??[],...p.descriptors]:l.mcpServers;try{let h=await e.create({cwd:f,agentId:u,mcpServers:m});p!==void 0&&p.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){p!==void 0&&p.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),t.post("/v1/sessions/collect",async(c,d)=>{let l=c.body??{},f=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,u=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,p=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let m=await Cl({manager:e,maxAgeMs:f,maxDeletions:u,selection:p,verbose:!1});d.code(200).send(m)}catch(m){d.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){u.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m={};(p.mode==="memory"||p.mode==="file")&&(m.mode=p.mode),typeof p.capacityBytes=="number"&&(m.capacityBytes=p.capacityBytes),typeof p.fileCapBytes=="number"&&(m.fileCapBytes=p.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=h=>Zm.join(Ro.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return u.openStream(m)}catch(h){return d.code(409).send({error:h.message}),d}}),t.post("/v1/sessions/:id/stdin",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m=typeof p.chunk=="string"?p.chunk:"",h=p.eof===!0;try{return u.streamWrite(m,h)}catch(w){return d.code(409).send({error:w.message}),d}}),t.patch("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{};if(u.priority!==void 0){let m=u.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(u.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),d.code(202).send();return}if(typeof u.title!="string"||u.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,u.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.delete("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){await u.close({deleteRecord:!0}),d.code(204).send();return}if(!await e.deleteRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.get("/v1/sessions/:id/export",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.query?.tools,p=u==="references"?"references":cm(u),m=await e.exportBundle(f,p==="references"?{tools:"references"}:{});if(!m){d.code(404).send({error:"session not found"});return}let h=yo({record:m.record,history:p==="summary"?lm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:Ro.hostname(),hydraHost:Xm(n)}),w=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),d.code(200).send(h)}),t.get("/v1/sessions/:id/diff",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=c.query??{},m=p.fold==="true"||p.fold==="1",h=typeof p.paths=="string"&&p.paths.length>0?new Set(p.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,w=di(u.history);h&&(w=w.filter(b=>h.has(b.path))),m&&(w=w.map(b=>({...b,hunks:ci(b.hunks)}))),d.code(200).send(w)}),t.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let l=c.params,f=await e.resolveCanonicalId(l.id)??l.id,u=await e.loadToolBlob(f,l.hash);if(u===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(u)}),t.get("/v1/sessions/:id/transcript",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=yo({record:u.record,history:u.history,promptHistory:u.promptHistory.length>0?u.promptHistory:void 0,hydraVersion:fe,machine:Ro.hostname(),hydraHost:Xm(n)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(td(p))}),t.post("/v1/sessions/:id/fork",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{},p={};if(u.forkAt!==void 0){if(typeof u.forkAt!="string"||u.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}p.forkAt=u.forkAt}if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}p.cwd=je(u.cwd)}if(u.agentId!==void 0){if(typeof u.agentId!="string"||u.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}p.agentId=u.agentId}if(u.title!==void 0){if(typeof u.title!="string"){d.code(400).send({error:"title must be a string"});return}p.title=u.title}try{let m=await e.forkSession(f,p);d.code(201).send(m)}catch(m){let h=m;if(h.code===z.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===z.InvalidParams||h.code===z.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),t.post("/v1/sessions/import",async(c,d)=>{let l=c.body??{};if(l.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let f;if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}f=l.cwd}let u;try{u=ln(l.bundle)}catch(p){d.code(400).send({error:"invalid bundle",details:p.message});return}try{let p=await e.importBundle(u,{replace:l.replace===!0,...f!==void 0?{cwd:f}:{}});d.code(201).send(p)}catch(p){let m=p;if(m.code===z.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}d.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f),p;if(u?p=u.summarizedThroughEntry:p=await e.getSummarizedThroughEntry(f),p===void 0&&!await e.hasRecord(f))return d.code(404).send({error:"session not found"}),d;let m=await e.getCompactionState(f),h=await e.getRollbackBreadcrumb(f),w=!1,b,S=await e.getHistory(f).catch(()=>[])??[];if(S.length>0&&n.compaction){let x=p??0,T=S.length,$=S.slice(x).reduce((N,j)=>N+JSON.stringify(j.params).length,0);b=Rl($);let H=u?.currentModel,J=S.at(-1).recordedAt,B=u?.currentUsage;w=Fm({summarizedThroughEntry:x,totalEntries:T,unsummarizedChars:$,compactionInFlight:e.getCompactionInFlight(),currentModel:H,lastActivityMs:J,nowMs:Date.now(),config:n.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:p??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),t.post("/v1/sessions/:id/compact",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(e.get(f)){e.scheduleCompaction(f),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),d.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),d.code(202).send({rolledBack:!0})}catch(u){let p=u instanceof Error?u.message:String(u);d.code(409).send({error:p})}}),t.get("/v1/sessions/:id/history",async(c,d)=>{let l=c.params.id,f=c.query,u=f?.follow==="1"||f?.follow==="true",p=await e.resolveCanonicalId(l)??l,m=e.get(p),h,w,b=!1,v=1e4,S=[];if(m){u&&(w=m.onBroadcast(T=>{d.raw.writableEnded||(b?d.raw.write(JSON.stringify(T)+`
259
+ `):(S.push(T),S.length>v&&S.shift()))})),c.raw.on("close",()=>{w?.(),d.raw.writableEnded||d.raw.end()});try{h=await m.getHistorySnapshot()}catch(T){throw w?.(),T}}else{let T=await e.getHistory(p);if(T===void 0)return d.code(404).send({error:"session not found"}),d;h=T}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let x=new Set;for(let T of h??[]){d.raw.write(JSON.stringify(T)+`
260
+ `);let F=T;typeof F.recordedAt=="number"&&x.add(String(F.recordedAt))}for(;S.length>0;){let T=S.splice(0,S.length);for(let F of T){let $=F,H=typeof $.recordedAt=="number"?String($.recordedAt):"";H&&x.has(H)||d.raw.write(JSON.stringify(F)+`
261
+ `)}}return b=!0,w||d.raw.end(),d});function r(c,d,l){let f=typeof c=="string"?c.trim():"";if(f.length===0)return null;let u;try{u=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!u||typeof u!="object"||Array.isArray(u))return console.debug("events endpoint: skipping non-object JSONL line"),null;let p=u;if(typeof p.recordedAt!="number"||l!==void 0&&p.recordedAt<l||typeof p.params!="object"||p.params===null||Array.isArray(p.params))return null;let m=p.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!d.has(w)?null:{recordedAt:p.recordedAt,entry:u}}function i(c,d,l){let u=d.params.update,p={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:l,update:u};return u.messageId!==void 0&&u.messageId!==null&&(p.messageId=u.messageId),p}async function o(c,d,l,f){let u=$l.createInterface({input:_l.createReadStream(d),crlfDelay:1/0}),p=null;for await(let m of u){let h=r(m,l,f);if(h){let w=h.entry.params.update.sessionUpdate;p={ts:h.recordedAt,row:i(c,h.entry,w)};break}}return{sessionId:c,rl:u,current:p,exhausted:p===null}}async function a(c,d,l){for await(let f of c.rl){let u=r(f,d,l);if(u){let p=u.entry.params.update.sessionUpdate;c.current={ts:u.recordedAt,row:i(c.sessionId,u.entry,p)};return}}c.exhausted=!0}t.get("/v1/sessions/events",async(c,d)=>{let l=c.query,f=l.kinds;if(!f||f.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let u=f.split(",").map(v=>v.trim());if(u.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let v of u)if(!sd.has(v))return d.code(400).send({error:`kind "${v}" is not queryable; allowed kinds: ${[...sd].join(", ")}`}),d;let p=new Set(u),m;if(l.since!==void 0&&l.since.trim().length>0){let v=new Date(l.since);if(isNaN(v.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;m=v.getTime()}let h=await e.list({includeNonInteractive:!0}),w=m!==void 0?h.filter(v=>new Date(v.updatedAt).getTime()>=m):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let b=[];for(let v of w)try{let S=_.historyFile(v.sessionId),x=await o(v.sessionId,S,p,m);x.exhausted||b.push(x)}catch(S){if(S.code==="ENOENT")continue;throw S}c.raw.on("close",()=>{for(let v of b)try{v.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;b.length>0;){let v=-1,S=1/0;for(let T=0;T<b.length;T++){let F=b[T];F.current!==null&&F.current.ts<S&&(S=F.current.ts,v=T)}if(v===-1)break;let x=b[v];if(d.raw.write(JSON.stringify(x.current.row)+`
262
+ `),await a(x,p,m),x.exhausted){try{x.rl.close()}catch{}b.splice(v,1)}}}catch(v){for(let S of b)try{S.rl.close()}catch{}throw v}return d.raw.end(),d}),t.get("/v1/sessions/:id/events",async(c,d)=>{let l=c.params.id,f=c.query,u=await e.resolveCanonicalId(l)??l;if(!e.get(u)&&!await e.hasRecord(u))return d.code(404).send({error:"session not found"}),d;let m=f.kinds;if(!m||m.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=m.split(",").map(T=>T.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let T of h)if(!sd.has(T))return d.code(400).send({error:`kind "${T}" is not queryable; allowed kinds: ${[...sd].join(", ")}`}),d;let w=new Set(h),b;if(f.since!==void 0&&f.since.trim().length>0){let T=new Date(f.since);if(isNaN(T.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;b=T.getTime()}let v=_.historyFile(u),S=_l.createReadStream(v),x=$l.createInterface({input:S,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let T of x){let F=typeof T=="string"?T.trim():"";if(F.length===0)continue;let $;try{$=JSON.parse(F)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",v);continue}if(!$||typeof $!="object"||Array.isArray($)){console.debug("events endpoint: skipping non-object JSONL line in %s",v);continue}let H=$;if(typeof H.recordedAt!="number"||typeof H.params!="object"||H.params===null||Array.isArray(H.params))continue;let J=H.params;if(typeof J.update!="object"||J.update===null||Array.isArray(J.update))continue;let B=J.update,N=B.sessionUpdate;if(typeof N!="string"||!w.has(N)||b!==void 0&&H.recordedAt<b)continue;let j={ts:new Date(H.recordedAt).toISOString(),kind:N,update:B};B.messageId!==void 0&&B.messageId!==null&&(j.messageId=B.messageId),d.raw.write(JSON.stringify(j)+`
263
+ `)}}catch(T){if(T.code==="ENOENT")return d.raw.end(),d;throw T}return d.raw.end(),d})}It();function th(t,e,n,s={}){t.get("/v1/agents",async()=>Kr(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 cn(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 nh(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var sI=/^[A-Za-z0-9._-]+$/;function rd(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=rI(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){To(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){To(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){To(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){To(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){To(o,c)}})}function To(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 rI(t){let e=t.name;if(typeof e!="string"||!sI.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 sh(t,e){rd(t,"extension",e)}function rh(t,e){rd(t,"transformer",e)}function ih(t,e){t.get("/v1/config",async()=>e)}import{z as ui}from"zod";pe();import*as ws from"fs/promises";import*as ch from"path";import{randomBytes as iI,scrypt as oI,timingSafeEqual as aI}from"crypto";import{promisify as dI}from"util";var lh=dI(oI);function Ol(){return ch.join(_.home(),"password-hash")}var oh=32768,ah=8,dh=1,cI=64,lI=16,uh=128*1024*1024;async function fh(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=iI(lI),n=await lh(t,e,cI,{N:oh,r:ah,p:dh,maxmem:uh}),s=`scrypt$${oh}$${ah}$${dh}$${e.toString("hex")}$${n.toString("hex")}
264
+ `;await ws.mkdir(_.home(),{recursive:!0}),await ws.writeFile(Ol(),s,{encoding:"utf8",mode:384})}async function id(){try{return(await ws.readFile(Ol(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function od(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await ws.readFile(Ol(),"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 lh(t,o,a.length,{N:s,r,p:i,maxmem:uh});return c.length!==a.length?!1:aI(c,a)}var uI=ui.object({password:ui.string().min(1),label:ui.string().min(1).max(256).optional(),ttlSec:ui.number().int().positive().optional()}),fI=ui.object({id:ui.string().optional()}).optional();function ph(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=pI(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=uI.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await id())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await od(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=fI.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 pI(t){return t.ip||"unknown"}sr();fi();import{nanoid as Dl}from"nanoid";Ra();It();Nt();import{randomBytes as hh}from"crypto";import*as gh from"os";function we(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function wI(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 un(t,e,n){let s=t.get(e);if(!s)throw we(z.SessionNotFound,n??`session ${e} not found`);return s}async function Fl(t,e){let n=li(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=hh(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=Ml({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,f=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{f.unbind(l)})}return xI(d,t),d}function yh(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Om({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=Tn(n),a=new Pt(o),c={clientId:`hydra_client_${Dl(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let d=(f,u)=>{if(c.attached.get(f)?.readonly)throw we(z.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=ap.parse(f??{});u.clientInfo?.name&&(c.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),II()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let w=h;if(typeof w.verb!="string")return;let b={verb:w.verb};return typeof w.argsHint=="string"&&(b.argsHint=w.argsHint),typeof w.description=="string"&&(b.description=w.description),b}).filter(h=>h!==void 0):[];return f.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},m=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;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(w=>w!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,m=typeof u.method=="string"?u.method:void 0,h=u.envelope,w=u.route;if(!p||!m)throw we(-32602,"emit_message requires sessionId and method");let b=un(e.manager,p),v=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(v)return b.dischargeClaim(v,h),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,h)};if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,h)};throw we(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(-32602,"hydra-acp/session/request_permission requires sessionId");return un(e.manager,p).requestPermissionFromClients(u)}),a.onRequest("hydra-acp/transformer/attach",async f=>SI(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0,w=u._meta&&typeof u._meta=="object"?u._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["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(!m&&h){let F=e.manager.get(h);F&&(m=F.cwd)}if(!m)throw we(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:h,interactive:x,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(z.InvalidParams,"fork_session requires sessionId");let p=typeof u.forkAt=="string"?u.forkAt:void 0,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(z.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw we(z.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,m=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,18e5):3e5;if(!p)throw we(-32602,"await_child requires childSessionId");let w=un(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],F=0,$=!1,H,J,B=!1,N=()=>{B||(B=!0,clearTimeout(j),H?.(),J?.(),b($?{entries:x,truncated:!0}:{entries:x}))};H=w.onBroadcast(X=>{let Y=wI(X);for(x.push(X),T.push(Y),F+=Y;x.length>0&&(x.length>1e3||F>1048576);)x.shift(),F-=T.shift()??0,$=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&N()});let j=setTimeout(N,h);typeof j.unref=="function"&&j.unref(),J=w.onClose(()=>N())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw we(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,m=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw we(z.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(p,u.hash);if(m===null)throw we(z.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>bI(f,e)),a.onRequest("session/new",async f=>{let u=dp.parse(f),p=Bt(f?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(j=>typeof j=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],w,b,v=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){w=hh(32).toString("hex"),b=e.mcpTokenRegistry.reserve(w);let X={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${w}`}]};v=[...u.mcpServers??[],X]}let S,x,T=li(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let F=Ml({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:mh(a),transformChain:h,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...F?{mintMcpServersForSwap:F}:{}})}catch(j){throw b!==void 0&&b.abandon(j instanceof Error?j:void 0),x!==void 0&&x.abandon(j instanceof Error?j:void 0),T!==void 0&&T.abandon(j instanceof Error?j:void 0),j}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let j=w,X=e.mcpTokenRegistry;b.complete($),$.onClose(()=>{X.unbind(j)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let j=S,X=e.mcpTokenRegistry;x.complete($),$.onClose(()=>{X.unbind(j)})}T!==void 0&&T.bindToSession($);let H,J;try{H=ad(a,$,c),{entries:J}=await $.attach(H,"full")}catch(j){throw await $.close({deleteRecord:!1}).catch(()=>{}),j}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:H.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let j of J){if(a.isClosed())break;await a.notify(j.method,j.params).catch(()=>{})}})()});let B=Ll($),N=Bl($);return{sessionId:$.sessionId,...B?{modes:B}:{},...N?{models:N}:{},configOptions:$.buildConfigOptions(),_meta:Nl(e.manager,$,{clientId:H.clientId})}}),a.onRequest("session/attach",async f=>{let u=lp.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Bt(u._meta),h=m.resume,w=m.readonly===!0,b=m.env;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${w}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,S=e.manager.get(v);if(!S&&w){let N=await e.manager.loadFromDisk(v);if(!N)throw we(z.SessionNotFound,`session ${u.sessionId} not found`);let j=await e.manager.loadHistory(v),X=u.clientId??`cli_${Dl(8)}`;c.attached.set(N.hydraSessionId,{sessionId:N.hydraSessionId,clientId:X,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${N.hydraSessionId} clientId=${X} attachedCount=${c.attached.size} replayed=${j.length}`);for(let Y of j)await a.notify(Y.method,Y.params).catch(()=>{});return{sessionId:N.hydraSessionId,clientId:X,connectedClients:[X],historyPolicy:"full",replayed:j.length,_meta:kI(N)}}let x=!S;if(!S){let N=await e.manager.loadFromDisk(v),j=N;if(h&&(j={...N,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!j)throw we(z.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);let X=j.originatingClient?j:{...j,originatingClient:c.clientInfo},Y=b!==void 0?{...X,forwardedEnv:b}:X;S=await Fl(e,{...Y,onInstallProgress:mh(a)})}let T=ad(a,S,c,u.clientInfo,u.clientId),F=m.replayMode==="drip",{entries:$,appliedPolicy:H}=await S.attach(T,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:F,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:w}),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=${u.historyPolicy} appliedPolicy=${H} replayed=${$.length} readonly=${w}${F?" replayMode=drip":""}`),F){let N=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,j=750;(async()=>{let X=null;for(let Y of $){let be=typeof Y.recordedAt=="number"?Y.recordedAt:null;if(X!==null&&be!==null){let V=Math.min(j,Math.max(0,(be-X)/N));V>0&&await new Promise(ge=>setTimeout(ge,V))}be!==null&&(X=be);try{await a.notify(Y.method,Y.params)}catch{return}}})()}else for(let N=0;N<$.length&&!a.isClosed();N++){let j=$[N],X=a.notify(j.method,j.params).catch(()=>{});(N+1)%200===0&&await X}S.replayPendingPermissions(T);let J=Ll(S),B=Bl(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:H,replayed:$.length,...J?{modes:J}:{},...B?{models:B}:{},configOptions:S.buildConfigOptions(),_meta:Nl(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async f=>{let u=up.parse(f),p=c.attached.get(u.sessionId);if(!p)throw we(z.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(p.clientId),c.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=fp.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(w=>w.originatingClient?.name!==rr).map(pp)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw we(z.InternalError,"agent registry unavailable");return Kr(e.registry)}),a.onRequest("session/prompt",async f=>{let u=mp.parse(f);d(u.sessionId,"session/prompt");let p=c.attached.get(u.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),we(z.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let h=await e.manager.loadFromDisk(u.sessionId);if(!h)throw we(z.SessionNotFound,`session ${u.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),m=await Fl(e,h);let w=ad(a,m,c,void 0,p.clientId);await m.attach(w,"none")}return m.prompt(p.clientId,u)});let l=f=>{let u;try{u=Sa.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=c.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Sa.parse(f);return d(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=gp.parse(f);return d(u.sessionId,"hydra-acp/prompt/cancel"),un(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Sa.parse(f);return d(u.sessionId,"hydra-acp/session/force_cancel"),un(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=yp.parse(f);return d(u.sessionId,"hydra-acp/prompt/update"),un(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=wp.parse(f);d(u.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(u.sessionId);if(!p)throw we(z.SessionNotFound,"not attached to session");return un(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(z.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let x=await e.manager.loadFromDisk(m);if(!x)throw we(z.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Fl(e,x)}let w=ad(a,h,c),{entries:b}=await h.attach(w,"pending_only");c.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:w.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}h.replayPendingPermissions(w);let v=Ll(h),S=Bl(h);return{sessionId:h.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:h.buildConfigOptions(),_meta:Nl(e.manager,h,{clientId:w.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&d(u,"session/set_model");let p=vI(f,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),we(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:m}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:m});return p.session.applyModelChange(m),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw we(z.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw we(z.InvalidParams,"session/set_mode requires string modeId");let m=un(e.manager,u.sessionId),h=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=b=>we(z.InvalidParams,b),m=u?.sessionId;if(typeof m=="string"&&d(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=un(e.manager,u.sessionId),w=h.buildConfigOptions().find(b=>b.id===u.configId);if(!w)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!w.options.some(b=>b.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object")throw we(z.MethodNotFound,`Method not found: ${u}`);let p=f.sessionId;if(typeof p!="string")throw we(z.MethodNotFound,`Method not found: ${u}`);return d(p,u),un(e.manager,p).forwardRequest(u,f)})})}async function bI(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw we(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 u=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(u)}let c=a.authMethods??[],d=c.find(u=>u.id===s);if(!d){let u=c.map(p=>p.id);throw we(z.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${u.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=d._meta?.type;if((d.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let u=d._meta?.args,p=[];if(u!==void 0){if(!Array.isArray(u))throw we(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${u===null?"null":typeof u}`);for(let b of u)if(typeof b!="string")throw we(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(b)}`);p=u}let m=await e.manager.planSpawnForAgent(a.agentId),h={};for(let[b,v]of Object.entries(process.env))typeof v=="string"&&(h[b]=v);Object.assign(h,m.env);let w=gh.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m.command,args:[...m.args,...p],env:h,cwd:w}}try{return await a.connection.request("authenticate",{methodId:s})}catch(u){throw ms(u,a)}}function mh(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(ka,n).catch(()=>{})}}function Ll(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 Bl(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 vI(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=Qr(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 SI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw we(z.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw we(z.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw we(z.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return un(n.manager,r).addTransformer(i),{ok:!0}}function kI(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,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{[mt]:ba(e,n)}}function Nl(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 io(e.agentMeta,ba(s,r))}function II(){return{protocolVersion:1,agentInfo:{name:"hydra",version:fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:io(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function xI(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 ad(t,e,n,s,r){return{clientId:r??`cli_${Dl(8)}`,connection:t,clientInfo:s}}var dd=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 CI}from"crypto";import{McpServer as AI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as RI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as ht}from"zod";function*Hl(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 Dt(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var wh="Bearer ";function pi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(wh))return;let n=e.slice(wh.length).trim();return n.length>0?n:void 0}function TI(t){let e=new AI({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:ht.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return Dt(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:ht.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return Dt(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:ht.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:ht.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:ht.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 Dt(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:ht.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:ht.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 Dt({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:ht.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:ht.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:ht.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:ht.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:ht.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:ht.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:ht.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:ht.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:ht.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 Dt(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 Dt(n)}),e}var EI=1e4;function bh(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=TI(a),l=new RI({sessionIdGenerator:()=>CI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),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=pi(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 u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),EI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let f=await s(c,l);a.hijack(),await f.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)})}Ta();import{randomUUID as PI}from"crypto";import{McpServer as MI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as _I}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as bs}from"zod";function $I(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function OI(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 FI(t){let e=new MI({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 `recall_search` to find entries by keyword, `recall_range` to pull a contiguous slice verbatim, and `recall_tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("recall_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 recall_range. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:bs.string().min(1).describe("Case-insensitive substring to search for."),limit:bs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:bs.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 Dt({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. recall_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:f}of Hl(o)){if(f==="tool_call"&&!r)continue;let u=Xr([l]),p=u.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let m=$I(f),h=OI(u,p),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:m,snippet:h,timestamp:w}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return Dt({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("recall_range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after recall_search narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:bs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:bs.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 Dt({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. recall_range retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`recall_range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`recall_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),f=Xr(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:d}}}),e.registerTool("recall_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:bs.string().optional(),file_path:bs.string().optional(),limit:bs.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 Dt({calls:[],truncated:!1,note:"This session has no compacted history. recall_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("recall_tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[];for(let{entryId:f,entry:u,kind:p,update:m}of Hl(c)){if(p!=="tool_call")continue;let h;if(typeof m.name=="string"&&m.name.length>0?h=m.name:typeof m.title=="string"&&m.title.length>0?h=m.title:h="(unnamed)",n!==void 0&&h.toLowerCase()!==n.toLowerCase())continue;let w=m.rawInput,b={};if(w&&typeof w=="object"&&!Array.isArray(w))for(let[x,T]of Object.entries(w))typeof T=="string"?b[x]=T.length>500?T.slice(0,497)+"\u2026":T:(typeof T=="number"||typeof T=="boolean")&&(b[x]=T);if(a&&w&&typeof w=="object"&&!Array.isArray(w)){let x=s.toLowerCase(),T=["file_path","path"],F=!1;for(let $ of T){let H=w[$];if(typeof H=="string"&&H.toLowerCase()===x){F=!0;break}}if(!F)continue}let v="in_progress";typeof m.status=="string"&&(v=m.status);let S=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(d.push({entryId:f,tool:h,args:b,status:v,timestamp:S}),d.length>=r)break}let l=d.length>=r;return Dt({calls:d,truncated:l})}),e}var LI=1e4;function vh(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=FI(a),l=new _I({sessionIdGenerator:()=>PI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),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=pi(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 f=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),LI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.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 cd=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 WI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as zI}from"crypto";import{Server as BI}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as NI,ListToolsRequestSchema as DI}from"@modelcontextprotocol/sdk/types.js";function Sh(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new BI({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(DI,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(NI,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=UI(d,a.sendNotification);try{let f=await s(),u=await jI(e.connection,t,c,o.params.arguments??{},f);return qI(u,c)}catch(f){return ld(f instanceof Error?f.message:String(f))}finally{l()}}),r}var HI=15e3;function UI(t,e,n=HI){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 jI(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function qI(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 JI=1e4;function kh(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 f=l.get(d);f!==void 0&&(l.delete(d),r(f))}}n.onChange(d=>{i(d)});async function o(d,l){let f=s.get(d);f===void 0&&(f=new Map,s.set(d,f),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 u=f.get(l);if(u!==void 0)return u.transport;let p=n.lookup(l);if(p===void 0)return;let h=Sh(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),JI)}),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}),w=new WI({sessionIdGenerator:()=>zI()});return await h.connect(w),f.set(l,{server:h,transport:w}),w}async function a(d,l){let f=pi(d);if(f===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,m=await o(f,p);if(m===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await m.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 Rh(t,e){XI(t);let n=t.daemon.tls?await mi.readFile(je(t.daemon.tls.key)):void 0,s=t.daemon.tls?await mi.readFile(je(t.daemon.tls.cert)):void 0;await mi.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await GI(t.daemon.logLevel),o=KI({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(YI,{options:{handleProtocols:jf}}),Mc(ee=>{o.log.info(ee)}),Oc(ee=>{o.log.info(ee)});let a=await Ja.load(),c=new Qa,d=new Ga,l=new Va([new Ka(e),new Ya(a),d]),f=$m({validator:l});o.addHook("onRequest",async(ee,$e)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await f(ee,$e)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let m=new ga(t,{onFetched:()=>{xm(m,v)}});xl(ee=>o.log.info(ee));let h={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},w=ee=>ps.spawn({...ee,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:h});Jf(t.compressToolContent);let b=new Wa,v=new Na(m,w,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:h,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new ja(gf(t),void 0,{tokenRegistry:d}),x=new qa(yf(t),void 0,{tokenRegistry:d});nh(o,fe,gs(t));let T=new dd,F=new cd,$,H=()=>{if($!==void 0)return $;let ee=o.server.address();return $=`http://127.0.0.1:${ee&&typeof ee=="object"?ee.port:t.daemon.port}`,$};eh(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:F,mcpTokenRegistry:T,getDaemonOrigin:H}),th(o,m,v,{npmRegistry:t.npmRegistry}),sh(o,S),rh(o,x),ih(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]}),ph(o,{store:a,rateLimiter:c}),bh(o,T),vh(o,T),kh(o,T,F),yh(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(ee,$e)=>S.reportVersion(ee,$e),onTransformerVersion:(ee,$e)=>x.reportVersion(ee,$e),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:F,getDaemonOrigin:H,registry:m});let J=!!t.daemon.tls;await o.listen({host:J?"127.0.0.1":t.daemon.host,port:J?0:t.daemon.port});let B=o.server.address(),N=B&&typeof B=="object"?B.port:t.daemon.port,j,X=t.daemon.host,Y=N;if(J&&n&&s){j=QI({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:N,tlsOptions:{key:n,cert:s},logger:o.log});let ee=j.address();ee&&typeof ee=="object"&&(Y=ee.port)}await mi.mkdir(_.home(),{recursive:!0}),await Cf({pid:process.pid,host:X,port:Y,loopbackPort:N,startedAt:new Date().toISOString()});let be={daemonUrl:`http://127.0.0.1:${N}`,daemonHost:"127.0.0.1",daemonPort:N,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${N}/acp`,hydraHome:_.home()};S.setContext(be),x.setContext(be),await S.start(),await x.start(),v.resurrectPendingQueues().catch(ee=>{o.log.warn(`queue replay scan failed: ${ee.message}`)}),v.resumePendingCompactions().catch(ee=>{o.log.warn(`compaction resume scan failed: ${ee.message}`)});let V=t.daemon.agentSyncIntervalMinutes*60*1e3,ge=V>0?Cm({registry:m,manager:v,intervalMs:V,logger:h}):void 0,Je=t.daemon.sessionGcIntervalMinutes*60*1e3,Ms=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ct=Je>0?Am({manager:v,intervalMs:Je,maxAgeMs:Ms,logger:h}):void 0;return{app:o,manager:v,registry:m,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:F,processRegistry:d,shutdown:async()=>{Ct&&Ct(),ge&&ge(),clearInterval(u),clearInterval(p);let ee=async($e,pn)=>{try{await pn()}catch(Ce){o.log.warn(`shutdown step ${$e} failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>S.stop()),await ee("transformers.stop",()=>x.stop()),await ee("manager.closeAll",()=>v.closeAll()),await ee("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await ee("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await ee("manager.flushMetaWrites",()=>v.flushMetaWrites()),await ee("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Mc(null),Oc(null),xl(null),j&&await ee("tlsTerminator.close",()=>new Promise($e=>j.close(()=>$e()))),await ee("app.close",()=>o.close());try{xh.unlinkSync(_.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}async function GI(t){let e=await VI({file:_.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=Ih.destination(2);return{stream:Ih.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function QI(t){let e=Ah.createServer(t.tlsOptions,n=>{let s=Ch.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 XI(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.`)}lr();Nt();xo();import*as Eh from"fs";import*as hi from"fs/promises";async function gi(t,e,n){let s=sx(e),r;try{r=await hi.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=Eh.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await hi.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await hi.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 hi.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let f=Buffer.alloc(l);await r.read(f,0,l,i),o=f.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
267
267
  `).slice(-n-1);process.stdout.write(d.join(`
268
268
  `)),o.endsWith(`
269
269
  `)||process.stdout.write(`
270
- `)}finally{await r.close()}return e}function dd(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 ex(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}
270
+ `)}finally{await r.close()}return e}function md(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 sx(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
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 Ph(t={}){let e=await ye(),n=await qi();if(await id(e)){let r=await ai();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
273
- `);return}if(Rr(t,"foreground")){process.title="hydra-daemon";let r=await Ah(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
274
- `);let i=async()=>{process.stdout.write(`Shutting down...
275
- `),await r.shutdown(),process.exit(0)};process.on("SIGINT",()=>{i()}),process.on("SIGTERM",()=>{i()}),process.on("SIGHUP",()=>{});return}od(),await ad(e);let s=await ai();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
276
- `)}async function Mh(){let t=await ai();if(!t){process.stdout.write(`No running daemon found.
272
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function Mh(t={}){let e=await ye(),n=await Xi();if(await ud(e)){let r=await yi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
273
+ `);return}if(Br(t,"foreground")){process.title="hydra-daemon";let r=await Rh(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
274
+ `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
275
+ `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
276
+ `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
277
+ `),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}fd(),await pd(e);let s=await yi();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
279
+ `)}async function _h(){let t=await yi();if(!t){process.stdout.write(`No running daemon found.
277
280
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
278
281
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
279
- `)}}async function _h(){let t=await ye();await qi();let e=await ai();if(e&&tn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
282
+ `)}}async function $h(){let t=await ye();await Xi();let e=await yi();if(e&&dn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
280
283
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
281
- `),process.exit(1)}await nx(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
284
+ `),process.exit(1)}await ix(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
282
285
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
283
- `);if(od(),await ad(t),await id(t)){let n=await ai();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
284
- `)}}async function nx(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!tn(t))return!0;await tx(50)}return!1}async function $h(t){await oi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Oh(){let t=await ai();if(!t){process.stdout.write(`Daemon: not running
286
+ `);if(fd(),await pd(t),await ud(t)){let n=await yi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
287
+ `)}}async function ix(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!dn(t))return!0;await rx(50)}return!1}async function Oh(t){await gi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Fh(){let t=await yi();if(!t){process.stdout.write(`Daemon: not running
285
288
  `),process.stdout.write(`CLI version: ${fe}
286
- `);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}
287
- `);let n,s;if(e)try{let o=await ye();n=await Xs(o),s=cs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
289
+ `);return}let e=dn(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 ye();n=await cr(o),s=gs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
288
291
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
289
292
  `);return}let r=n.version===fe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${fe}
290
293
  `);return}process.stdout.write(`CLI version: ${fe}
291
294
  `),process.stdout.write(`Daemon version: ${n.version}
292
- `),r||process.stdout.write(Eh.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Eh.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function ai(){return Fn()}He();$n();ms();Ws();zi();wn();So();Vs();import*as Kt from"fs/promises";import*as Kh from"os";import*as Yt from"path";hd();async function Yh(t={}){let e=await ye(),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(w=>!w.importedFromMachine||!!w.upstreamSessionId):i.filter(w=>w.importedFromMachine===o&&!w.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
295
+ `),r||process.stdout.write(Ph.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Ph.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function yi(){return zn()}Ne();qn();Ss();tr();eo();xn();Po();or();import*as Kt from"fs/promises";import*as Yh from"os";import*as Yt from"path";Sd();async function Vh(t={}){let e=await ye(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Ee(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(w=>!w.importedFromMachine||!!w.upstreamSessionId):i.filter(w=>w.importedFromMachine===o&&!w.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
293
296
  `);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.
294
297
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
295
298
  `);return}process.stdout.write(`No active sessions.
296
- `);return}let c=a.slice().sort((w,b)=>{let v=(b.status==="live"?1:0)-(w.status==="live"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(w.updatedAt||""))}),d=c,l=0;if(!t.all){let w=c.filter(A=>A.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(w,w+b),S=c.length-w-v.length;d=[...c.slice(0,w),...v],l=S}let f=Date.now(),u=d.map(w=>pi(w,f)),p={columns:t.columns??e.tui.sessionColumns??ui,cwdMaxWidth:e.tui.cwdColumnMaxWidth},m=mi(u,p),h=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(hs(fi,m,h,p)+`
297
- `);for(let w of u)process.stdout.write(hs(w,m,h,p)+`
299
+ `);return}let c=a.slice().sort((w,b)=>{let v=(b.status==="live"?1:0)-(w.status==="live"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(w.updatedAt||""))}),d=c,l=0;if(!t.all){let w=c.filter(x=>x.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(w,w+b),S=c.length-w-v.length;d=[...c.slice(0,w),...v],l=S}let f=Date.now(),u=d.map(w=>Ii(w,f)),p={columns:t.columns??e.tui.sessionColumns??Si,cwdMaxWidth:e.tui.cwdColumnMaxWidth},m=xi(u,p),h=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ks(ki,m,h,p)+`
300
+ `);for(let w of u)process.stdout.write(ks(w,m,h,p)+`
298
301
  `);l>0&&process.stdout.write(`
299
302
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
300
- `)}async function Vh(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
301
- `),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}
303
+ `)}async function Gh(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
304
+ `),process.exit(2));let e=await Ee(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
302
305
  `),process.exit(1)),process.stdout.write(`Killed ${t}
303
- `)}async function Gh(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
304
- `),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}
306
+ `)}async function Qh(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
307
+ `),process.exit(2));let e=await Ee(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
305
308
  `),process.exit(1)),process.stdout.write(`Removed ${t}
306
- `)}async function Qh(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)}
309
+ `)}async function Xh(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 Ee("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
307
310
  `);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.
308
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${ci(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
311
+ `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${bi(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
309
312
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
310
313
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
311
- `)}async function Xh(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
312
- `),process.exit(2));let s=await Ds(),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}
314
+ `)}async function Zh(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 Gs(),r=await wi(),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}
313
316
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
314
317
  `)||process.stdout.write(`
315
- `);return}let c=e==="."?vx(o,t):e;await Kt.mkdir(Yt.dirname(Yt.resolve(c)),{recursive:!0}),await Kt.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
316
- `)}async function Zh(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
317
- `),process.exit(2));let n,s,r=await hx(t);if(r!==null){let o=gx(r.raw);n=Va(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Yt.basename(t,Yt.extname(t))}-${a}.md`}else{let o=await Ds(),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}
318
+ `);return}let c=e==="."?Ix(o,t):e;await Kt.mkdir(Yt.dirname(Yt.resolve(c)),{recursive:!0}),await Kt.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
319
+ `)}async function eg(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 wx(t);if(r!==null){let o=bx(r.raw);n=td(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Yt.basename(t,Yt.extname(t))}-${a}.md`}else{let o=await Gs(),a=await wi(),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}
318
321
  `),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(`
319
322
  `)||process.stdout.write(`
320
323
  `);return}let i=e==="."?s:e;await Kt.mkdir(Yt.dirname(Yt.resolve(i)),{recursive:!0}),await Kt.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
321
- `)}async function hx(t){try{if(!(await Kt.stat(t)).isFile())return null}catch{return null}let e=await Kt.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
322
- `),process.exit(1)}}function gx(t){try{return sn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
323
- `),process.exit(1)}}async function eg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
324
+ `)}async function wx(t){try{if(!(await Kt.stat(t)).isFile())return null}catch{return null}let e=await Kt.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 bx(t){try{return ln(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
326
+ `),process.exit(1)}}async function tg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
324
327
  `),process.exit(2));let n;if(e.cwd!==void 0){let a=Yt.resolve(e.cwd);try{(await Kt.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
325
328
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
326
- `),process.exit(1)}n=a}let s;t==="-"?s=await bx():s=await Kt.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
327
- `),process.exit(1)}if(e.info===!0){let a=await ye();wx(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.
329
+ `),process.exit(1)}n=a}let s;t==="-"?s=await kx():s=await Kt.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 ye();Sx(r,a.tui.cwdColumnMaxWidth);return}let i=await Ee("/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.
328
331
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
329
332
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
330
333
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
331
- `)}function yx(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 wx(t,e){let n;try{n=sn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
332
- `),process.exit(1)}let s=yx(n),r=pi(s),i={columns:md,cwdMaxWidth:e},o=mi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(hs(fi,o,a,i)+`
333
- `),process.stdout.write(hs(r,o,a,i)+`
334
+ `)}function vx(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 Sx(t,e){let n;try{n=ln(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
335
+ `),process.exit(1)}let s=vx(n),r=Ii(s),i={columns:vd,cwdMaxWidth:e},o=xi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ks(ki,o,a,i)+`
336
+ `),process.stdout.write(ks(r,o,a,i)+`
334
337
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
335
338
  lineage: ${n.session.lineageId}
336
339
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -338,108 +341,108 @@ origin session: ${n.session.sessionId}
338
341
  origin upstream: ${c}
339
342
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
340
343
  `:`
341
- `))}async function bx(){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 vx(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 tg(t,e={}){let n=await ye(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Et(n),l=e.cwd?Yt.resolve(e.cwd):process.cwd(),f=await In(d,{cwd:l,all:!0}),u=fd(f,l);u||(process.stderr.write(`No sessions found for ${l}.
342
- `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=Sx(e.host,n),a=Ge(s),c=vf({host:r,port:i,sessionId:a});process.stdout.write(c+`
344
+ `))}async function kx(){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 Ix(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 ng(t,e={}){let n=await ye(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Et(n),l=e.cwd?Yt.resolve(e.cwd):process.cwd(),f=await En(d,{cwd:l,all:!0}),u=wd(f,l);u||(process.stderr.write(`No sessions found for ${l}.
345
+ `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=xx(e.host,n),a=Ve(s),c=kf({host:r,port:i,sessionId:a});process.stdout.write(c+`
343
346
  `),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.
344
- `)}function Sx(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Jh(t,en);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Jh(e.daemon.publicHost,en);return{host:n,port:s,isFallback:!1}}return kx(e.daemon.host)?{host:Ix(),port:e.daemon.port,isFallback:!1}:Us(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 kx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function Ix(){let t=Kh.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Jh(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}}nu();hd();Xl();He();me();ms();var iC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function Sd(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function wi(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function kd(t){let e=iC[t],n=`/v1/${e.plural}`;async function s(){let f=(await _e(n,{expectStatus:200})).body[e.plural]??[];if(f.length===0){process.stdout.write(`No ${e.plural} configured.
345
- `);return}let u=f.map(w=>({name:w.name,status:w.status.toUpperCase(),version:w.version??"-",pid:w.pid!=null?String(w.pid):"-",restarts:String(w.restartCount),started:w.startedAt?ci(w.startedAt):"-",log:w.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},m={name:wi(p.name,u.map(w=>w.name)),status:wi(p.status,u.map(w=>w.status)),version:wi(p.version,u.map(w=>w.version)),pid:wi(p.pid,u.map(w=>w.pid)),restarts:wi(p.restarts,u.map(w=>w.restarts)),started:wi(p.started,u.map(w=>w.started))},h=w=>[w.name.padEnd(m.name),w.status.padEnd(m.status),w.version.padEnd(m.version),w.pid.padStart(m.pid),w.restarts.padStart(m.restarts),w.started.padEnd(m.started),w.log].join(" ");process.stdout.write(h(p)+`
347
+ `)}function xx(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Kh(t,an);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Kh(e.daemon.publicHost,an);return{host:n,port:s,isFallback:!1}}return Cx(e.daemon.host)?{host:Ax(),port:e.daemon.port,isFallback:!1}:Xs(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 Cx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function Ax(){let t=Yh.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Kh(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}}ou();Sd();nu();Ne();pe();Ss();var dC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function Rd(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Ti(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Td(t){let e=dC[t],n=`/v1/${e.plural}`;async function s(){let f=(await Ee(n,{expectStatus:200})).body[e.plural]??[];if(f.length===0){process.stdout.write(`No ${e.plural} configured.
348
+ `);return}let u=f.map(w=>({name:w.name,status:w.status.toUpperCase(),version:w.version??"-",pid:w.pid!=null?String(w.pid):"-",restarts:String(w.restartCount),started:w.startedAt?bi(w.startedAt):"-",log:w.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},m={name:Ti(p.name,u.map(w=>w.name)),status:Ti(p.status,u.map(w=>w.status)),version:Ti(p.version,u.map(w=>w.version)),pid:Ti(p.pid,u.map(w=>w.pid)),restarts:Ti(p.restarts,u.map(w=>w.restarts)),started:Ti(p.started,u.map(w=>w.started))},h=w=>[w.name.padEnd(m.name),w.status.padEnd(m.status),w.version.padEnd(m.version),w.pid.padStart(m.pid),w.restarts.padStart(m.restarts),w.started.padEnd(m.started),w.log].join(" ");process.stdout.write(h(p)+`
346
349
  `);for(let w of u)process.stdout.write(h(w)+`
347
350
  `);for(let w of f)w.failureReason&&process.stdout.write(` \u21B3 ${w.name}: ${w.failureReason}
348
351
  `)}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]
349
352
  `),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._-]+
350
- `),process.exit(2);return}await ye();let f=await li(),u=f;(!u[e.plural]||typeof u[e.plural]!="object")&&(u[e.plural]={});let p=u[e.plural];if(p[d]){process.stderr.write(`${yg(e.singular)} '${d}' already exists in config.
351
- `),process.exit(1);return}let m=ld(l,e.singular),h=m.command,w={};h.length>0&&(w.command=h),m.args.length>0&&(w.args=m.args),Object.keys(m.env).length>0&&(w.env=m.env),m.enabled||(w.enabled=!1),p[d]=w,await Nl(f),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
352
- `);let b={name:d,...w};try{let v=await _e(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,A=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${A}
353
- `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${Sd(v.body)}). Restart the daemon to apply.
353
+ `),process.exit(2);return}await ye();let f=await vi(),u=f;(!u[e.plural]||typeof u[e.plural]!="object")&&(u[e.plural]={});let p=u[e.plural];if(p[d]){process.stderr.write(`${wg(e.singular)} '${d}' already exists in config.
354
+ `),process.exit(1);return}let m=gd(l,e.singular),h=m.command,w={};h.length>0&&(w.command=h),m.args.length>0&&(w.args=m.args),Object.keys(m.env).length>0&&(w.env=m.env),m.enabled||(w.enabled=!1),p[d]=w,await jl(f),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
355
+ `);let b={name:d,...w};try{let v=await Ee(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}${Rd(v.body)}). Restart the daemon to apply.
354
357
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
355
- `),process.exit(2);return}await ye();let l=await li(),f=l,u=f[e.plural]??{};if(!u[d]){process.stderr.write(`${yg(e.singular)} '${d}' not found in config.
356
- `),process.exit(1);return}delete u[d],f[e.plural]=u,await Nl(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
357
- `);try{let p=await _e(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
358
- `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Sd(p.body)}).
358
+ `),process.exit(2);return}await ye();let l=await vi(),f=l,u=f[e.plural]??{};if(!u[d]){process.stderr.write(`${wg(e.singular)} '${d}' not found in config.
359
+ `),process.exit(1);return}delete u[d],f[e.plural]=u,await jl(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
360
+ `);try{let p=await Ee(`${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}${Rd(p.body)}).
359
362
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
360
363
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
361
- `),process.exit(2);return}if(d==="all"){await a(l);return}let f=await _e(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!f.ok){process.stderr.write(`HTTP ${f.status}${Sd(f.body)}
364
+ `),process.exit(2);return}if(d==="all"){await a(l);return}let f=await Ee(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!f.ok){process.stderr.write(`HTTP ${f.status}${Rd(f.body)}
362
365
  `),process.exit(1);return}let u=f.body,p=u.pid!=null?` pid=${u.pid}`:"";process.stdout.write(`${d}: ${u.status}${p}
363
- `)}async function a(d){let p=((await _e(n,{expectStatus:200})).body[e.plural]??[]).filter(h=>d==="start"?h.enabled&&h.status!=="running":h.status==="running");if(p.length===0){let h=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${h}.
364
- `);return}let m=0;for(let h of p)try{let w=await _e(`${n}/${encodeURIComponent(h.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!w.ok){process.stdout.write(`${h.name}: ERROR HTTP ${w.status}${Sd(w.body)}
366
+ `)}async function a(d){let p=((await Ee(n,{expectStatus:200})).body[e.plural]??[]).filter(h=>d==="start"?h.enabled&&h.status!=="running":h.status==="running");if(p.length===0){let h=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${h}.
367
+ `);return}let m=0;for(let h of p)try{let w=await Ee(`${n}/${encodeURIComponent(h.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!w.ok){process.stdout.write(`${h.name}: ERROR HTTP ${w.status}${Rd(w.body)}
365
368
  `),m+=1;continue}let b=w.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${h.name}: ${b.status}${v}
366
369
  `)}catch(w){process.stdout.write(`${h.name}: ERROR ${w.message}
367
- `),m+=1}m>0&&process.exit(1)}async function c(d){let{name:l,rest:f}=dd(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
368
- `),process.exit(2);return}let u=e.logFile(l);await oi(u,f,`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 yg(t){return t.charAt(0).toUpperCase()+t.slice(1)}var tr=kd("extension"),wg=tr.list,bg=tr.add,vg=tr.remove,Sg=tr.start,kg=tr.stop,Ig=tr.restart,xg=tr.logs;var nr=kd("transformer"),Cg=nr.list,Ag=nr.add,Rg=nr.remove,Tg=nr.start,Eg=nr.stop,Pg=nr.restart,Mg=nr.logs;He();me();ms();async function Og(){let e=(await _e("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
369
- `);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:Bn(s.id,n.map(a=>a.id)),name:Bn(s.name,n.map(a=>a.name)),version:Bn(s.version,n.map(a=>a.version)),source:Bn(s.source,n.map(a=>a.source)),distributions:Bn(s.distributions,n.map(a=>a.distributions)),installed:Bn(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)+`
370
+ `),m+=1}m>0&&process.exit(1)}async function c(d){let{name:l,rest:f}=md(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
371
+ `),process.exit(2);return}let u=e.logFile(l);await gi(u,f,`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 wg(t){return t.charAt(0).toUpperCase()+t.slice(1)}var fr=Td("extension"),bg=fr.list,vg=fr.add,Sg=fr.remove,kg=fr.start,Ig=fr.stop,xg=fr.restart,Cg=fr.logs;var pr=Td("transformer"),Ag=pr.list,Rg=pr.add,Tg=pr.remove,Eg=pr.start,Pg=pr.stop,Mg=pr.restart,_g=pr.logs;Ne();pe();Ss();async function Fg(){let e=(await Ee("/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:Kn(s.id,n.map(a=>a.id)),name:Kn(s.name,n.map(a=>a.name)),version:Kn(s.version,n.map(a=>a.version)),source:Kn(s.source,n.map(a=>a.source)),distributions:Kn(s.distributions,n.map(a=>a.distributions)),installed:Kn(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)+`
370
373
  `);for(let a of n)process.stdout.write(i(a)+`
371
- `);let o=e.fetchedAt!==void 0?` (synced ${ci(e.fetchedAt)})`:"";process.stdout.write(`
374
+ `);let o=e.fetchedAt!==void 0?` (synced ${bi(e.fetchedAt)})`:"";process.stdout.write(`
372
375
  Registry version: ${e.version}${o}
373
- `)}async function ru(t){if((await ye()).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.
374
- `),process.exit(2))}async function Fg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
376
+ `)}async function du(t){if((await ye()).agents[t]!==void 0)return;let n;try{let s=await Ee("/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 Lg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
375
378
  `),process.exit(2);return}process.stdout.write(`Installing ${t}\u2026
376
- `);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"}
379
+ `);let n=(await Ee(`/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"}
377
380
  `);return}process.stdout.write(`Installed ${n.agentId} (${n.version}, ${n.distribution})
378
381
  `),n.command&&process.stdout.write(` \u2192 ${n.command}
379
- `)}async function Lg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
380
- `),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).
381
- `);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:Bn(r.id,s.map(a=>a.id)),upstream:Bn(r.upstream,s.map(a=>a.upstream)),cwd:Bn(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)+`
382
+ `)}async function Bg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
383
+ `),process.exit(2);return}let n=(await Ee(`/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:Kn(r.id,s.map(a=>a.id)),upstream:Kn(r.upstream,s.map(a=>a.upstream)),cwd:Kn(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)+`
382
385
  `);for(let a of s)process.stdout.write(o(a)+`
383
386
  `);process.stdout.write(`
384
387
  Synced ${n.synced.length} session(s); skipped ${n.skipped} already tracked.
385
- `)}async function Bg(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
386
- `),process.exit(2);return}let n=_.agentLogFile(t);await oi(n,e,"No log file (agent never ran?)")}async function Ng(t,e){let n=await ye();if(!t){let c=await $g()??su(await li());process.stdout.write(`${_g(c)}
387
- `);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(", ")}
388
- `),process.exit(1);return}e!==void 0?await gf(t,e):await na(t);let i=su(await li());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
389
- `),process.stdout.write(`${_g(i)}
390
- `);let o=await $g();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Dg(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
391
- `))}function _g(t){return`Default agent is ${Dg(t)}`}function Dg(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function su(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 $g(){try{let t=await _e("/v1/config",{rethrowNetworkError:!0});return t.ok?su(t.body):void 0}catch{return}}async function iu(){let e=(await _e("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
392
- `)}async function Hg(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
393
- `),process.exit(2);return}await yf(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
388
+ `)}async function Ng(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 gi(n,e,"No log file (agent never ran?)")}async function Dg(t,e){let n=await ye();if(!t){let c=await Og()??au(await vi());process.stdout.write(`${$g(c)}
390
+ `);return}let s;try{let a=await Ee("/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 wf(t,e):await da(t);let i=au(await vi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
392
+ `),process.stdout.write(`${$g(i)}
393
+ `);let o=await Og();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Hg(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
394
+ `))}function $g(t){return`Default agent is ${Hg(t)}`}function Hg(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function au(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 Og(){try{let t=await Ee("/v1/config",{rethrowNetworkError:!0});return t.ok?au(t.body):void 0}catch{return}}async function cu(){let e=(await Ee("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
395
+ `)}async function Ug(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
396
+ `),process.exit(2);return}await bf(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
394
397
  `):process.stdout.write(`Pinned ${t} to ${e}.
395
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Ug(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
398
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function jg(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
396
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._-]+
397
- `),process.exit(2);return}let n=ld(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 dc(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(" "):""}
398
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function jg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
399
- `),process.exit(2);return}await dc(t,void 0),process.stdout.write(`Removed local agent ${t}.
400
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function ou(t){await wf(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.
401
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Bn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}vo();ni();Js();He();Ws();Zs();xt();Ht();fa();lu();import kC from"os";import{spawn as IC}from"child_process";async function xC({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){try{return await t.request("session/new",{cwd:kC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
402
- `),{exitCode:0}}catch(i){if(i instanceof Error&&"code"in i&&i.code===q.AuthRequired){let o=i.data,a=o?._meta?.["hydra-acp"]?.authMethods??n,c=o?._meta?.["hydra-acp"]?.agentId??e,d=await CC(a,s),f=await cu(d,{authenticate:u=>t.request("authenticate",{methodId:u,_meta:{"hydra-acp":{agentId:c}}}),runTerminalAuth:u=>new Promise(p=>{let m=r(u.command,u.args,{stdio:"inherit",env:u.env,cwd:u.cwd});m.on("exit",h=>{p({exitCode:h})}),m.on("error",()=>{p({exitCode:-1})})})});return f.kind==="terminal-completed"?{exitCode:0}:f.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
400
+ `),process.exit(2);return}let n=gd(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 fc(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 qg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
402
+ `),process.exit(2);return}await fc(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 lu(t){await vf(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 Kn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Eo();fi();sr();Ne();tr();lr();It();Nt();wa();mu();import CC from"os";import{spawn as AC}from"child_process";async function RC({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){try{return await t.request("session/new",{cwd:CC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
405
+ `),{exitCode:0}}catch(i){if(i instanceof Error&&"code"in i&&i.code===z.AuthRequired){let o=i.data,a=o?._meta?.["hydra-acp"]?.authMethods??n,c=o?._meta?.["hydra-acp"]?.agentId??e,d=await TC(a,s),f=await pu(d,{authenticate:u=>t.request("authenticate",{methodId:u,_meta:{"hydra-acp":{agentId:c}}}),runTerminalAuth:u=>new Promise(p=>{let m=r(u.command,u.args,{stdio:"inherit",env:u.env,cwd:u.cwd});m.on("exit",h=>{p({exitCode:h})}),m.on("error",()=>{p({exitCode:-1})})})});return f.kind==="terminal-completed"?{exitCode:0}:f.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
403
406
  `),{exitCode:0}):f.kind==="error"?(process.stderr.write(`${f.message}
404
407
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${f.exitCode}
405
- `),{exitCode:1})}throw i}}async function CC(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}
408
+ `),{exitCode:1})}throw i}}async function TC(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}
406
409
  `),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:
407
410
  ${s.join(`
408
411
  `)}
409
412
  `);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}
410
413
  `),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})
411
- `),process.exit(2)}async function oy(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
412
- `),process.exit(2));let n=await ye(),s=await Et(n);await ps(n);let r=["acp.v1",`hydra-acp-token.${s.token}`],i=await er(s.wsUrl,r),o=kn(i),a=new Pt(o);try{await a.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:fe}})}catch{}let c;try{c=await xC({conn:a,agentId:t,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:IC})}finally{i.close()}process.exit(c.exitCode)}pc();ms();async function ay(t){let e=Rr(t,"force");if(await Za()&&!e){let r=await _r("Current password: ");await ed(r)||(process.stderr.write(`Wrong password.
413
- `),process.exit(1))}let n=await _r("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
414
- `),process.exit(2));let s=await _r("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
415
- `),process.exit(1)),await uh(n),process.stdout.write(`Password set.
416
- `)}async function dy(){let e=(await _e("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
417
- `);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:Rd(n.id,s.map(o=>o.id)),label:Rd(n.label,s.map(o=>o.label)),createdAt:Rd(n.createdAt,s.map(o=>o.createdAt)),expiresAt:Rd(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)+`
414
+ `),process.exit(2)}async function ay(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
415
+ `),process.exit(2));let n=await ye(),s=await Et(n);await vs(n);let r=["acp.v1",`hydra-acp-token.${s.token}`],i=await ur(s.wsUrl,r),o=Tn(i),a=new Pt(o);try{await a.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:fe}})}catch{}let c;try{c=await RC({conn:a,agentId:t,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:AC})}finally{i.close()}process.exit(c.exitCode)}yc();Ss();async function dy(t){let e=Br(t,"force");if(await id()&&!e){let r=await jr("Current password: ");await od(r)||(process.stderr.write(`Wrong password.
416
+ `),process.exit(1))}let n=await jr("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
+ `),process.exit(2));let s=await jr("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
+ `),process.exit(1)),await fh(n),process.stdout.write(`Password set.
419
+ `)}async function cy(){let e=(await Ee("/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:$d(n.id,s.map(o=>o.id)),label:$d(n.label,s.map(o=>o.label)),createdAt:$d(n.createdAt,s.map(o=>o.createdAt)),expiresAt:$d(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)+`
418
421
  `);for(let o of s)process.stdout.write(i(o)+`
419
- `)}async function cy(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
420
- `),process.exit(2));let e=await _e(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
422
+ `)}async function ly(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
423
+ `),process.exit(2));let e=await Ee(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
421
424
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
422
425
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
423
- `),process.exit(1)}function Rd(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as bs from"fs";He();Ws();Zs();uu();xt();var Td=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(pu(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(fu(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(!fu(e)&&!pu(e)&&"method"in e){if(e.method==="session/update"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0,p=typeof f.update?.messageId=="string"?f.update.messageId:void 0;u&&p&&this.lastMessageIds.set(u,p)}return}if(fu(e)){if(e.method==="session/request_permission"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0;if(u){let p=f.toolCall,m=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:u,toolCallId:m,params:f};if(this.pendingPermissions.set(e.id,h),m){let w=this.pendingPermissionsByToolCall.get(m);w?w.push(e.id):this.pendingPermissionsByToolCall.set(m,[e.id])}}}return}if(!pu(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=Dt(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 fu(t){return"method"in t&&"id"in t&&t.id!==void 0}function pu(t){return!("method"in t)&&"id"in t}Pd();Ht();me();Ji();import{writeFileSync as MC}from"fs";var _C=t=>{MC("/proc/self/comm",t)};function Ai(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??_C;try{s(e.commName??mn())}catch{}}function Ri(t,e=mn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function _d(t){Ai(Ri(process.argv.slice(2)),{commName:"hydra-shim"});let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await ps(e);let s=new Td,r=ya(process.stdin,process.stdout),i=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new Ci({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await NC(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
424
- `);for(let l of d)await DC(a,l,s.lastMessageId(l.sessionId))}}});$C({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
425
- `),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 $C({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(gy("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&qC(i)){e.send({jsonrpc:"2.0",id:i.id,result:dr(i.params)});return}OC(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(gy("client\u2192daemon",i),s.observeFromClient(i),UC(i)){e.send(jC(i));return}if(HC(i)){if(t.sessionId){e.send(WC(i,t.sessionId));return}let o=i;t.agentId&&(o=Md(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Md(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Md(o,{title:r.name}),r.used=!0),t.model&&(o=Md(o,{model:t.model})),e.send(o);return}e.send(i)})}function OC(t,e,n){let s=FC(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=BC(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function FC(t){if(!LC(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function LC(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function BC(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function NC(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
426
- `);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 DC(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}
426
+ `),process.exit(1)}function $d(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as As from"fs";Ne();tr();lr();hu();It();var Od=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(yu(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(gu(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(!gu(e)&&!yu(e)&&"method"in e){if(e.method==="session/update"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0,p=typeof f.update?.messageId=="string"?f.update.messageId:void 0;u&&p&&this.lastMessageIds.set(u,p)}return}if(gu(e)){if(e.method==="session/request_permission"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0;if(u){let p=f.toolCall,m=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:u,toolCallId:m,params:f};if(this.pendingPermissions.set(e.id,h),m){let w=this.pendingPermissionsByToolCall.get(m);w?w.push(e.id):this.pendingPermissionsByToolCall.set(m,[e.id])}}}return}if(!yu(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=Bt(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 gu(t){return"method"in t&&"id"in t&&t.id!==void 0}function yu(t){return!("method"in t)&&"id"in t}Ld();Nt();pe();to();import{writeFileSync as OC}from"fs";var FC=t=>{OC("/proc/self/comm",t)};function Li(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??FC;try{s(e.commName??vn())}catch{}}function Bi(t,e=vn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Nd(t){Li(Bi(process.argv.slice(2)),{commName:"hydra-shim"});let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await vs(e);let s=new Od,r=Ia(process.stdin,process.stdout),i=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new Fi({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await UC(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 jC(a,l,s.lastMessageId(l.sessionId))}}});LC({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 LC({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(yy("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&JC(i)){e.send({jsonrpc:"2.0",id:i.id,result:br(i.params)});return}BC(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(yy("client\u2192daemon",i),s.observeFromClient(i),WC(i)){e.send(zC(i));return}if(qC(i)){if(t.sessionId){e.send(KC(i,t.sessionId));return}let o=i;t.agentId&&(o=Bd(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Bd(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Bd(o,{title:r.name}),r.used=!0),t.model&&(o=Bd(o,{model:t.model})),e.send(o);return}e.send(i)})}function BC(t,e,n){let s=NC(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=HC(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function NC(t){if(!DC(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function DC(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function HC(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function UC(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 jC(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}
427
430
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
428
- `)}}function HC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function UC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function jC(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:fe}}}}function qC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function WC(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var zC=25*1024*1024,hy=!1,cr=null;function gy(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!hy){hy=!0;try{cr=_.shimWireLogFile(),bs.mkdirSync(_.home(),{recursive:!0});let n=bs.statSync(cr,{throwIfNoEntry:!1});n&&n.size>zC&&bs.renameSync(cr,`${cr}.1`)}catch{cr=null}}if(cr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
429
- `;bs.appendFile(cr,n,()=>{})}catch{}}}function Md(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}Js();ni();vo();He();Ws();Zs();ls();xt();Ht();Pd();import{mkdtempSync as nA,rmSync as sA}from"fs";import{tmpdir as rA}from"os";import{join as iA}from"path";function yy(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())}}}yi();import JC from"chalk";import KC from"strip-ansi";var $d=new JC.Instance({level:3});function wy(t,e){if(t.length===0)return"";let n=ys(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(YC(i,e));let r=s.join(`
431
+ `)}}function qC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function WC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function zC(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:fe}}}}function JC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function KC(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var YC=25*1024*1024,gy=!1,vr=null;function yy(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!gy){gy=!0;try{vr=_.shimWireLogFile(),As.mkdirSync(_.home(),{recursive:!0});let n=As.statSync(vr,{throwIfNoEntry:!1});n&&n.size>YC&&As.renameSync(vr,`${vr}.1`)}catch{vr=null}}if(vr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
432
+ `;As.appendFile(vr,n,()=>{})}catch{}}}function Bd(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}sr();fi();Eo();Ne();tr();lr();ys();It();Nt();Ld();import{mkdtempSync as iA,rmSync as oA}from"fs";import{tmpdir as aA}from"os";import{join as dA}from"path";function wy(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())}}}Ri();import VC from"chalk";import GC from"strip-ansi";var Dd=new VC.Instance({level:3});function by(t,e){if(t.length===0)return"";let n=xs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(QC(i,e));let r=s.join(`
430
433
  `);return r.endsWith(`
431
434
  `)||(r+=`
432
- `),r}function YC(t,e){let n=eA(t.body,e);return e==="ansi"?n=tA(n,t.bodyStyle):n=KC(n),n}var VC="\x1B[1m",GC="\x1B[96m",QC="\x1B[93m",XC="\x1B[0m",ZC="\0";function eA(t,e){let n=t.replace(/\^\^/g,ZC);return e==="ansi"&&(n=n.replace(/\^\+/g,VC).replace(/\^C/g,GC).replace(/\^Y/g,QC).replace(/\^:/g,XC)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function tA(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return $d.bold.yellowBright(t);case"heading-2":return $d.bold.cyanBright(t);case"heading-3":return $d.bold(t);case"dim":return $d.dim(t);default:return t}}var oA=1*1024*1024,by="mcp__hydra-acp-stdin__";function vy(t,e){return{sessionId:t,prompt:e,_meta:{[pt]:{ancillary:!0}}}}function aA(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 dA(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(by))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(by))}async function Sy(t){if(Ai(Ri(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.
433
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=nA(iA(rA(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{sA(c,{recursive:!0,force:!0})}catch{}})}let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await ps(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await er(n.wsUrl,s),i=kn(r),o=new Pt(i),a=await lA({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:cA(n.baseUrl,n.token)});process.exit(a.exitCode)}function cA(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 lA(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 Y=>n.dangerouslySkipPermissions?dr(Y):dA(Y)?dr(Y):fy(Y));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Ks,version:fe}})}catch{}let f=await pA(e,n,l),u=!1,p=!0,m="",h=0,w=Y=>{Y.length!==0&&(o(Y),p=Y.charCodeAt(Y.length-1)===10,u=!0)},b=()=>{if(d||m.length===0)return;let Y=wy(m,c);if(m="",Y.length===0)return;let de=h>0?`
434
- `:"";w(de+Y),h+=1},v=()=>{b(),u&&!p&&w(`
435
- `),u=!1};e.onNotification("session/update",Y=>{let de=Y?.update,je=Sn(de,{cwd:n.cwd});if(je){if(je.kind==="agent-text"){d?w(je.text):m+=je.text;return}if(je.kind==="turn-complete"){v();return}switch(je.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,A=async Y=>{let de=[];if(n.prompt&&!S&&de.push({type:"text",text:n.prompt}),Y.length>0&&de.push({type:"text",text:Y}),de.length!==0){try{await e.request("session/prompt",vy(f,de)),S=!0}catch(je){a(`hydra-acp cat: prompt failed: ${je.message}
436
- `);return}v()}},T=0,U,O=new Promise(Y=>{U=Y}),z=!1,V=async Y=>{z||(z=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:f}))().catch(()=>{}),new Promise(je=>setTimeout(je,500))]),await e.close().catch(()=>{}),U({exitCode:Y}))};e.onClose(Y=>{Y&&(a(`hydra-acp cat: ${Y.message}
437
- `),T=1),z||(z=!0,v(),U({exitCode:T}))});let N=[],F=!1,H=!1,Z=async()=>{if(!F){F=!0;try{for(;N.length>0;){let Y=N.shift();if(Y===void 0)break;await A(Y)}}finally{F=!1,H&&N.length===0&&await V(T)}}};if(r&&!n.sessionId)return n.prompt&&await A(""),await V(0),O;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),uA({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:A,onEof:()=>{H=!0,!F&&N.length===0&&V(T)},onError:Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
438
- `),T=1,H=!0,!F&&N.length===0&&V(T)},onPromptFailed:Y=>{a(`hydra-acp cat: ${Y.message}
439
- `),T=1,H=!0,!F&&N.length===0&&V(T)}}),O;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let Y=yy({scheduleFlushCheck:de=>{let je=setImmediate(de);return()=>clearImmediate(je)},onChunk:de=>{N.push(de),Z()}});return s.on("data",de=>{Y.feed(typeof de=="string"?de:de.toString("utf8"))}),s.on("end",()=>{Y.eof(),H=!0,!F&&N.length===0&&V(T)}),s.on("error",de=>{a(`hydra-acp cat: stdin error: ${de.message}
440
- `),T=1,H=!0,!F&&N.length===0&&V(T)}),O}let re="";return s.on("data",Y=>{re+=typeof Y=="string"?Y:Y.toString("utf8")}),s.on("end",()=>{H=!0,re.length>0&&N.push(re),Z()}),s.on("error",Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
441
- `),T=1,H=!0,!F&&N.length===0&&V(T)}),O}function uA(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??oA,d="undecided",l=!1,f=[],u=0,p=!1,m=Promise.resolve(),h=(v,S)=>{let A=v.toString("base64");m=m.then(()=>n.write(s,A,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
442
- `)})},w=async()=>{d="inline";let v=Buffer.concat(f,u).toString("utf8");f=[],u=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}u>0&&(h(Buffer.concat(f,u),!1),f=[],u=0),d="file",l&&(l=!1,h(Buffer.alloc(0),!0)),await m.catch(()=>{});let S=fA(r.prompt,v.capacityBytes);e.request("session/prompt",vy(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||h(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){f.push(S),u+=S.length,u>c&&b();return}if(d==="pivoting"){f.push(S),u+=S.length;return}if(d==="file"){h(S,!1);return}f.push(S),u+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){w();return}if(d==="pivoting"){l=!0;return}d==="file"&&h(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function fA(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:
435
+ `),r}function QC(t,e){let n=sA(t.body,e);return e==="ansi"?n=rA(n,t.bodyStyle):n=GC(n),n}var XC="\x1B[1m",ZC="\x1B[96m",eA="\x1B[93m",tA="\x1B[0m",nA="\0";function sA(t,e){let n=t.replace(/\^\^/g,nA);return e==="ansi"&&(n=n.replace(/\^\+/g,XC).replace(/\^C/g,ZC).replace(/\^Y/g,eA).replace(/\^:/g,tA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function rA(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Dd.bold.yellowBright(t);case"heading-2":return Dd.bold.cyanBright(t);case"heading-3":return Dd.bold(t);case"dim":return Dd.dim(t);default:return t}}var cA=1*1024*1024,vy="mcp__hydra-acp-stdin__";function Sy(t,e){return{sessionId:t,prompt:e,_meta:{[mt]:{ancillary:!0}}}}function lA(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 uA(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(vy))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(vy))}async function ky(t){if(Li(Bi(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=iA(dA(aA(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{oA(c,{recursive:!0,force:!0})}catch{}})}let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await vs(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await ur(n.wsUrl,s),i=Tn(r),o=new Pt(i),a=await pA({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:fA(n.baseUrl,n.token)});process.exit(a.exitCode)}function fA(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 pA(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 V=>n.dangerouslySkipPermissions?br(V):uA(V)?br(V):py(V));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:rr,version:fe}})}catch{}let f=await gA(e,n,l),u=!1,p=!0,m="",h=0,w=V=>{V.length!==0&&(o(V),p=V.charCodeAt(V.length-1)===10,u=!0)},b=()=>{if(d||m.length===0)return;let V=by(m,c);if(m="",V.length===0)return;let ge=h>0?`
437
+ `:"";w(ge+V),h+=1},v=()=>{b(),u&&!p&&w(`
438
+ `),u=!1};e.onNotification("session/update",V=>{let ge=V?.update,Je=Rn(ge,{cwd:n.cwd});if(Je){if(Je.kind==="agent-text"){d?w(Je.text):m+=Je.text;return}if(Je.kind==="turn-complete"){v();return}switch(Je.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,x=async V=>{let ge=[];if(n.prompt&&!S&&ge.push({type:"text",text:n.prompt}),V.length>0&&ge.push({type:"text",text:V}),ge.length!==0){try{await e.request("session/prompt",Sy(f,ge)),S=!0}catch(Je){a(`hydra-acp cat: prompt failed: ${Je.message}
439
+ `);return}v()}},T=0,F,$=new Promise(V=>{F=V}),H=!1,J=async V=>{H||(H=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:f}))().catch(()=>{}),new Promise(Je=>setTimeout(Je,500))]),await e.close().catch(()=>{}),F({exitCode:V}))};e.onClose(V=>{V&&(a(`hydra-acp cat: ${V.message}
440
+ `),T=1),H||(H=!0,v(),F({exitCode:T}))});let B=[],N=!1,j=!1,X=async()=>{if(!N){N=!0;try{for(;B.length>0;){let V=B.shift();if(V===void 0)break;await x(V)}}finally{N=!1,j&&B.length===0&&await J(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await J(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),mA({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{j=!0,!N&&B.length===0&&J(T)},onError:V=>{a(`hydra-acp cat: stdin error: ${V.message}
441
+ `),T=1,j=!0,!N&&B.length===0&&J(T)},onPromptFailed:V=>{a(`hydra-acp cat: ${V.message}
442
+ `),T=1,j=!0,!N&&B.length===0&&J(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let V=wy({scheduleFlushCheck:ge=>{let Je=setImmediate(ge);return()=>clearImmediate(Je)},onChunk:ge=>{B.push(ge),X()}});return s.on("data",ge=>{V.feed(typeof ge=="string"?ge:ge.toString("utf8"))}),s.on("end",()=>{V.eof(),j=!0,!N&&B.length===0&&J(T)}),s.on("error",ge=>{a(`hydra-acp cat: stdin error: ${ge.message}
443
+ `),T=1,j=!0,!N&&B.length===0&&J(T)}),$}let be="";return s.on("data",V=>{be+=typeof V=="string"?V:V.toString("utf8")}),s.on("end",()=>{j=!0,be.length>0&&B.push(be),X()}),s.on("error",V=>{a(`hydra-acp cat: stdin error: ${V.message}
444
+ `),T=1,j=!0,!N&&B.length===0&&J(T)}),$}function mA(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??cA,d="undecided",l=!1,f=[],u=0,p=!1,m=Promise.resolve(),h=(v,S)=>{let x=v.toString("base64");m=m.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
445
+ `)})},w=async()=>{d="inline";let v=Buffer.concat(f,u).toString("utf8");f=[],u=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}u>0&&(h(Buffer.concat(f,u),!1),f=[],u=0),d="file",l&&(l=!1,h(Buffer.alloc(0),!0)),await m.catch(()=>{});let S=hA(r.prompt,v.capacityBytes);e.request("session/prompt",Sy(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||h(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){f.push(S),u+=S.length,u>c&&b();return}if(d==="pivoting"){f.push(S),u+=S.length;return}if(d==="file"){h(S,!1);return}f.push(S),u+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){w();return}if(d==="pivoting"){l=!0;return}d==="file"&&h(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function hA(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:
443
446
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
444
447
  - \`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.
445
448
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -454,49 +457,49 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
454
457
  User's question:
455
458
  ${t}`:`${s}
456
459
 
457
- 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 pA(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Ks,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=aA(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={[pt]:s});let o=await t.request("session/new",i);return Dt(o._meta),o.sessionId}He();me();function Od(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 ky(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 mA(t){try{return JSON.parse(t)}catch{return t}}function Iy(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function xy(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
458
- `),process.exit(2));let e=Od(t),n=await ye(),s=ky(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
459
- `),process.exit(1)),process.stdout.write(`${Iy(s)}
460
- `)}async function Cy(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
461
- `),process.exit(2));let n=Od(t),s=mA(e);try{await On(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}
462
- `),process.exit(1)}process.stdout.write(`set ${t} = ${Iy(s)}
463
- `)}async function Ay(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
464
- `),process.exit(2));let e=Od(t);try{await On(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}
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 gA(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:rr,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=lA(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={[mt]:s});let o=await t.request("session/new",i);return Bt(o._meta),o.sessionId}Ne();pe();function Hd(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 Iy(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 yA(t){try{return JSON.parse(t)}catch{return t}}function xy(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function Cy(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
461
+ `),process.exit(2));let e=Hd(t),n=await ye(),s=Iy(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
462
+ `),process.exit(1)),process.stdout.write(`${xy(s)}
463
+ `)}async function Ay(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
464
+ `),process.exit(2));let n=Hd(t),s=yA(e);try{await Wn(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} = ${xy(s)}
466
+ `)}async function Ry(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
467
+ `),process.exit(2));let e=Hd(t);try{await Wn(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}
465
468
  `),process.exit(1)}process.stdout.write(`unset ${t}
466
- `)}async function Ry(t){let e=await ye(),n=t?ky(e,Od(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
469
+ `)}async function Ty(t){let e=await ye(),n=t?Iy(e,Hd(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
467
470
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
468
- `)}function Ty(){process.stdout.write(`${_.config()}
469
- `)}He();$n();Zs();Ht();ms();async function My(t={}){let{report:e,configLoaded:n}=await hA();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
471
+ `)}function Ey(){process.stdout.write(`${_.config()}
472
+ `)}Ne();qn();lr();Nt();Ss();async function _y(t={}){let{report:e,configLoaded:n}=await wA();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
470
473
  `);return}process.stdout.write(`CLI: ${e.cli}
471
474
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
472
- `),e.daemonReachable&&(Ey("Extensions",e.extensions),Ey("Transformers",e.transformers)))}function Ey(t,e){if(process.stdout.write(`
475
+ `),e.daemonReachable&&(Py("Extensions",e.extensions),Py("Transformers",e.transformers)))}function Py(t,e){if(process.stdout.write(`
473
476
  ${t}:
474
477
  `),e.length===0){process.stdout.write(` (none)
475
478
  `);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}
476
- `)}}async function hA(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await ye()}catch{return{report:t,configLoaded:!1}}let n=await Xs(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 Ds()}catch{return{report:t,configLoaded:!0}}let r=await di(),i={Authorization:`Bearer ${s}`};return t.extensions=await Py(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Py(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Py(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 gA}from"child_process";import{accessSync as yA,constants as wA,statSync as bA}from"fs";import{delimiter as vA,join as SA}from"path";var kA=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function IA(t){return kA.has(t)}function xA(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function CA(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 AA(t){try{if(!bA(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return yA(t,wA.X_OK),!0}catch{return!1}}function RA(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(vA).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=SA(o,r+a);if(AA(c))return c}}function TA(t,e){let n=gA(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
477
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function _y(t){let e=xA(t);if(e===void 0||IA(e))return!1;let n=RA(e);if(n===void 0)return!1;TA(n,CA(t))}mu();var Is=!1,zw=!1;function Jw(t){!t||zw||(zw=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
478
- `))}async function c0(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(Vi(),Pf));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],A=v.slice(1),{flags:T}=rc(b);if(Yw(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.
479
- `),process.exit(2);return}let U=S??at(T,"agent");if(!U){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
480
- `),process.exit(2);return}let O=await Vw(Sc(T),{allowPrompt:!1}),z=at(T,"name"),V=at(T,"model");Is=!0;let N=T["dangerously-skip-permissions"]===!0;Jw(N);let F={agentId:U,agentArgs:A,name:z,model:V,dangerouslySkipPermissions:N};O?.sessionId!==void 0&&(F.sessionId=O.sessionId),O?.target!==void 0&&O.fromUrl&&(F.target=O.target),await _d(F);return}Ju(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&_y(e);let{positional:s,flags:r}=rc(e);if(Yw(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${l0()}
481
- `);return}if(r.help===!0){Yu();return}let i=Ju(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=at(r,"name"),d=at(r,"agent"),l=at(r,"model"),f=r["dangerously-skip-permissions"]===!0;Jw(f);let u=Sc(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,m=await Vw(u,{allowPrompt:p});m!==void 0&&m.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
482
- `),process.exit(2));let h=m?.sessionId,w=m?.fromUrl?m.target:void 0;if(!a){if(process.stdout.isTTY){Is=!0,await Kw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return}Is=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await _d(b);return}switch(a){case"shim":{Is=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await _d(b);return}case"cat":{let b=Ju(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,A=at(r,"cwd"),T={prompt:S,sessionId:h,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:f};A!==void 0&&(T.cwd=A),w!==void 0&&(T.target=w);let U=Ku(r,"stream-threshold");U!==void 0&&(T.streamThreshold=U);let O=Ku(r,"stream-bytes");O!==void 0&&(T.streamBufferBytes=O),d!==void 0&&await ru(d),Is=!0,await Sy(T);return}case"version":{Is=!0,await My({json:r.json===!0});return}case"init":await Df(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Oh();return}if(S==="start"){await Ph(r);return}if(S==="stop"){await Mh();return}if(S==="restart"){await _h();return}if(S==="log"||S==="logs"){await $h(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
483
- `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=at(r,"columns"),S;if(v!==void 0)try{S=zh(v)}catch(A){process.stderr.write(`${A.message}
484
- `),process.exit(2);return}await Yh({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 hg(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 Vh(s[2]);return}if(b==="remove"){await Gh(s[2]);return}if(b==="collect"){let v=at(r,"max-age-days"),S=at(r,"limit"),A={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
485
- `),process.exit(2);return}A.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
486
- `),process.exit(2);return}A.limit=T}await Qh(A);return}if(b==="export"){let v=at(r,"out"),S=at(r,"tools");await Xh(s[2],v,S);return}if(b==="transcript"){let v=at(r,"out");await Zh(s[2],v);return}if(b==="import"){let v=at(r,"cwd");await eg(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=at(r,"host"),S=at(r,"cwd");await tg(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
487
- `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],A=v[1],T=v.slice(2);if(S===void 0||S==="list"){await wg();return}if(S==="add"){await bg(A,T);return}if(S==="remove"){await vg(A);return}if(S==="start"){await Sg(A);return}if(S==="stop"){await kg(A);return}if(S==="restart"){await Ig(A);return}if(S==="log"||S==="logs"){await xg(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
488
- `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],A=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Cg();return}if(S==="add"){await Ag(A,T);return}if(S==="remove"){await Rg(A);return}if(S==="start"){await Tg(A);return}if(S==="stop"){await Eg(A);return}if(S==="restart"){await Pg(A);return}if(S==="log"||S==="logs"){await Mg(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
489
- `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await Og();return}if(b==="refresh"){await iu();return}if(b==="install"){await Fg(s[2]);return}if(b==="sync"){await Lg(s[2]);return}if(b==="set"){await Ng(s[2],s[3]);return}if(b==="pin"){await Hg(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await Ug(S[1],S.slice(2));return}if(b==="remove"){await jg(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:A,rest:T}=dd(S);await Bg(A,T);return}if(b==="auth"){await oy(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
490
- `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await iu();return}if(b==="pin"){await ou(!0);return}if(b==="unpin"){await ou(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
491
- `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await ay(r);return}process.stderr.write(`Unknown auth password action: ${v}
492
- `),process.exit(2);return}if(b===void 0||b==="list"){await dy();return}if(b==="revoke"){await cy(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
493
- `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await Ry(s[2]);return}if(b==="get"){await xy(s[2]);return}if(b==="set"){await Cy(s[2],s[3]);return}if(b==="unset"){await Ay(s[2]);return}if(b==="path"){Ty();return}process.stderr.write(`Unknown config subcommand: ${b}
494
- `),process.exit(2);return}case"tui":Is=!0,await Kw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return;default:process.stderr.write(`Unknown command: ${a}
495
- `),Yu(),process.exit(2)}}async function Kw(t,e){let n=at(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 ru(e.agentId),Ai(Ri(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Ww(),qw)),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.
496
- `),process.exit(2)),a.drip=!0;let c=Ku(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Ku(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 Yw(t){let e=cf(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
479
+ `)}}async function wA(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await ye()}catch{return{report:t,configLoaded:!1}}let n=await cr(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 Gs()}catch{return{report:t,configLoaded:!0}}let r=await wi(),i={Authorization:`Bearer ${s}`};return t.extensions=await My(`${r}/v1/extensions`,i,"extensions"),t.transformers=await My(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function My(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 bA}from"child_process";import{accessSync as vA,constants as SA,statSync as kA}from"fs";import{delimiter as IA,join as xA}from"path";var CA=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function AA(t){return CA.has(t)}function RA(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function TA(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 EA(t){try{if(!kA(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return vA(t,SA.X_OK),!0}catch{return!1}}function PA(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(IA).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=xA(o,r+a);if(EA(c))return c}}function MA(t,e){let n=bA(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 $y(t){let e=RA(t);if(e===void 0||AA(e))return!1;let n=PA(e);if(n===void 0)return!1;MA(n,TA(t))}wu();var Ps=!1,Jw=!1;function Kw(t){!t||Jw||(Jw=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
481
+ `))}async function p0(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(ro(),Mf));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(Vw(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 F=S??it(T,"agent");if(!F){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
483
+ `),process.exit(2);return}let $=await Gw(Cc(T),{allowPrompt:!1}),H=it(T,"name"),J=it(T,"model");Ps=!0;let B=T["dangerously-skip-permissions"]===!0;Kw(B);let N={agentId:F,agentArgs:x,name:H,model:J,dangerouslySkipPermissions:B};$?.sessionId!==void 0&&(N.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(N.target=$.target),await Nd(N);return}Gu(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&$y(e);let{positional:s,flags:r}=dc(e);if(Vw(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${m0()}
484
+ `);return}if(r.help===!0){Xu();return}let i=Gu(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=it(r,"name"),d=it(r,"agent"),l=it(r,"model"),f=r["dangerously-skip-permissions"]===!0;Kw(f);let u=Cc(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,m=await Gw(u,{allowPrompt:p});m!==void 0&&m.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 h=m?.sessionId,w=m?.fromUrl?m.target:void 0;if(!a){if(process.stdout.isTTY){Ps=!0,await Yw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return}Ps=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await Nd(b);return}switch(a){case"shim":{Ps=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await Nd(b);return}case"cat":{let b=Gu(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=it(r,"cwd"),T={prompt:S,sessionId:h,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:f};x!==void 0&&(T.cwd=x),w!==void 0&&(T.target=w);let F=Qu(r,"stream-threshold");F!==void 0&&(T.streamThreshold=F);let $=Qu(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await du(d),Ps=!0,await ky(T);return}case"version":{Ps=!0,await _y({json:r.json===!0});return}case"init":await Hf(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Fh();return}if(S==="start"){await Mh(r);return}if(S==="stop"){await _h();return}if(S==="restart"){await $h();return}if(S==="log"||S==="logs"){await Oh(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=it(r,"columns"),S;if(v!==void 0)try{S=Jh(v)}catch(x){process.stderr.write(`${x.message}
487
+ `),process.exit(2);return}await Vh({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 yg(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 gg(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 Gh(s[2]);return}if(b==="remove"){await Qh(s[2]);return}if(b==="collect"){let v=it(r,"max-age-days"),S=it(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
488
+ `),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 Xh(x);return}if(b==="export"){let v=it(r,"out"),S=it(r,"tools");await Zh(s[2],v,S);return}if(b==="transcript"){let v=it(r,"out");await eg(s[2],v);return}if(b==="import"){let v=it(r,"cwd");await tg(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=it(r,"host"),S=it(r,"cwd");await ng(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 bg();return}if(S==="add"){await vg(x,T);return}if(S==="remove"){await Sg(x);return}if(S==="start"){await kg(x);return}if(S==="stop"){await Ig(x);return}if(S==="restart"){await xg(x);return}if(S==="log"||S==="logs"){await Cg(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 Ag();return}if(S==="add"){await Rg(x,T);return}if(S==="remove"){await Tg(x);return}if(S==="start"){await Eg(x);return}if(S==="stop"){await Pg(x);return}if(S==="restart"){await Mg(x);return}if(S==="log"||S==="logs"){await _g(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 Fg();return}if(b==="refresh"){await cu();return}if(b==="install"){await Lg(s[2]);return}if(b==="sync"){await Bg(s[2]);return}if(b==="set"){await Dg(s[2],s[3]);return}if(b==="pin"){await Ug(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await jg(S[1],S.slice(2));return}if(b==="remove"){await qg(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=md(S);await Ng(x,T);return}if(b==="auth"){await ay(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 cu();return}if(b==="pin"){await lu(!0);return}if(b==="unpin"){await lu(!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 dy(r);return}process.stderr.write(`Unknown auth password action: ${v}
495
+ `),process.exit(2);return}if(b===void 0||b==="list"){await cy();return}if(b==="revoke"){await ly(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 Ty(s[2]);return}if(b==="get"){await Cy(s[2]);return}if(b==="set"){await Ay(s[2],s[3]);return}if(b==="unset"){await Ry(s[2]);return}if(b==="path"){Ey();return}process.stderr.write(`Unknown config subcommand: ${b}
497
+ `),process.exit(2);return}case"tui":Ps=!0,await Yw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return;default:process.stderr.write(`Unknown command: ${a}
498
+ `),Xu(),process.exit(2)}}async function Yw(t,e){let n=it(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),Li(Bi(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(zw(),Ww)),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=Qu(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Qu(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 Vw(t){let e=uf(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
497
500
 
498
- `),Yu(),process.exit(2))}function Ju(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 Vw(t,e){try{return await Bf(t,e)}catch(n){process.stderr.write(`${n.message}
499
- `),process.exit(1)}}function l0(){try{let t=a0(o0(import.meta.url));return JSON.parse(i0(d0(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Yu(){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(`
500
- `))}async function Gw(){if(!Is)try{let t=await Eo();t&&process.stderr.write(`\u2728 ${Po(t)}
501
- `)}catch{}}c0().then(Gw).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
502
- `),await Gw(),process.exit(1)});
501
+ `),Xu(),process.exit(2))}function Gu(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 Gw(t,e){try{return await Nf(t,e)}catch(n){process.stderr.write(`${n.message}
502
+ `),process.exit(1)}}function m0(){try{let t=u0(l0(import.meta.url));return JSON.parse(c0(f0(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Xu(){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 Qw(){if(!Ps)try{let t=await No();t&&process.stderr.write(`\u2728 ${Do(t)}
504
+ `)}catch{}}p0().then(Qw).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
505
+ `),await Qw(),process.exit(1)});