@hydra-acp/cli 0.1.109 → 0.1.111

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 (3) hide show
  1. package/dist/cli.js +279 -279
  2. package/dist/index.js +67 -67
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- var qv=Object.defineProperty;var V=(n,e)=>()=>(n&&(e=n(n=0)),e);var Pl=(n,e)=>{for(var t in e)qv(n,t,{get:e[t],enumerable:!0})};import*as ke from"path";import*as _l from"os";function at(n){let e=_l.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Vv(){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 Ae(){let n=process.env[Yv];if(n&&n.length>0)return ke.resolve(n);let e=Vv();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 ke.join(_l.homedir(),".hydra-acp")}var Yv,L,ve=V(()=>{"use strict";Yv="HYDRA_ACP_HOME";L={home:Ae,config:()=>ke.join(Ae(),"config.json"),authToken:()=>ke.join(Ae(),"auth-token"),remotes:()=>ke.join(Ae(),"remotes.json"),pidFile:()=>ke.join(Ae(),"daemon.pid"),logFile:()=>ke.join(Ae(),"daemon.log"),currentLogFile:()=>ke.join(Ae(),"current.log"),registryCache:()=>ke.join(Ae(),"registry.json"),agentsDir:()=>ke.join(Ae(),"agents"),agentLogFile:n=>ke.join(Ae(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>ke.join(Ae(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>ke.join(Ae(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>ke.join(Ae(),"sessions"),sessionDir:n=>ke.join(Ae(),"sessions",n),sessionFile:n=>ke.join(Ae(),"sessions",n,"meta.json"),historyFile:n=>ke.join(Ae(),"sessions",n,"history.jsonl"),toolsDir:n=>ke.join(Ae(),"sessions",n,"tools"),toolBlobFile:(n,e)=>ke.join(Ae(),"sessions",n,"tools",e),queueFile:n=>ke.join(Ae(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>ke.join(Ae(),"sessions",".tombstones"),tombstoneAgentDir:n=>ke.join(Ae(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>ke.join(Ae(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>ke.join(Ae(),"extensions"),extensionLogDir:n=>ke.join(Ae(),"extensions",n),extensionLogFile:n=>ke.join(Ae(),"extensions",n,"current.log"),extensionPidFile:n=>ke.join(Ae(),"extensions",n,"extension.pid"),transformersDir:()=>ke.join(Ae(),"transformers"),transformerLogDir:n=>ke.join(Ae(),"transformers",n),transformerLogFile:n=>ke.join(Ae(),"transformers",n,"current.log"),transformerPidFile:n=>ke.join(Ae(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>ke.join(Ae(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>ke.join(Ae(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>ke.join(Ae(),"prompt-history"),tuiLogFile:()=>ke.join(Ae(),"tui.log"),shimWireLogFile:()=>ke.join(Ae(),"shim-wire.log")}});import*as Ri from"fs/promises";function Ti(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Ei(){try{let e=(await Ri.readFile(L.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Er(){let n=await Ei();if(!n)throw new Error(`No service token found at ${L.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Pi(n){await Ri.mkdir(L.home(),{recursive:!0}),await Ri.writeFile(L.authToken(),n+`
3
- `,{encoding:"utf8",mode:384})}async function Ko(){let n=await Ei();if(n)return n;let e=Ti();return await Pi(e),process.stderr.write(`hydra-acp: initialized ${L.authToken()} with a fresh service token.
4
- `),e}var ks=V(()=>{"use strict";ve()});import*as Mt from"fs/promises";import*as Dp from"fs";import*as _n from"path";import{randomBytes as Qv}from"crypto";async function nn(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await Gv(n,r,t)}async function Gv(n,e,t={}){let s=await Xv(n),r=Zv(s);await Mt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${eS()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Mt.writeFile(i,e,o),await Mt.rename(i,s)}catch(o){throw await Mt.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{Dp.chmodSync(s,t.mode)}catch{}}async function Xv(n){let e;try{e=await Mt.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Mt.readlink(n),s=_n.isAbsolute(t)?t:_n.resolve(_n.dirname(n),t);try{let r=await Mt.realpath(_n.dirname(s));return _n.join(r,_n.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(n){let e;try{e=await Mt.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Zv(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function eS(){return Qv(4).toString("hex")}var Pr=V(()=>{"use strict"});import*as Gs from"fs/promises";import{homedir as $l}from"os";import{z as q}from"zod";function jp(n){return n.tui.inAppSelection??n.tui.mouse}function qp(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Wp(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function ld(){return await lS(),await yn(L.config())??{}}async function lS(){let n;try{n=await Gs.lstat(L.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Gs.stat(L.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Gs.readlink(L.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${L.config()} is a broken symlink (-> ${t}); 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 ud(){let n=await ld(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Gs.access(L.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${L.authToken()} and ${L.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Pi(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await nn(L.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${L.config()} to ${L.authToken()}.
6
- `)}async function xe(){return await ud(),Fl.parse(await ld())}async function Is(n){await ud();let e=await ld();n(e),Fl.parse(e),await nn(L.config(),e,{mode:384})}async function Jo(n,e){await Is(t=>{let s=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};s[n]=e,t.tui=s})}async function Mi(n){await Is(e=>{e.defaultAgent=n})}async function zp(n,e){await Is(t=>{let s=t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{};s[n]=e,t.defaultModels=s})}async function Kp(n,e){await Is(t=>{let s=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{};e===void 0?delete s[n]:s[n]={packageSpec:e},t.agentOverrides=s})}async function Ol(n,e){await Is(t=>{let s=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete s[n]:s[n]=e,t.agents=s})}async function Jp(n){await Is(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function Yp(){let n=await ld();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function et(n){return n==="~"||n==="$HOME"?$l():n.startsWith("~/")?$l()+n.slice(1):n.startsWith("$HOME/")?$l()+n.slice(5):n}var Up,tS,$n,nS,sS,rS,iS,oS,aS,Hp,dS,cS,Fl,Qe=V(()=>{"use strict";ve();ks();Pr();Up="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",tS=q.object({cert:q.string(),key:q.string()}),$n=55514,nS=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default($n),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:tS.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),sS=q.object({url:q.string().url().default(Up),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),rS=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),iS=q.object({packageSpec:q.string().optional()}),oS=q.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),aS=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:q.record(oS,q.object({command:q.union([q.string(),q.array(q.string())])})).default({})}),Hp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),dS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),cS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Fl=q.object({daemon:nS.default({}),registry:sS.default({url:Up,ttlHours:24,pinned:!1}),agents:q.record(q.string(),rS).default({}),agentOverrides:q.record(q.string(),iS).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(Hp,dS).default({}),transformers:q.record(Hp,cS).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:aS.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 Mr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Ll(n){return{httpScheme:"https",wsScheme:"wss"}}function Bl(n){if(typeof n!="string"||n.length===0)throw new Error("expected a hydra:// URL");if(!n.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${fd(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${fd(n)}`);let t=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(t){let d=Number(t[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${t[1]}`)}let s=uS(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${fd(n)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${fd(n)}`);let i=Mr(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=$n;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function Vp(n){let e=n.port!==void 0&&n.port!==$n?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function uS(n){try{return new URL(n)}catch{return null}}function fd(n){return n.length>80?`${n.slice(0,77)}...`:n}var Yo=V(()=>{"use strict";Qe()});function _r(n,e){return`${n}:${e}`}function Qp(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function fS(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}async function pS(){let n=await yn(L.remotes());return n===void 0?{version:1,entries:{}}:hS(n)}function hS(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(t)){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 Nl(n){await nn(L.remotes(),n,{mode:384})}var pd,Dl=V(()=>{"use strict";ve();Pr();pd=class n{data;constructor(e){this.data=e}static async load(){let e=await pS(),t=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Qp(a,t)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Nl(i),new n(i)}get(e,t){let s=this.data.entries[_r(e,t)];if(s&&!Qp(s,Date.now()))return s}async set(e,t,s){this.data.entries[_r(e,t)]=s,await Nl(this.data)}async delete(e,t){let s=_r(e,t);return s in this.data.entries?(delete this.data.entries[s],await Nl(this.data),!0):!1}list(){let e=[];for(let[t,s]of Object.entries(this.data.entries)){let r=fS(t);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function _i(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{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(),t(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),t(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):mS()}function mS(){return new Promise((n,e)=>{let t="";process.stdin.setEncoding("utf8");let s=i=>{t+=i;let o=t.indexOf(`
8
- `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),n(t.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 Hl=V(()=>{"use strict"});import*as Gp from"path";function Vn(){let n=process.argv[1];if(!n)return"hydra-acp";let e=Gp.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Vo=V(()=>{"use strict"});import*as hd from"fs/promises";async function xs(){try{let n=await hd.readFile(L.pidFile(),"utf8"),e=JSON.parse(n);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(n){if(n.code==="ENOENT")return;throw n}}async function Xp(n){await hd.writeFile(L.pidFile(),JSON.stringify(n)+`
9
- `,{encoding:"utf8",mode:384})}function Fn(n){try{return process.kill(n,0),!0}catch{return!1}}var $i=V(()=>{"use strict";ve()});var rh={};Pl(rh,{_resetForTests:()=>xS,clearPin:()=>kS,fetchPeerFingerprint:()=>Wl,formatFingerprint:()=>md,getPin:()=>jl,installGlobalTlsTrust:()=>Kl,loadPinsFromStore:()=>ql,setPin:()=>Qo,sha256Hex:()=>zl,wsTlsOptions:()=>Go});import{createHash as gS}from"crypto";import*as Zp from"tls";import{Agent as yS,Dispatcher as wS,buildConnector as bS,getGlobalDispatcher as vS,setGlobalDispatcher as SS}from"undici";function Qo(n,e,t){$r.set(_r(n,e),eh(t))}function kS(n,e){$r.delete(_r(n,e))}function jl(n,e){return $r.get(_r(n,e))}function ql(n){$r.clear();for(let e of n.list())e.entry.pinnedFingerprint&&Qo(e.host,e.port,e.entry.pinnedFingerprint)}async function Wl(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=Zp.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${n}:${e} did not present a TLS certificate`));return}c(null,zl(l.raw))}),o.once("error",l=>c(l))})}function zl(n){return gS("sha256").update(n).digest("hex")}function md(n){let e=eh(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function eh(n){return n.replace(/:/g,"").toLowerCase()}function Kl(){if(Ul)return;Ul=!0;let n=vS(),e=new yS({connect:bS({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>nh(s,r)})}),t=new wS;t.dispatch=(s,r)=>{let i=IS(s.origin);return(i&&th(i)?e:n).dispatch(s,r)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(s=>Promise.all([e.destroy(s??null),n.destroy(s??null)]).then(()=>{})),SS(t)}function IS(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function th(n){for(let e of $r.keys())if(sh(e)?.host===n)return!0;return!1}function nh(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=zl(e.raw);for(let[s,r]of $r.entries()){let i=sh(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${md(t)})`)}function sh(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}function Go(n){return th(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>nh(e,t)}:{autoSelectFamily:!0}}function xS(){$r.clear(),Ul=!1}var $r,Ul,Xo=V(()=>{"use strict";Dl();$r=new Map,Ul=!1});import*as dh from"os";async function Dt(n){let e=await Ko(),t=await xs();if(t&&Fn(t.pid))return{baseUrl:`http://127.0.0.1:${t.loopbackPort}`,wsUrl:`ws://127.0.0.1:${t.loopbackPort}/acp`,token:e,display:`${t.host}:${t.port}`,isLocal:!0};let s=n.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=n.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Mr(r)}}function ih(n,e){let{httpScheme:t,wsScheme:s}=Ll(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${s}://${n.host}:${n.port}/acp`,token:e,display:lh(n),isLocal:n.isLoopback}}async function ch(n,e={}){let t=e.fetchImpl??fetch,s=e.promptImpl??_i,r=e.confirmImpl??TS,i=e.tlsHandshakeImpl??AS,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&o){let b=await Ei();if(b)return RS(n,b)}let c=e.store??await pd.load();ql(c),Kl();let d=c.get(n.host,n.port);if(d)return d.pinnedFingerprint&&Qo(n.host,n.port,d.pinnedFingerprint),ih(n,d.token);if(!a)throw new Jl(n.host,n.port);let l=lh(n),{httpScheme:u}=Ll(n.host),f;if(u==="https"&&jl(n.host,n.port)===void 0){let b=await i(n.host,n.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
- subject: ${b.subject??"(unknown)"}
11
- issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${md(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Qo(n.host,n.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${n.host}:${n.port}`,m=await t(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:ah()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(n.host,n.port,{token:y.session_token,expiresAt:y.expires_at,label:ah(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),ih(n,y.session_token)}async function AS(n,e){let t=await CS(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await Wl(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function CS(n,e,t=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:n,port:e,servername:n,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);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?oh(p.subject):void 0,issuer:p?.issuer?oh(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function oh(n){if(!n)return"";let e=[];for(let[t,s]of Object.entries(n)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${t}=${r}`)}return e.join(", ")}async function RS(n,e){let t=await xs(),r=t&&Fn(t.pid)?t.loopbackPort:n.port,i=n.port===$n?n.host:`${n.host}:${n.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 TS(n){return process.stdout.write(n),new Promise(e=>{let t="",s=r=>{t+=r.toString("utf8");let i=t.indexOf(`
14
- `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=t.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function ah(){try{let n=dh.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function lh(n){return n.port===$n?n.host:`${n.host}:${n.port}`}var Jl,Fr=V(()=>{"use strict";Qe();ks();Yo();Dl();Hl();Vo();$i();Xo();Yo();Jl=class extends Error{host;port;constructor(e,t){let s=t===$n?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${Vn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as ES,renameSync as PS,statSync as MS}from"fs";function ph(n){fh=n}function oe(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?L.tuiLogFile():e;if(t.length!==0)try{_S(t);let s=JSON.stringify({t:new Date().toISOString(),...n});ES(t,`${s}
15
- `)}catch{}}function _S(n){try{if(MS(n).size<fh)return;PS(n,`${n}.0`)}catch{}}var fh,Or=V(()=>{"use strict";ve();fh=5*1024*1024});import*as Ch from"fs";import*as Ht from"fs/promises";import*as Xs from"path";import{spawn as Rh}from"child_process";import{Readable as NS}from"stream";function wn(){let n=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(!(!n||!e))return`${n}-${e}`}function Zl(n,e=wn()){if(e)return n[e]}function eu(n){Fi=n??(e=>process.stderr.write(e+`
16
- `))}async function Th(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${wn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=wn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentInstallDir(n.agentId,e,n.version),s=Xs.resolve(t,n.target.cmd);if(await Xl(s))return s;if(await DS({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await Xl(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Ht.chmod(s,493).catch(()=>{}),s}async function DS(n){await Ht.mkdir(Xs.dirname(n.installDir),{recursive:!0});let e=await Ht.mkdtemp(`${n.installDir}.partial-`);try{Fi(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await HS({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Fi(`hydra-acp: extracting ${n.agentId}`),Oi(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await jS(t,e),await Ht.unlink(t).catch(()=>{});try{await Ht.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Xl(n.installDir)){await Ht.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Oi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Fi(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Oi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Ht.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Oi(n,e){if(n)try{n(e)}catch{}}async function HS(n){let e=US(n.url),t=Xs.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Ch.createWriteStream(t),o=NS.fromWeb(s.body);Oi(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,Oi(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Fi(Ah(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),Fi(Ah(n.agentId,a,r,!0)),Oi(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Ah(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function US(n){let e=new URL(n);return Xs.posix.basename(e.pathname)||"archive"}async function jS(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await Gl("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await qS("unzip")){await Gl("unzip",["-q",n,"-d",e]);return}await Gl("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function Gl(n,e){return new Promise((t,s)=>{let r=Rh(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function qS(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Rh(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Xl(n){try{return await Ht.access(n),!0}catch{return!1}}var Fi,Li=V(()=>{"use strict";ve();Fi=n=>{process.stderr.write(n+`
17
- `)}});var j,Sd=V(()=>{"use strict";j={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 Be}from"zod";var Lh,ik,Bh,Nh,Dh,ou=V(()=>{"use strict";Lh=Be.object({protocolVersion:Be.number().optional(),clientCapabilities:Be.record(Be.unknown()).optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional()}),ik=Be.enum(["full","pending_only","none","after_message"]),Bh=Be.object({cwd:Be.string(),mcpServers:Be.array(Be.unknown()).optional(),_meta:Be.record(Be.unknown()).optional()}),Nh=Be.object({upstreamSessionId:Be.string(),agentId:Be.string(),cwd:Be.string(),title:Be.string().optional(),agentArgs:Be.array(Be.string()).optional()}),Dh=Be.object({sessionId:Be.string(),historyPolicy:ik.default("full"),afterMessageId:Be.string().optional(),clientId:Be.string().optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional(),_meta:Be.record(Be.unknown()).optional()})});import{z as pe}from"zod";function kd(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function jh(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:Zo(n._meta,kd(n))};return n.title!==void 0&&(e.title=n.title),e}var Hh,Uh,au,qP,ok,WP,du=V(()=>{"use strict";Id();Hh=pe.object({sessionId:pe.string()}),Uh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),au=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),qP=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:au.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),ok=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),WP=pe.object({sessions:pe.array(ok),nextCursor:pe.string().optional()})});function ak(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function rn(n){if(!n)return{};let e=n[$t];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=Nh.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=au.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.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(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.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(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.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(t.availableModes)){let r=[];for(let i of t.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(t.availableModels)){let r=[];for(let i of t.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((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=ak(t.env);r!==void 0&&(s.env=r)}return s}function Zo(n,e){return{...n??{},[$t]:e}}var $t,Id=V(()=>{"use strict";ou();du();$t="hydra-acp"});import{z as te}from"zod";var qh,xd,Wh,QP,GP,XP,zh,ZP,Kh,eM,Jh,tM,nM,Yh=V(()=>{"use strict";qh=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),xd=te.object({sessionId:te.string()}),Wh=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),QP=te.object({sessionId:te.string(),messageId:te.string(),originator:Wh,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),GP=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),XP=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),zh=te.object({sessionId:te.string(),messageId:te.string()}),ZP=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Kh=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),eM=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Jh=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),tM=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),nM=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:Wh,amendedAt:te.number()})});import{z as Zs}from"zod";var Vh,Ad,Di,Qh=V(()=>{"use strict";Vh=Zs.object({agentId:Zs.string(),version:Zs.string(),source:Zs.enum(["binary","npm"]),phase:Zs.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Zs.number().optional(),totalBytes:Zs.number().optional(),packageSpec:Zs.string().optional()}),Ad="hydra-acp/agents/install_progress",Di={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Ft=V(()=>{"use strict";Sd();ou();Id();du();Yh();Qh()});import{nanoid as dk}from"nanoid";var cu,Kt,Br=V(()=>{"use strict";Ft();cu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Kt=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}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,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(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,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new cu;let s=dk(),r={jsonrpc:"2.0",id:s,method:e,params:t},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,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};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 t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:j.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(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??j.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.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>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){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,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}}});async function Hi(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;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:t,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 Ui(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;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:t,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 lu=V(()=>{"use strict"});import*as Zh from"fs/promises";function vk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var pk,hk,ji,mk,gk,yk,wk,bk,Xh,Td,em=V(()=>{"use strict";pk=64*1024*1024,hk=1*1024*1024,ji=64*1024,mk=6e4,gk=100,yk=1e3,wk=64*1024,bk=256*1024,Xh=20;Td=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??pk,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(hk,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,t){let s=Math.max(0,Math.min(t,ji));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,ji)),s=this.oldestAvailable,r=this.writeCursor-t,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 t=Math.max(0,Math.min(e,ji)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,mk));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 t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),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(vk(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??gk,yk)),f=Math.max(1,Math.min(e.maxBytes??wk,bk)),p=Math.max(0,Math.min(e.contextBefore??0,Xh)),h=Math.max(0,Math.min(e.contextAfter??0,Xh)),m=[],y=[],b=[],v=0,S=!1,x=0,T=0,E=(M,D)=>{for(let X of b)X.remaining>0&&(X.match.after===void 0&&(X.match.after=[]),X.match.after.push({cursor:M,line:D}),X.remaining--,v+=D.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(D)!==l&&m.length<u){let X={cursor:M,line:D};if(p>0&&y.length>0){X.before=y.slice();for(let Z of X.before)v+=Z.line.length}v+=D.length,m.push(X),h>0&&b.push({match:X,remaining:h})}if(p>0)for(y.push({cursor:M,line:D});y.length>p;)y.shift();let O=m.length>=u&&b.length===0,K=v>=f;return O||K};for(let M=0;M<o.length;M++){if(o[M]!==10)continue;let D=o.subarray(x,M).toString("utf8"),B=r+x;if(x=M+1,T=x,E(B,D)){S=!0;break}}if(!S&&x<o.length&&this.closed){let M=o.subarray(x).toString("utf8"),D=r+x;E(D,M)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),N={matches:m,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(N.gap=i),this.closed&&$>=this.writeCursor&&(N.eof=!0),N}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&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 t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===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(()=>Zh.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var qi,AM,tm=V(()=>{"use strict";qi=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],AM=new Map(qi.map(n=>[n.verb,n]))});function nm(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Wi(n,e){return uu(n,e.map(t=>t.modelId))}function uu(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=nm(n),s=e.filter(i=>nm(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.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:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}var Ed=V(()=>{"use strict"});function sm(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=fu(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=t.get(l);u?u.push(...d.content):t.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=fu(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?kk(r,i.outIndex,Sk(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&t.has(u)?Ik(c,t.get(u)??[]):c;u!==void 0&&s.has(u)&&!xk(f)&&(f=Ak(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function fu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Sk(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function kk(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Ik(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function xk(n){let t=fu(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Ak(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var rm=V(()=>{"use strict"});function zi(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){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=hu(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=mu(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(pu(c))):d==="turn_complete"&&i()}return i(),Pk(s.join(`
18
- `),t)}function pu(n){let e=Rk(n),t=Tk(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Rk(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Tk(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Ck){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Ek(r,200)}`)}return t}function hu(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function mu(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Ek(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Pk(n,e){if(n.length<=e)return n;let t=n.split(`
19
- `);for(;t.length>0;){let s=im+t.join(`
20
- `);if(s.length<=e)return s;t.shift()}return im}var im,Ck,Pd=V(()=>{"use strict";im=`[older history truncated]
21
- `,Ck=["file_path","filePath","path","command","pattern","query"]});function gu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??om}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let o=ea("Open threads",t.open_threads);o.length>0&&e.push(o);let a=ea("Decisions",t.decisions);a.length>0&&e.push(a);let c=ea("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let d=ea("Unresolved errors",t.unresolved_errors);d.length>0&&e.push(d);let l=ea("Tool state",t.tool_state);l.length>0&&e.push(l);let u=am(t.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=am(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??om}`);let{closedText:s,openText:r,keptCount:i}=Mk(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
22
- `)}function ea(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
23
- `)}`}function am(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Mk(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=_k(n),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=t).length,u=Math.max(l,s),f=Math.min(u,e,r.length);o=f,a=f>0?r.slice(-f):[]}let c=a.length>0?dm(a):"",d=i?dm([i]):"";return{closedText:c,openText:d,keptCount:o}}function dm(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
24
- `)}function _k(n){let e=[],t=null;for(let r=0;r<n.length;r++){let i=n[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let c=a.sessionUpdate;if(c==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:hu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&t!==null){let d=mu(a.content);d.length>0&&(t.agent+=d)}else c==="tool_call"&&t!==null?t.tools.push(pu(a)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}var om,cm=V(()=>{"use strict";Pd();om="(untitled)"});import*as Gn from"fs/promises";async function ta(n,e){let t=L.queueFile(n);if(e.length===0){await Gn.unlink(t).catch(()=>{});return}await Gn.mkdir(L.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
2
+ var Jv=Object.defineProperty;var V=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ml=(n,e)=>{for(var t in e)Jv(n,t,{get:e[t],enumerable:!0})};import*as ke from"path";import*as $l from"os";function at(n){let e=$l.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Zv(){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 Ae(){let n=process.env[Xv];if(n&&n.length>0)return ke.resolve(n);let e=Zv();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 ke.join($l.homedir(),".hydra-acp")}var Xv,L,ve=V(()=>{"use strict";Xv="HYDRA_ACP_HOME";L={home:Ae,config:()=>ke.join(Ae(),"config.json"),authToken:()=>ke.join(Ae(),"auth-token"),remotes:()=>ke.join(Ae(),"remotes.json"),pidFile:()=>ke.join(Ae(),"daemon.pid"),logFile:()=>ke.join(Ae(),"daemon.log"),currentLogFile:()=>ke.join(Ae(),"current.log"),registryCache:()=>ke.join(Ae(),"registry.json"),agentsDir:()=>ke.join(Ae(),"agents"),agentLogFile:n=>ke.join(Ae(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>ke.join(Ae(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>ke.join(Ae(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>ke.join(Ae(),"sessions"),sessionDir:n=>ke.join(Ae(),"sessions",n),sessionFile:n=>ke.join(Ae(),"sessions",n,"meta.json"),historyFile:n=>ke.join(Ae(),"sessions",n,"history.jsonl"),toolsDir:n=>ke.join(Ae(),"sessions",n,"tools"),toolBlobFile:(n,e)=>ke.join(Ae(),"sessions",n,"tools",e),queueFile:n=>ke.join(Ae(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>ke.join(Ae(),"sessions",".tombstones"),tombstoneAgentDir:n=>ke.join(Ae(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>ke.join(Ae(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>ke.join(Ae(),"extensions"),extensionLogDir:n=>ke.join(Ae(),"extensions",n),extensionLogFile:n=>ke.join(Ae(),"extensions",n,"current.log"),extensionPidFile:n=>ke.join(Ae(),"extensions",n,"extension.pid"),transformersDir:()=>ke.join(Ae(),"transformers"),transformerLogDir:n=>ke.join(Ae(),"transformers",n),transformerLogFile:n=>ke.join(Ae(),"transformers",n,"current.log"),transformerPidFile:n=>ke.join(Ae(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>ke.join(Ae(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>ke.join(Ae(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>ke.join(Ae(),"prompt-history"),tuiLogFile:()=>ke.join(Ae(),"tui.log"),shimWireLogFile:()=>ke.join(Ae(),"shim-wire.log")}});import*as Ei from"fs/promises";function Pi(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Mi(){try{let e=(await Ei.readFile(L.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function _r(){let n=await Mi();if(!n)throw new Error(`No service token found at ${L.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function _i(n){await Ei.mkdir(L.home(),{recursive:!0}),await Ei.writeFile(L.authToken(),n+`
3
+ `,{encoding:"utf8",mode:384})}async function Jo(){let n=await Mi();if(n)return n;let e=Pi();return await _i(e),process.stderr.write(`hydra-acp: initialized ${L.authToken()} with a fresh service token.
4
+ `),e}var xs=V(()=>{"use strict";ve()});import*as Mt from"fs/promises";import*as jp from"fs";import*as _n from"path";import{randomBytes as eS}from"crypto";async function nn(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await tS(n,r,t)}async function tS(n,e,t={}){let s=await nS(n),r=sS(s);await Mt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${rS()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await Mt.writeFile(i,e,o),await Mt.rename(i,s)}catch(o){throw await Mt.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{jp.chmodSync(s,t.mode)}catch{}}async function nS(n){let e;try{e=await Mt.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Mt.readlink(n),s=_n.isAbsolute(t)?t:_n.resolve(_n.dirname(n),t);try{let r=await Mt.realpath(_n.dirname(s));return _n.join(r,_n.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function yn(n){let e;try{e=await Mt.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function sS(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function rS(){return eS(4).toString("hex")}var $r=V(()=>{"use strict"});import*as Zs from"fs/promises";import{homedir as Fl}from"os";import{z as q}from"zod";function zp(n){return n.tui.inAppSelection??n.tui.mouse}function Kp(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Jp(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function ud(){return await hS(),await yn(L.config())??{}}async function hS(){let n;try{n=await Zs.lstat(L.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Zs.stat(L.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Zs.readlink(L.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${L.config()} is a broken symlink (-> ${t}); 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 fd(){let n=await ud(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Zs.access(L.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${L.authToken()} and ${L.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await _i(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await nn(L.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${L.config()} to ${L.authToken()}.
6
+ `)}async function xe(){return await fd(),Ol.parse(await ud())}async function As(n){await fd();let e=await ud();n(e),Ol.parse(e),await nn(L.config(),e,{mode:384})}async function Yo(n,e){await As(t=>{let s=t.tui&&typeof t.tui=="object"&&!Array.isArray(t.tui)?t.tui:{};s[n]=e,t.tui=s})}async function $i(n){await As(e=>{e.defaultAgent=n})}async function Yp(n,e){await As(t=>{let s=t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{};s[n]=e,t.defaultModels=s})}async function Vp(n,e){await As(t=>{let s=t.agentOverrides&&typeof t.agentOverrides=="object"?t.agentOverrides:{};e===void 0?delete s[n]:s[n]={packageSpec:e},t.agentOverrides=s})}async function Ll(n,e){await As(t=>{let s=t.agents&&typeof t.agents=="object"?t.agents:{};e===void 0?delete s[n]:s[n]=e,t.agents=s})}async function Qp(n){await As(e=>{let t=e.registry&&typeof e.registry=="object"?e.registry:{};t.pinned=n,e.registry=t})}async function Gp(){let n=await ud();return typeof n.defaultAgent=="string"&&n.defaultAgent.length>0}function et(n){return n==="~"||n==="$HOME"?Fl():n.startsWith("~/")?Fl()+n.slice(1):n.startsWith("$HOME/")?Fl()+n.slice(5):n}var Wp,iS,$n,oS,aS,dS,cS,lS,uS,qp,fS,pS,Ol,Qe=V(()=>{"use strict";ve();xs();$r();Wp="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",iS=q.object({cert:q.string(),key:q.string()}),$n=55514,oS=q.object({host:q.string().default("127.0.0.1"),port:q.number().int().positive().default($n),logLevel:q.enum(["debug","info","warn","error"]).default("info"),tls:iS.optional(),sessionIdleTimeoutSeconds:q.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:q.number().int().positive().default(1e4),agentStderrTailBytes:q.number().int().positive().default(4096),publicHost:q.string().optional(),agentSyncIntervalMinutes:q.number().nonnegative().default(60),sessionGcIntervalMinutes:q.number().nonnegative().default(60),sessionGcMaxAgeDays:q.number().positive().default(2)}),aS=q.object({url:q.string().url().default(Wp),ttlHours:q.number().positive().default(24),pinned:q.boolean().default(!1)}),dS=q.object({name:q.string().optional(),description:q.string().optional(),command:q.string().optional(),args:q.array(q.string()).optional(),env:q.record(q.string()).optional()}),cS=q.object({packageSpec:q.string().optional()}),lS=q.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),uS=q.object({repaintThrottleMs:q.number().int().nonnegative().default(1e3),maxScrollbackLines:q.number().int().positive().default(1e4),mouse:q.boolean().default(!0),inAppSelection:q.boolean().optional(),selectionClipboard:q.enum(["primary","clipboard","both"]).default("both"),openFileCommand:q.union([q.string(),q.array(q.string())]).optional(),logMaxBytes:q.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:q.number().int().positive().default(32),progressIndicator:q.boolean().default(!0),defaultEnterAction:q.enum(["enqueue","amend"]).default("amend"),showThoughts:q.boolean().default(!0),ambiguousWidth:q.enum(["auto","narrow","wide"]).default("auto"),toolContent:q.enum(["inline","references"]).default("references"),diffContextLines:q.number().int().min(0).default(3),promptHistoryMaxEntries:q.number().int().positive().default(2e3),maxToolItems:q.number().int().nonnegative().default(5),maxPlanItems:q.number().int().nonnegative().default(5),showFileUpdates:q.enum(["none","edit","diff"]).default("edit"),sessionColumns:q.array(q.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:q.record(lS,q.object({command:q.union([q.string(),q.array(q.string())])})).default({})}),qp=q.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),fS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),pS=q.object({command:q.array(q.string()).default([]),args:q.array(q.string()).default([]),env:q.record(q.string()).default({}),enabled:q.boolean().default(!0)}),Ol=q.object({daemon:oS.default({}),registry:aS.default({url:Wp,ttlHours:24,pinned:!1}),agents:q.record(q.string(),dS).default({}),agentOverrides:q.record(q.string(),cS).default({}),defaultAgent:q.string().default("opencode"),defaultModels:q.record(q.string(),q.string()).default({}),synopsisAgent:q.string().optional(),synopsisModel:q.string().optional(),compaction:q.object({agent:q.string().optional(),model:q.string().optional(),tailK:q.number().int().nonnegative().default(20),maxIterations:q.number().int().positive().default(3),contextFraction:q.number().min(0).max(1).default(.5),hardCeilingFraction:q.number().min(0).max(1).default(.85),absoluteFallback:q.number().int().positive().default(12e4),idleBeforePromptMs:q.number().int().nonnegative().default(3e5),modelContextWindows:q.record(q.string(),q.number().int().positive()).default({})}).default({}),defaultCwd:q.string().default("~"),compressToolContent:q.boolean().default(!0),sessionListColdLimit:q.number().int().nonnegative().default(20),extensions:q.record(qp,fS).default({}),transformers:q.record(qp,pS).default({}),defaultTransformers:q.array(q.string()).default([]),npmRegistry:q.string().url().optional(),tui:uS.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 Fr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Bl(n){return{httpScheme:"https",wsScheme:"wss"}}function Nl(n){if(typeof n!="string"||n.length===0)throw new Error("expected a hydra:// URL");if(!n.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${pd(n)}`);let e=n.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${pd(n)}`);let t=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(t){let d=Number(t[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${t[1]}`)}let s=mS(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${pd(n)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${pd(n)}`);let i=Fr(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=$n;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function Xp(n){let e=n.port!==void 0&&n.port!==$n?`:${n.port}`:"",t=n.sessionId?`/${n.sessionId}`:"/";return`hydra://${n.host}${e}${t}`}function mS(n){try{return new URL(n)}catch{return null}}function pd(n){return n.length>80?`${n.slice(0,77)}...`:n}var Vo=V(()=>{"use strict";Qe()});function Or(n,e){return`${n}:${e}`}function Zp(n,e){let t=Date.parse(n.expiresAt);return Number.isFinite(t)?t<=e:!0}function gS(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}async function yS(){let n=await yn(L.remotes());return n===void 0?{version:1,entries:{}}:wS(n)}function wS(n){if(!n||typeof n!="object")return{version:1,entries:{}};let e=n,t=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(t)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function Dl(n){await nn(L.remotes(),n,{mode:384})}var hd,Hl=V(()=>{"use strict";ve();$r();hd=class n{data;constructor(e){this.data=e}static async load(){let e=await yS(),t=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Zp(a,t)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Dl(i),new n(i)}get(e,t){let s=this.data.entries[Or(e,t)];if(s&&!Zp(s,Date.now()))return s}async set(e,t,s){this.data.entries[Or(e,t)]=s,await Dl(this.data)}async delete(e,t){let s=Or(e,t);return s in this.data.entries?(delete this.data.entries[s],await Dl(this.data),!0):!1}list(){let e=[];for(let[t,s]of Object.entries(this.data.entries)){let r=gS(t);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Fi(n){return process.stdout.write(n),process.stdin.isTTY?new Promise((e,t)=>{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(),t(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),t(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):bS()}function bS(){return new Promise((n,e)=>{let t="";process.stdin.setEncoding("utf8");let s=i=>{t+=i;let o=t.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),n(t.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 Ul=V(()=>{"use strict"});import*as eh from"path";function Qn(){let n=process.argv[1];if(!n)return"hydra-acp";let e=eh.basename(n);return e==="cli.js"||e==="cli"?"hydra-acp":e}var Qo=V(()=>{"use strict"});import*as md from"fs/promises";async function Cs(){try{let n=await md.readFile(L.pidFile(),"utf8"),e=JSON.parse(n);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(n){if(n.code==="ENOENT")return;throw n}}async function th(n){await md.writeFile(L.pidFile(),JSON.stringify(n)+`
9
+ `,{encoding:"utf8",mode:384})}function Fn(n){try{return process.kill(n,0),!0}catch{return!1}}var Oi=V(()=>{"use strict";ve()});var ah={};Ml(ah,{_resetForTests:()=>TS,clearPin:()=>CS,fetchPeerFingerprint:()=>zl,formatFingerprint:()=>gd,getPin:()=>ql,installGlobalTlsTrust:()=>Jl,loadPinsFromStore:()=>Wl,setPin:()=>Go,sha256Hex:()=>Kl,wsTlsOptions:()=>Xo});import{createHash as vS}from"crypto";import*as nh from"tls";import{Agent as SS,Dispatcher as kS,buildConnector as IS,getGlobalDispatcher as xS,setGlobalDispatcher as AS}from"undici";function Go(n,e,t){Lr.set(Or(n,e),sh(t))}function CS(n,e){Lr.delete(Or(n,e))}function ql(n,e){return Lr.get(Or(n,e))}function Wl(n){Lr.clear();for(let e of n.list())e.entry.pinnedFingerprint&&Go(e.host,e.port,e.entry.pinnedFingerprint)}async function zl(n,e,t={}){let s=t.timeoutMs??1e4;return new Promise((r,i)=>{let o=nh.connect({host:n,port:e,servername:n,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${n}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${n}:${e} did not present a TLS certificate`));return}c(null,Kl(l.raw))}),o.once("error",l=>c(l))})}function Kl(n){return vS("sha256").update(n).digest("hex")}function gd(n){let e=sh(n),t=e.match(/.{2}/g);return t?t.join(":"):e}function sh(n){return n.replace(/:/g,"").toLowerCase()}function Jl(){if(jl)return;jl=!0;let n=xS(),e=new SS({connect:IS({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>ih(s,r)})}),t=new kS;t.dispatch=(s,r)=>{let i=RS(s.origin);return(i&&rh(i)?e:n).dispatch(s,r)},t.close=(()=>Promise.all([e.close(),n.close()]).then(()=>{})),t.destroy=(s=>Promise.all([e.destroy(s??null),n.destroy(s??null)]).then(()=>{})),AS(t)}function RS(n){if(!n)return null;try{return new URL(String(n)).hostname}catch{return null}}function rh(n){for(let e of Lr.keys())if(oh(e)?.host===n)return!0;return!1}function ih(n,e){if(!e||!e.raw)return new Error(`TLS peer ${n} did not present a certificate`);let t=Kl(e.raw);for(let[s,r]of Lr.entries()){let i=oh(s);if(i&&i.host===n&&r===t)return}return new Error(`TLS pin mismatch for ${n} (cert sha256 ${gd(t)})`)}function oh(n){let e=n.lastIndexOf(":");if(e<0)return null;let t=n.slice(0,e),s=Number(n.slice(e+1));return Number.isInteger(s)?{host:t,port:s}:null}function Xo(n){return rh(n)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,t)=>ih(e,t)}:{autoSelectFamily:!0}}function TS(){Lr.clear(),jl=!1}var Lr,jl,Zo=V(()=>{"use strict";Hl();Lr=new Map,jl=!1});import*as uh from"os";async function Dt(n){let e=await Jo(),t=await Cs();if(t&&Fn(t.pid))return{baseUrl:`http://127.0.0.1:${t.loopbackPort}`,wsUrl:`ws://127.0.0.1:${t.loopbackPort}/acp`,token:e,display:`${t.host}:${t.port}`,isLocal:!0};let s=n.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=n.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Fr(r)}}function dh(n,e){let{httpScheme:t,wsScheme:s}=Bl(n.host);return{baseUrl:`${t}://${n.host}:${n.port}`,wsUrl:`${s}://${n.host}:${n.port}/acp`,token:e,display:ph(n),isLocal:n.isLoopback}}async function fh(n,e={}){let t=e.fetchImpl??fetch,s=e.promptImpl??Fi,r=e.confirmImpl??_S,i=e.tlsHandshakeImpl??ES,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(n.isLoopback&&o){let w=await Mi();if(w)return MS(n,w)}let c=e.store??await hd.load();Wl(c),Jl();let d=c.get(n.host,n.port);if(d)return d.pinnedFingerprint&&Go(n.host,n.port,d.pinnedFingerprint),dh(n,d.token);if(!a)throw new Yl(n.host,n.port);let l=ph(n),{httpScheme:u}=Bl(n.host),f;if(u==="https"&&ql(n.host,n.port)===void 0){let w=await i(n.host,n.port);if(w.kind==="untrusted"){let v=w.subject||w.issuer?`
10
+ subject: ${w.subject??"(unknown)"}
11
+ issuer: ${w.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
+ sha256: ${gd(w.fingerprint)}${v}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);Go(n.host,n.port,w.fingerprint),f=w.fingerprint}else if(w.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${w.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let h=`${u}://${n.host}:${n.port}`,m=await t(`${h}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:lh()})});if(m.status===401)throw new Error(`Wrong password for ${l}.`);if(m.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(m.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!m.ok)throw new Error(`Login to ${l} failed: HTTP ${m.status}`);let y=await m.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(n.host,n.port,{token:y.session_token,expiresAt:y.expires_at,label:lh(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),dh(n,y.session_token)}async function ES(n,e){let t=await PS(n,e);return t.kind!=="untrusted"?t:{kind:"untrusted",fingerprint:await zl(n,e),...t.subject!==void 0?{subject:t.subject}:{},...t.issuer!==void 0?{issuer:t.issuer}:{}}}async function PS(n,e,t=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:n,port:e,servername:n,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${t}ms`}),t);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?ch(p.subject):void 0,issuer:p?.issuer?ch(p.issuer):void 0});return}let f=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:f.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function ch(n){if(!n)return"";let e=[];for(let[t,s]of Object.entries(n)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${t}=${r}`)}return e.join(", ")}async function MS(n,e){let t=await Cs(),r=t&&Fn(t.pid)?t.loopbackPort:n.port,i=n.port===$n?n.host:`${n.host}:${n.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 _S(n){return process.stdout.write(n),new Promise(e=>{let t="",s=r=>{t+=r.toString("utf8");let i=t.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=t.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function lh(){try{let n=uh.hostname();return n.length>0?n:"remote"}catch{return"remote"}}function ph(n){return n.port===$n?n.host:`${n.host}:${n.port}`}var Yl,Br=V(()=>{"use strict";Qe();xs();Vo();Hl();Ul();Qo();Oi();Zo();Vo();Yl=class extends Error{host;port;constructor(e,t){let s=t===$n?"":`:${t}`;super(`No cached credentials for ${e}:${t}. Run \`${Qn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=t}}});import{appendFileSync as $S,renameSync as FS,statSync as OS}from"fs";function gh(n){mh=n}function oe(n){let e=process.env.HYDRA_TUI_DEBUG_LOG,t=e===void 0?L.tuiLogFile():e;if(t.length!==0)try{LS(t);let s=JSON.stringify({t:new Date().toISOString(),...n});$S(t,`${s}
15
+ `)}catch{}}function LS(n){try{if(OS(n).size<mh)return;FS(n,`${n}.0`)}catch{}}var mh,Nr=V(()=>{"use strict";ve();mh=5*1024*1024});import*as Eh from"fs";import*as Ht from"fs/promises";import*as er from"path";import{spawn as Ph}from"child_process";import{Readable as jS}from"stream";function wn(){let n=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(!(!n||!e))return`${n}-${e}`}function eu(n,e=wn()){if(e)return n[e]}function tu(n){Li=n??(e=>process.stderr.write(e+`
16
+ `))}async function Mh(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${wn()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=wn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentInstallDir(n.agentId,e,n.version),s=er.resolve(t,n.target.cmd);if(await Zl(s))return s;if(await qS({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await Zl(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await Ht.chmod(s,493).catch(()=>{}),s}async function qS(n){await Ht.mkdir(er.dirname(n.installDir),{recursive:!0});let e=await Ht.mkdtemp(`${n.installDir}.partial-`);try{Li(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await WS({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Li(`hydra-acp: extracting ${n.agentId}`),Bi(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await KS(t,e),await Ht.unlink(t).catch(()=>{});try{await Ht.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Zl(n.installDir)){await Ht.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Bi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Li(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Bi(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Ht.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Bi(n,e){if(n)try{n(e)}catch{}}async function WS(n){let e=zS(n.url),t=er.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Eh.createWriteStream(t),o=jS.fromWeb(s.body);Bi(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,Bi(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Li(Th(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),Li(Th(n.agentId,a,r,!0)),Bi(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Th(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function zS(n){let e=new URL(n);return er.posix.basename(e.pathname)||"archive"}async function KS(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await Xl("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await JS("unzip")){await Xl("unzip",["-q",n,"-d",e]);return}await Xl("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function Xl(n,e){return new Promise((t,s)=>{let r=Ph(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function JS(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Ph(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Zl(n){try{return await Ht.access(n),!0}catch{return!1}}var Li,Ni=V(()=>{"use strict";ve();Li=n=>{process.stderr.write(n+`
17
+ `)}});var j,kd=V(()=>{"use strict";j={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 Be}from"zod";var Dh,ck,Hh,Uh,jh,au=V(()=>{"use strict";Dh=Be.object({protocolVersion:Be.number().optional(),clientCapabilities:Be.record(Be.unknown()).optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional()}),ck=Be.enum(["full","pending_only","none","after_message"]),Hh=Be.object({cwd:Be.string(),mcpServers:Be.array(Be.unknown()).optional(),_meta:Be.record(Be.unknown()).optional()}),Uh=Be.object({upstreamSessionId:Be.string(),agentId:Be.string(),cwd:Be.string(),title:Be.string().optional(),agentArgs:Be.array(Be.string()).optional()}),jh=Be.object({sessionId:Be.string(),historyPolicy:ck.default("full"),afterMessageId:Be.string().optional(),clientId:Be.string().optional(),clientInfo:Be.object({name:Be.string(),version:Be.string().optional()}).optional(),_meta:Be.record(Be.unknown()).optional()})});import{z as pe}from"zod";function Id(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function zh(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ea(n._meta,Id(n))};return n.title!==void 0&&(e.title=n.title),e}var qh,Wh,du,YP,lk,VP,cu=V(()=>{"use strict";xd();qh=pe.object({sessionId:pe.string()}),Wh=pe.object({cwd:pe.string().optional(),cursor:pe.string().optional()}),du=pe.object({used:pe.number().optional(),size:pe.number().optional(),costAmount:pe.number().optional(),costCurrency:pe.string().optional()}),YP=pe.object({sessionId:pe.string(),upstreamSessionId:pe.string().optional(),cwd:pe.string(),title:pe.string().optional(),agentId:pe.string().optional(),currentModel:pe.string().optional(),currentUsage:du.optional(),importedFromMachine:pe.string().optional(),importedFromUpstreamSessionId:pe.string().optional(),parentSessionId:pe.string().optional(),forkedFromSessionId:pe.string().optional(),forkedFromMessageId:pe.string().optional(),originatingClient:pe.object({name:pe.string(),version:pe.string().optional()}).optional(),interactive:pe.boolean().optional(),priority:pe.number().int().nonnegative().optional(),updatedAt:pe.string(),attachedClients:pe.number().int().nonnegative(),status:pe.enum(["warm","cold"]).default("warm"),busy:pe.boolean().default(!1),awaitingInput:pe.boolean().default(!1),compactionState:pe.any().optional(),forkSynthesisState:pe.enum(["running","failed"]).optional(),_meta:pe.record(pe.unknown()).optional()}),lk=pe.object({sessionId:pe.string(),cwd:pe.string(),title:pe.string().optional(),updatedAt:pe.string().optional(),_meta:pe.record(pe.unknown()).optional()}),VP=pe.object({sessions:pe.array(lk),nextCursor:pe.string().optional()})});function uk(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function rn(n){if(!n)return{};let e=n[$t];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=Uh.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=du.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.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(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.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(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.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(t.availableModes)){let r=[];for(let i of t.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(t.availableModels)){let r=[];for(let i of t.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((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=uk(t.env);r!==void 0&&(s.env=r)}return s}function ea(n,e){return{...n??{},[$t]:e}}var $t,xd=V(()=>{"use strict";au();cu();$t="hydra-acp"});import{z as te}from"zod";var Kh,Ad,Jh,tM,nM,sM,Yh,rM,Vh,iM,Qh,oM,aM,Gh=V(()=>{"use strict";Kh=te.object({sessionId:te.string(),prompt:te.array(te.unknown()),_meta:te.record(te.unknown()).optional()}),Ad=te.object({sessionId:te.string()}),Jh=te.object({clientId:te.string(),name:te.string().optional(),version:te.string().optional()}),tM=te.object({sessionId:te.string(),messageId:te.string(),originator:Jh,prompt:te.array(te.unknown()),position:te.number().int().nonnegative(),queueDepth:te.number().int().positive(),enqueuedAt:te.number()}),nM=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),sM=te.object({sessionId:te.string(),messageId:te.string(),reason:te.enum(["started","cancelled","abandoned"])}),Yh=te.object({sessionId:te.string(),messageId:te.string()}),rM=te.object({cancelled:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Vh=te.object({sessionId:te.string(),messageId:te.string(),prompt:te.array(te.unknown())}),iM=te.object({updated:te.boolean(),reason:te.enum(["ok","not_found","already_running"])}),Qh=te.object({sessionId:te.string(),targetMessageId:te.string(),prompt:te.array(te.unknown()),replaceQueue:te.boolean().optional(),onTargetCompleted:te.enum(["reject","send_anyway"]).optional()}),oM=te.object({amended:te.boolean(),reason:te.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:te.string().optional()}),aM=te.object({sessionId:te.string(),cancelledMessageId:te.string(),newMessageId:te.string(),prompt:te.array(te.unknown()),originator:Jh,amendedAt:te.number()})});import{z as tr}from"zod";var Xh,Cd,Ui,Zh=V(()=>{"use strict";Xh=tr.object({agentId:tr.string(),version:tr.string(),source:tr.enum(["binary","npm"]),phase:tr.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:tr.number().optional(),totalBytes:tr.number().optional(),packageSpec:tr.string().optional()}),Cd="hydra-acp/agents/install_progress",Ui={auth:{terminal:!0},_meta:{"terminal-auth":!0}}});var Ft=V(()=>{"use strict";kd();au();xd();cu();Gh();Zh()});import{nanoid as fk}from"nanoid";var lu,Kt,Hr=V(()=>{"use strict";Ft();lu=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Kt=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}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,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(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,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new lu;let s=fk(),r={jsonrpc:"2.0",id:s,method:e,params:t},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,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};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 t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:j.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(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??j.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.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>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){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,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}}});async function ji(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;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:t,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 qi(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;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:t,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 uu=V(()=>{"use strict"});import*as nm from"fs/promises";function xk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yk,wk,Wi,bk,vk,Sk,kk,Ik,tm,Ed,sm=V(()=>{"use strict";yk=64*1024*1024,wk=1*1024*1024,Wi=64*1024,bk=6e4,vk=100,Sk=1e3,kk=64*1024,Ik=256*1024,tm=20;Ed=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??yk,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(wk,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,t){let s=Math.max(0,Math.min(t,Wi));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Wi)),s=this.oldestAvailable,r=this.writeCursor-t,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 t=Math.max(0,Math.min(e,Wi)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,bk));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 t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),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(xk(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??vk,Sk)),f=Math.max(1,Math.min(e.maxBytes??kk,Ik)),p=Math.max(0,Math.min(e.contextBefore??0,tm)),h=Math.max(0,Math.min(e.contextAfter??0,tm)),m=[],y=[],w=[],v=0,S=!1,x=0,T=0,E=(M,D)=>{for(let X of w)X.remaining>0&&(X.match.after===void 0&&(X.match.after=[]),X.match.after.push({cursor:M,line:D}),X.remaining--,v+=D.length);for(;w.length>0&&w[0].remaining===0;)w.shift();if(d.test(D)!==l&&m.length<u){let X={cursor:M,line:D};if(p>0&&y.length>0){X.before=y.slice();for(let Z of X.before)v+=Z.line.length}v+=D.length,m.push(X),h>0&&w.push({match:X,remaining:h})}if(p>0)for(y.push({cursor:M,line:D});y.length>p;)y.shift();let O=m.length>=u&&w.length===0,K=v>=f;return O||K};for(let M=0;M<o.length;M++){if(o[M]!==10)continue;let D=o.subarray(x,M).toString("utf8"),B=r+x;if(x=M+1,T=x,E(B,D)){S=!0;break}}if(!S&&x<o.length&&this.closed){let M=o.subarray(x).toString("utf8"),D=r+x;E(D,M)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),N={matches:m,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(N.gap=i),this.closed&&$>=this.writeCursor&&(N.eof=!0),N}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&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 t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===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(()=>nm.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var zi,PM,rm=V(()=>{"use strict";zi=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],PM=new Map(zi.map(n=>[n.verb,n]))});function im(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Ki(n,e){return fu(n,e.map(t=>t.modelId))}function fu(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=im(n),s=e.filter(i=>im(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.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:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}var Pd=V(()=>{"use strict"});function om(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=pu(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=t.get(l);u?u.push(...d.content):t.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let d=pu(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?Ck(r,i.outIndex,Ak(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&t.has(u)?Rk(c,t.get(u)??[]):c;u!==void 0&&s.has(u)&&!Tk(f)&&(f=Ek(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function pu(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ak(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Ck(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Rk(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Tk(n){let t=pu(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Ek(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var am=V(()=>{"use strict"});function Ji(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){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=mu(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=gu(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(hu(c))):d==="turn_complete"&&i()}return i(),Fk(s.join(`
18
+ `),t)}function hu(n){let e=Mk(n),t=_k(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Mk(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function _k(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Pk){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${$k(r,200)}`)}return t}function mu(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function gu(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function $k(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Fk(n,e){if(n.length<=e)return n;let t=n.split(`
19
+ `);for(;t.length>0;){let s=dm+t.join(`
20
+ `);if(s.length<=e)return s;t.shift()}return dm}var dm,Pk,Md=V(()=>{"use strict";dm=`[older history truncated]
21
+ `,Pk=["file_path","filePath","path","command","pattern","query"]});function yu(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??cm}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let o=ta("Open threads",t.open_threads);o.length>0&&e.push(o);let a=ta("Decisions",t.decisions);a.length>0&&e.push(a);let c=ta("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let d=ta("Unresolved errors",t.unresolved_errors);d.length>0&&e.push(d);let l=ta("Tool state",t.tool_state);l.length>0&&e.push(l);let u=lm(t.files_touched);u.length>0&&e.push(`[Files previously touched] ${u}`);let f=lm(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??cm}`);let{closedText:s,openText:r,keptCount:i}=Ok(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+i+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
22
+ `)}function ta(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
23
+ `)}`}function lm(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Ok(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:i}=Lk(n),o=0,a=[];if(e>0&&r.length>0){let l=r.filter(p=>p.startEntryIndex>=t).length,u=Math.max(l,s),f=Math.min(u,e,r.length);o=f,a=f>0?r.slice(-f):[]}let c=a.length>0?um(a):"",d=i?um([i]):"";return{closedText:c,openText:d,keptCount:o}}function um(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
24
+ `)}function Lk(n){let e=[],t=null;for(let r=0;r<n.length;r++){let i=n[r];if(i.method!=="session/update")continue;let a=i.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let c=a.sessionUpdate;if(c==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:mu(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&t!==null){let d=gu(a.content);d.length>0&&(t.agent+=d)}else c==="tool_call"&&t!==null?t.tools.push(hu(a)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}var cm,fm=V(()=>{"use strict";Md();cm="(untitled)"});import*as Xn from"fs/promises";async function na(n,e){let t=L.queueFile(n);if(e.length===0){await Xn.unlink(t).catch(()=>{});return}await Xn.mkdir(L.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
25
25
  `)+`
26
- `;await Gn.writeFile(t,s,"utf8")}async function lm(n){let e=L.queueFile(n),t;try{t=await Gn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
27
- `))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 um(n){let e=L.queueFile(n);await Gn.unlink(e).catch(()=>{})}var yu=V(()=>{"use strict";ve()});import{customAlphabet as mm}from"nanoid";import*as wm from"fs/promises";function tr(){return`m_${ym()}`}function ft(n){return n.startsWith(Ut)?n.slice(Ut.length):n}function on(n,e){return n.code=e,n}function fm(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Nk.has(s)}function Dk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Hk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Uk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Ji(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,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 na(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,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 jk(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.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 qk(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.chunks.push(i.text),n.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.thinkingChars+=i.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function Wk(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.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 zk(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:tr()}}}function vu(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function pm(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function Kk(n){let e=Jk(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=Yk(n.resolver),t}function Jk(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function Yk(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Ki(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function bu(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Vk(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function hm(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
26
+ `;await Xn.writeFile(t,s,"utf8")}async function pm(n){let e=L.queueFile(n),t;try{t=await Xn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
27
+ `))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 hm(n){let e=L.queueFile(n);await Xn.unlink(e).catch(()=>{})}var wu=V(()=>{"use strict";ve()});import{customAlphabet as wm}from"nanoid";import*as Sm from"fs/promises";function sr(){return`m_${vm()}`}function ft(n){return n.startsWith(Ut)?n.slice(Ut.length):n}function on(n,e){return n.code=e,n}function mm(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&jk.has(s)}function qk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Wk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function zk(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function Vi(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,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 sa(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,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 Kk(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.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 Jk(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.chunks.push(i.text),n.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(n.thinkingChars+=i.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function Yk(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.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 Vk(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:sr()}}}function Su(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function gm(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function Qk(n){let e=Gk(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=Xk(n.resolver),t}function Gk(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function Xk(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Yi(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function vu(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Zk(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function ym(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
28
28
  ${s.join(`
29
- `)}`}function Su(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var gm,ym,wu,$k,Fk,Ok,Ut,Lk,Md,Bk,Yi,Nk,Xn=V(()=>{"use strict";lu();em();tm();Ed();rm();cm();yu();Ft();gm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ym=mm(gm,16),wu=mm(gm,16),$k=20,Fk=20,Ok=5,Ut="hydra_session_";Lk=1e3,Md=300*1e3,Bk=64,Yi=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Ut}${ym()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Lk,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",t=>{if(this.internalPromptCapture){qk(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=pm(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.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,t=new Set,s=0,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let u=this.transformChain[l];if(t.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${wu()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,b=new Set(t),v=r;await new Promise(S=>{let x=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...b,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},Md);typeof x.unref=="function"&&x.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:x,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:b,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),t.add(u.name)}if(r!=="session/update")return;let c=Wk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=jk(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];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),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=this.currentModel,l=this.currentMode,u=this.spawnReplacementAgent;if(!u)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await u({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await Ui({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await Hi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=gu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,b=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...b!==void 0?{previousSummarizedThroughEntry:b}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
29
+ `)}`}function ku(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var bm,vm,bu,Bk,Nk,Dk,Ut,Hk,_d,Uk,Qi,jk,Zn=V(()=>{"use strict";uu();sm();rm();Pd();am();fm();wu();Ft();bm="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",vm=wm(bm,16),bu=wm(bm,16),Bk=20,Nk=20,Dk=5,Ut="hydra_session_";Hk=1e3,_d=300*1e3,Uk=64,Qi=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Ut}${vm()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Hk,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",t=>{if(this.internalPromptCapture){Jk(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=gm(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let i=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:i,sourceWasTransformer:!1}),i}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.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,t=new Set,s=0,r="session/update"){let i=e,o=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let l=s;l<this.transformChain.length;l++){let u=this.transformChain[l];if(t.has(u.name)||!u.intercepts.has(a))continue;let f=`t_${bu()}`,p;try{p=await u.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(m){this.logger?.warn(`transformer ${u.name} error on ${a}: ${m.message}`);continue}let h=p?.action??"continue";if(h==="stop")return;if(h==="processing"){let m=l,y=o,w=new Set(t),v=r;await new Promise(S=>{let x=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:u.name}),this.runResponseChain(y,new Set([...w,u.name]),m+1,v).then(()=>S()).catch(()=>S()))},_d);typeof x.unref=="function"&&x.unref(),this.pendingClaims.set(f,{resolve:()=>S(),timer:x,transformerName:u.name,method:v,envelope:y,chainIdx:m,originatedBy:w,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(o=p.payload),t.add(u.name)}if(r!=="session/update")return;let c=Yk(o);if(c!==null){this.setAgentAdvertisedCommands(c);return}let d=Kk(o);if(d!==null){this.setAgentAdvertisedModes(d);return}if(this.maybeApplyAgentModel(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentMode(o)){this.recordAndBroadcast("session/update",o);return}if(this.maybeApplyAgentConfigOption(o)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(o));return}if(this.maybeApplyAgentUsage(i)){this.recordAndBroadcast("session/update",o);return}this.maybeApplyAgentSessionInfo(o),this.recordAndBroadcast("session/update",o)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];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),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,i=r!==this.agentId,o=this.cwd,a=this.agentArgs,c=this.forwardedEnv,d=this.currentModel,l=this.currentMode,u=this.spawnReplacementAgent;if(!u)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await u({agentId:r,cwd:o,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),i||(await qi({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:d,agentReportedModel:p.initialModel,logger:this.logger}),await ji({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:l,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let h=[];if(this.historyStore)try{h=await this.historyStore.load(this.sessionId)}catch(T){this.logger?.warn(`swapUpstream: historyStore.load failed: ${T.message}`)}let m=yu({synopsis:e.artifact,title:e.title,tail:h,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:m}]});let T=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${T.toolCalls} thinkingChars=${T.thinkingChars} messageChars=${T.messageChars} used=${T.lastUsed??"?"} size=${T.lastSize??"?"} reply=${JSON.stringify(T.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let y=this.upstreamSessionId,w=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,i&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let T of this.agentChangeHandlers)try{T({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(E){this.logger?.warn(`swapUpstream: agentChange handler failed: ${E.message}`)}if(!i&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:y,...w!==void 0?{previousSummarizedThroughEntry:w}:{}})}catch(T){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${T.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:y,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),i||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),i&&this.broadcastAgentSwitch(s,r);let S=i?`
30
30
  Switched to ${r}.
31
31
  `:`
32
32
  Compaction completed.
33
- `,x=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",x).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 Ui({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Hi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=$k){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let u=c.status;(u==="completed"||u==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw on(new Error("session is closed"),j.SessionNotFound);if(this.clients.has(e.clientId))throw on(new Error(`client ${e.clientId} is already attached`),j.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:sm(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!fm(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?vu(i,t.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=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,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,t){let s=this.clients.get(e);if(!s)throw on(new Error("client not attached"),j.SessionNotFound);if(this.closing)throw on(new Error("session is closing; new prompts cannot be accepted"),j.SessionClosing);let r=tr();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(rn((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.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:t}},e.clientId);let s=Ki(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.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),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:tr()};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,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Bk;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.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 t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.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};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,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:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.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 t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,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,t){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=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw on(new Error("client not attached"),j.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;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,t,s,r){let i=tr(),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:t,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,t){let s=tr(),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:t,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 on(new Error("client not attached"),j.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 t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=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,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);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_${wu()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${d}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??bu(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:bu(e))))},Md);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${wu()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??Vk(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},Md);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:b,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Md,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:bu(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=tr(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Ki((e??{}).prompt),r=Su(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=Ji(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=Ji(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=na(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=Ji(o.options);if(c.length>0){let d=na(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:h,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(Dk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Hk(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),Uk(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(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 t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};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 t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.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?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of qi){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let d=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}if(c.length>0&&t.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of qi)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,o):c!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){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=t!==void 0;if(qi.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=j.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,t):this.runExtensionCommand(c,o);let d=qi.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=j.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let u,f=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){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:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
33
+ `,x=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:S},_meta:{"hydra-acp":{synthetic:!0}}}});for(let T of this.clients.values())T.connection.notify("session/update",x).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 qi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await ji({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let u=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await u.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let f of this.agentChangeHandlers)try{f({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Bk){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let u=c.status;(u==="completed"||u==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw on(new Error("session is closed"),j.SessionNotFound);if(this.clients.has(e.clientId))throw on(new Error(`client ${e.clientId} is already attached`),j.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:om(a),i=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!mm(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Su(i,t.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=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,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:t,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,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,t){let s=this.clients.get(e);if(!s)throw on(new Error("client not attached"),j.SessionNotFound);if(this.closing)throw on(new Error("session is closing; new prompts cannot be accepted"),j.SessionClosing);let r=sr();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(rn((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.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:t}},e.clientId);let s=Yi(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 t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.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),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:sr()};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,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Uk;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.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 t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.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};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,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:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.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 t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,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,t){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=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw on(new Error("client not attached"),j.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;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,t,s,r){let i=sr(),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:t,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,t){let s=sr(),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:t,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 on(new Error("client not attached"),j.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 t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=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,t,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(t);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_${bu()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${d}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??vu(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,h=o,m=new Set(s);return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,h,new Set([...m,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:vu(e))))},_d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(l,{resolve:y,timer:w,transformerName:c.name,method:e,envelope:h,chainIdx:p,originatedBy:m,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}async runAgentRequestChain(e,t,s=new Set,r=0){let i=t,o=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(o))continue;let d=`t_${bu()}`,l;try{l=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${c.name} error on ${o}: ${f.message}`);continue}let u=l?.action??"continue";if(u==="stop")return{shortCircuit:!0,payload:l?.payload??Zk(e)};if(u==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(c.name);continue}if(u==="processing"){let f=a,p=i,h=new Set(s),m=e;return new Promise(y=>{let w=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.runAgentRequestChain(m,p,new Set([...h,c.name]),f+1).then(y).catch(()=>y({shortCircuit:!1,envelope:p})))},_d);typeof w.unref=="function"&&w.unref(),this.pendingClaims.set(d,{resolve:v=>y({shortCircuit:!0,payload:v}),timer:w,transformerName:c.name,method:m,envelope:p,chainIdx:f,originatedBy:h,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:i}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):_d,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:vu(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}async emitToQueue(e,t){let s=this.transformChain.findIndex(d=>d.name===e),r=s>=0?s+1:0,i=(t??{}).prompt??[],o=sr(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((d,l)=>{let u={kind:"user",messageId:o,originator:c,clientId:a,prompt:i,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:d,reject:l},f=this.insertEntryAt(u,"tail");this.persistRewrite(),this.broadcastQueueAdded(u,{position:f}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Yi((e??{}).prompt),r=ku(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=Vi(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=Vi(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=sa(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=Vi(o.options);if(c.length>0){let d=sa(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,h=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(m>=0){let y={...this.agentAdvertisedConfigOptions[m]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:h,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(qk(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Wk(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),zk(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(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 t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};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 t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};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 t=e;if(!t.update||typeof t.update!="object")return e;let s=t.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?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of zi){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let i=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${i} ${r.argsHint}`:i};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let d=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}if(c.length>0&&t.get(c)===s){let d=r.verb?`${c} ${r.verb}`:c,u={name:r.argsHint?`${d} ${r.argsHint}`:d};r.description&&(u.description=r.description),e.push(u)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=o=>o.split(/\s+/)[0]??"";for(let o of this.daemonTopLevelCommands()){let a=t(o.name);a&&e.add(a)}for(let o of this.agentAdvertisedCommands){let a=t(o.name);a&&e.add(a)}let s=new Map;for(let o of zi)e.has(o.verb)||s.set(o.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,i=new Set;for(let{name:o}of this.extensionCommands.list()){if(i.has(o))continue;i.add(o);let a=o.startsWith("hydra-acp-")?o.slice(10):o;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,o):c!==o&&r.set(a,"__conflict__")}for(let[o,a]of r)a!=="__conflict__"&&s.set(o,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){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=t!==void 0;if(zi.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=j.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,t):this.runExtensionCommand(c,o);let d=zi.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(d.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=j.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(h=>h.verb===o)){let h=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${h||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(h=>{d=h});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:h=>d({stopReason:"cancelled",reason:h})});let u,f=!1;try{let h=r.connection.request("hydra-acp/commands/invoke",c),m=await Promise.race([h,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(h){return this.emitExtensionReply(`${e} ${o}: ${h.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){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:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
34
34
  ${e}
35
35
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.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 (${t.length}):
36
36
  ${s.join(`
@@ -43,7 +43,7 @@ ${s}
43
43
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let c=o?i.some(l=>l.modelId===o):!0,d=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!c&&o&&d.unshift(`\u25B6 ${o}`),a=d.join(`
44
44
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
45
45
  ${a}
46
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Wi(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" 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:`
46
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Ki(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" 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:`
47
47
  ${d}.
48
48
  ${l}:
49
49
  ${c.join(`
@@ -53,7 +53,7 @@ ${l}:
53
53
  ${o}
54
54
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(i=>i.id).join(", ");throw on(new Error(`unknown mode: ${t} (known: ${r})`),j.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[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:`
55
55
  _(no config options advertised yet)_
56
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>hm(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
56
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>ym(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
57
  ${u.join(`
58
58
 
59
59
  `)}
@@ -63,16 +63,16 @@ ${u.join(`
63
63
  Available options:
64
64
  ${l}
65
65
  `},_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:`
66
- ${hm(o)}
67
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=uu(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),u=c.kind==="ambiguous"?c.candidates:a.filter(m=>m.toLowerCase().includes(l)),f=u.length>0?u:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=c.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
66
+ ${ym(o)}
67
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=fu(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),u=c.kind==="ambiguous"?c.candidates:a.filter(m=>m.toLowerCase().includes(l)),f=u.length>0?u:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,h=c.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
68
68
  ${p}.
69
69
  ${h}:
70
70
  ${f.join(`
71
71
  `)}
72
72
  `},_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 t={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw on(new Error("/hydra agent requires an agent id"),j.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw on(new Error(`already on agent ${r}`),j.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw on(new Error("agent restart not configured for this session"),j.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?.(),t=this._summarizedThroughEntry;if(e==null&&t==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: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
73
- `)),{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 on(new Error("session is closing"),j.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,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(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Ki(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.title;(h==="completed"||h==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${h}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=t?.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(`
74
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=gu({synopsis:e,title:t,tail:s,tailK:Fk,tailFloor:Ok,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new Td(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,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??ji,ji)),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,t){return this.requireStreamBuffer().waitForData(e,t)}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=j.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>um(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>wm.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=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(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}notifyChain(e,t){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:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!fm(e,r),o=i?zk(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw on(new Error("no clients attached to handle permission request"),j.PermissionDenied);let s=this.rewriteForClient(e),r=pm(s),i=tr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===j.MethodNotFound;function b(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(x=>{f--,m(()=>{let T=Kk({toolCallId:r,result:x,resolver:v});for(let E of u)E.client.clientId!==v.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??on(new Error("no client handled permission request"),j.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of t)b(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:tr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).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(t);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 t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["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,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.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 t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ta(t,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 t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Ki(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
- `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(i){let c=t.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};Nk=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 Vi}from"zod";var Qk,bm,vm=V(()=>{"use strict";Qk=Vi.object({source:Vi.string(),reason:Vi.string(),raisedAt:Vi.number(),payload:Vi.unknown()}),bm=Vi.array(Qk)});import{z as Ne}from"zod";function Im(n){let e=n.trim();if(e.length===0)return;let t=Qi(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=Qi(e.slice(i,o+1)))}if(t===void 0){let i=Am(e);i!==void 0&&(t=Qi(i))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,km))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=sa.safeParse(s.synopsis);i.success&&Gk(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function xm(n){let e=n.trim();if(e.length===0)return;let t=Qi(e);if(t===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(t=Qi(e.slice(d,l+1)))}if(t===void 0){let d=Am(e);d!==void 0&&(t=Qi(d))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,km))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],u=Ne.array(Ne.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Qi(n){try{return JSON.parse(n)}catch{return}}function Am(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function Gk(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var Sm,sa,km,ku,Iu,_d=V(()=>{"use strict";Sm=Ne.object({status:Ne.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Ne.number(),iter:Ne.number().int().nonnegative().optional(),attempts:Ne.number().int().nonnegative().optional(),lastError:Ne.string().optional(),worker:Ne.object({upstreamSessionId:Ne.string(),pid:Ne.number().int().nonnegative()}).optional()}),sa=Ne.object({goal:Ne.string().optional(),outcome:Ne.string().optional(),files_touched:Ne.array(Ne.string()).optional(),tools_used:Ne.array(Ne.string()).optional(),rejected_approaches:Ne.array(Ne.string()).optional(),open_threads:Ne.array(Ne.string()).optional(),decisions:Ne.array(Ne.string()).optional(),file_edit_intentions:Ne.array(Ne.string()).optional(),unresolved_errors:Ne.array(Ne.string()).optional(),tool_state:Ne.array(Ne.string()).optional()}),km=200,ku=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
73
+ `)),{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 on(new Error("session is closing"),j.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,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(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let h=Yi(u.prompt);h&&s.push({speaker:"user",text:h})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let h=u.status,m=u.title;(h==="completed"||h==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${h}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=t?.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(`
74
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(i){this.logger?.warn(`seedFromFork: historyStore.load failed: ${i.message}`)}let r=yu({synopsis:e,title:t,tail:s,tailK:Nk,tailFloor:Dk,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let i=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${i.toolCalls} thinkingChars=${i.thinkingChars} messageChars=${i.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new Ed(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,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Wi,Wi)),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,t){return this.requireStreamBuffer().waitForData(e,t)}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=j.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let i of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(i,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let i of s){i.cancelled=!0,i.kind==="user"&&this.broadcastQueueRemoved(i.messageId,"abandoned");try{i.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>hm(r).catch(()=>{}));for(let i of this.clients.values())i.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let i=this.streamBuffer,o=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,i.close(),o!==void 0&&i.drainFileWrites().then(()=>Sm.unlink(o).catch(()=>{}))}for(let i of this.closeHandlers)i(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let i=`${e}::${t}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=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(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let i=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!i)return;let o=typeof s.kind=="string"?s.kind:void 0;o&&!this.toolCallKind.has(i)&&this.toolCallKind.set(i,o);let a=o??this.toolCallKind.get(i);if(a==="edit"&&Array.isArray(s.locations))for(let l of s.locations){if(!l||typeof l!="object")continue;let u=l.path;if(typeof u!="string"||u.length===0||this.filesEditedSeen.has(u))continue;this.filesEditedSeen.add(u);let f=l.line,p={path:u,toolCallId:i};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(i))return;this.toolCompletionSeen.set(i,c);let d={toolCallId:i,status:c};a&&(d.kind=a),s.content!==void 0&&(d.content=s.content),Array.isArray(s.locations)&&(d.locations=s.locations),this.notifyChain("tool.completed",d)}notifyChain(e,t){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:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!mm(e,r),o=i?Vk(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw on(new Error("no clients attached to handle permission request"),j.PermissionDenied);let s=this.rewriteForClient(e),r=gm(s),i=sr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,h=this.sessionId,m=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===j.MethodNotFound;function w(v){if(l)return;let S=v.connection.request("session/request_permission",s);u.push({client:v}),f++,S.then(x=>{f--,m(()=>{let T=Qk({toolCallId:r,result:x,resolver:v});for(let E of u)E.client.clientId!==v.clientId&&E.client.connection.notify("session/update",{sessionId:h,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??on(new Error("no client handled permission request"),j.PermissionDenied);m(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,w);for(let v of t)w(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:sr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).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(t);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 t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["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,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.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 t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>na(t,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 t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Yi(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
+ `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",i=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||i){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(i){let c=t.slice(s.length).trim(),d=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(d,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let o;try{o=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,o,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),o}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};jk=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 Gi}from"zod";var eI,km,Im=V(()=>{"use strict";eI=Gi.object({source:Gi.string(),reason:Gi.string(),raisedAt:Gi.number(),payload:Gi.unknown()}),km=Gi.array(eI)});import{z as Ne}from"zod";function Cm(n){let e=n.trim();if(e.length===0)return;let t=Xi(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(t=Xi(e.slice(i,o+1)))}if(t===void 0){let i=Tm(e);i!==void 0&&(t=Xi(i))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Am))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=ra.safeParse(s.synopsis);i.success&&tI(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Rm(n){let e=n.trim();if(e.length===0)return;let t=Xi(e);if(t===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(t=Xi(e.slice(d,l+1)))}if(t===void 0){let d=Tm(e);d!==void 0&&(t=Xi(d))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Am))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],u=Ne.array(Ne.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function Xi(n){try{return JSON.parse(n)}catch{return}}function Tm(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")t++;else if(o==="}"&&(t--,t===0))return n.slice(e,i+1)}}function tI(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var xm,ra,Am,Iu,xu,$d=V(()=>{"use strict";xm=Ne.object({status:Ne.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Ne.number(),iter:Ne.number().int().nonnegative().optional(),attempts:Ne.number().int().nonnegative().optional(),lastError:Ne.string().optional(),worker:Ne.object({upstreamSessionId:Ne.string(),pid:Ne.number().int().nonnegative()}).optional()}),ra=Ne.object({goal:Ne.string().optional(),outcome:Ne.string().optional(),files_touched:Ne.array(Ne.string()).optional(),tools_used:Ne.array(Ne.string()).optional(),rejected_approaches:Ne.array(Ne.string()).optional(),open_threads:Ne.array(Ne.string()).optional(),decisions:Ne.array(Ne.string()).optional(),file_edit_intentions:Ne.array(Ne.string()).optional(),unresolved_errors:Ne.array(Ne.string()).optional(),tool_state:Ne.array(Ne.string()).optional()}),Am=200,Iu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
76
76
  {
77
77
  "title": "short summary, max 80 chars",
78
78
  "synopsis": {
@@ -82,7 +82,7 @@ ${h}:
82
82
  "open_threads": ["work started but not finished"]
83
83
  }
84
84
  }
85
- Use empty arrays/strings where a field doesn't apply.`;Iu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
85
+ Use empty arrays/strings where a field doesn't apply.`;xu=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
86
86
  {
87
87
  "title": "short summary, max 80 chars",
88
88
  "goal": "the user's original ask",
@@ -94,294 +94,294 @@ Use empty arrays/strings where a field doesn't apply.`;Iu=`Reply with ONLY a JSO
94
94
  "unresolved_errors": ["errors left open at session end"],
95
95
  "tool_state": ["runtime state relevant for recall"]
96
96
  }
97
- Use empty arrays/strings where a field doesn't apply.`});import*as Gi from"fs/promises";import*as YM from"path";import{customAlphabet as Xk}from"nanoid";import{z as ne}from"zod";function ra(){return`${tI}${eI()}`}function iI(n){if(!xu.test(n))throw new Error(`unsafe session id: ${n}`)}function Eu(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}var Zk,eI,tI,Au,Cu,nI,Ru,Tu,sI,rI,xu,$d,Pu=V(()=>{"use strict";ve();Pr();vm();_d();Zk="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",eI=Xk(Zk,16),tI="hydra_lineage_";Au=ne.object({name:ne.string(),description:ne.string().optional()}),Cu=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),nI=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Ru=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Tu=ne.object({name:ne.string(),version:ne.string().optional()}),sI=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),rI=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:sa.optional(),compactionState:Sm.optional(),rollbackBreadcrumb:sI.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Ru.optional(),agentCommands:ne.array(Au).optional(),agentModes:ne.array(Cu).optional(),agentModels:ne.array(nI).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Tu.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:bm.default([]).optional(),extensionState:ne.record(ne.string(),ne.record(ne.string(),ne.unknown())).default({}).optional(),createdAt:ne.string(),updatedAt:ne.string()}),xu=/^[A-Za-z0-9_-]+$/;$d=class{async write(e){iI(e.sessionId);let t={version:1,...e};await nn(L.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!xu.test(e))return;let t=await yn(L.sessionFile(e));if(t!==void 0)try{return rI.parse(t)}catch{return}}async delete(e){if(xu.test(e)){try{await Gi.unlink(L.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Gi.rmdir(L.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Gi.readdir(L.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}}});import{fileURLToPath as aI}from"url";import*as ia from"path";import*as Od from"fs";function dI(){try{let n=ia.dirname(aI(import.meta.url));for(let e=0;e<8;e+=1){let t=ia.join(n,"package.json");if(Od.existsSync(t)){let r=JSON.parse(Od.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=ia.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var ye,Nr,an=V(()=>{"use strict";ye=dI(),Nr="hydra-acp-cat"});function Mu(n){let e=new Map;for(let t of Om(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function _m(n){return Mu(n).map(e=>e.name)}function _u(n){let e=new Map;for(let t of Om(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,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:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function $m(n){return _u(n).map(e=>e.path)}function Fm(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Om(n){let e=new Map,t=0;for(let s of n){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_${t++}`,d=e.get(c);d===void 0?(d={toolName:Pm(i),paths:new Set},e.set(c,d)):d.toolName=Pm(i);for(let l of Mm(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 Mm(i.rawInput,i.locations))a.paths.add(c)}return e}function Pm(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Mm(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.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"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var $u=V(()=>{"use strict"});import{promises as aa}from"fs";import*as Du from"path";async function da(n){let e;try{e=await aa.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return wI(e)}function wI(n){let e=[];for(let t of n.split(`
98
- `))if(t.length!==0)try{let s=JSON.parse(t);typeof s=="string"&&e.push(s)}catch{}return e}function ca(n,e,t=Km){let s=e.replace(/\n+$/,"");if(s.length===0||n.length>0&&n[n.length-1]===s)return n;let r=n.concat(s);return r.length>t?r.slice(r.length-t):r}async function Dr(n,e){await aa.mkdir(Du.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await aa.writeFile(n,t.length>0?t.join(`
97
+ Use empty arrays/strings where a field doesn't apply.`});import*as Zi from"fs/promises";import*as ZM from"path";import{customAlphabet as nI}from"nanoid";import{z as ne}from"zod";function ia(){return`${iI}${rI()}`}function cI(n){if(!Au.test(n))throw new Error(`unsafe session id: ${n}`)}function Pu(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}var sI,rI,iI,Cu,Ru,oI,Tu,Eu,aI,dI,Au,Fd,Mu=V(()=>{"use strict";ve();$r();Im();$d();sI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rI=nI(sI,16),iI="hydra_lineage_";Cu=ne.object({name:ne.string(),description:ne.string().optional()}),Ru=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),oI=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),Tu=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),Eu=ne.object({name:ne.string(),version:ne.string().optional()}),aI=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),dI=ne.object({version:ne.literal(1),sessionId:ne.string(),lineageId:ne.string().optional(),upstreamSessionId:ne.string(),importedFromSessionId:ne.string().optional(),importedFromUpstreamSessionId:ne.string().optional(),importedFromMachine:ne.string().optional(),agentId:ne.string(),cwd:ne.string(),title:ne.string().optional(),synopsis:ra.optional(),compactionState:xm.optional(),rollbackBreadcrumb:aI.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:Tu.optional(),agentCommands:ne.array(Cu).optional(),agentModes:ne.array(Ru).optional(),agentModels:ne.array(oI).optional(),pendingHistorySync:ne.boolean().optional(),pendingAgentSwap:ne.string().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),forkSynthesisState:ne.enum(["running","failed"]).optional(),originatingClient:Eu.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:km.default([]).optional(),extensionState:ne.record(ne.string(),ne.record(ne.string(),ne.unknown())).default({}).optional(),createdAt:ne.string(),updatedAt:ne.string()}),Au=/^[A-Za-z0-9_-]+$/;Fd=class{async write(e){cI(e.sessionId);let t={version:1,...e};await nn(L.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Au.test(e))return;let t=await yn(L.sessionFile(e));if(t!==void 0)try{return dI.parse(t)}catch{return}}async delete(e){if(Au.test(e)){try{await Zi.unlink(L.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Zi.rmdir(L.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Zi.readdir(L.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}}});import{fileURLToPath as uI}from"url";import*as oa from"path";import*as Ld from"fs";function fI(){try{let n=oa.dirname(uI(import.meta.url));for(let e=0;e<8;e+=1){let t=oa.join(n,"package.json");if(Ld.existsSync(t)){let r=JSON.parse(Ld.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=oa.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var ye,Ur,an=V(()=>{"use strict";ye=fI(),Ur="hydra-acp-cat"});function _u(n){let e=new Map;for(let t of Nm(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Om(n){return _u(n).map(e=>e.name)}function $u(n){let e=new Map;for(let t of Nm(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,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:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Lm(n){return $u(n).map(e=>e.path)}function Bm(n){let e=0;for(let t of n)t.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function Nm(n){let e=new Map,t=0;for(let s of n){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_${t++}`,d=e.get(c);d===void 0?(d={toolName:$m(i),paths:new Set},e.set(c,d)):d.toolName=$m(i);for(let l of Fm(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 Fm(i.rawInput,i.locations))a.paths.add(c)}return e}function $m(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Fm(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.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"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Fu=V(()=>{"use strict"});import{promises as da}from"fs";import*as Hu from"path";async function ca(n){let e;try{e=await da.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return[];throw t}return kI(e)}function kI(n){let e=[];for(let t of n.split(`
98
+ `))if(t.length!==0)try{let s=JSON.parse(t);typeof s=="string"&&e.push(s)}catch{}return e}function la(n,e,t=Vm){let s=e.replace(/\n+$/,"");if(s.length===0||n.length>0&&n[n.length-1]===s)return n;let r=n.concat(s);return r.length>t?r.slice(r.length-t):r}async function jr(n,e){await da.mkdir(Hu.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await da.writeFile(n,t.length>0?t.join(`
99
99
  `)+`
100
- `:"")}async function Jm(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await aa.mkdir(Du.dirname(n),{recursive:!0}),await aa.appendFile(n,JSON.stringify(t)+`
101
- `,{encoding:"utf8"}))}function Dd(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function Hu(n,e,t=Km){if(e.length===0)return n;let s=new Set(n),r=n;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=ca(r,o,t)))}return r}var Km,Hd=V(()=>{"use strict";Km=500});import{z as _e}from"zod";function la(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function On(n){return SI.parse(n)}var bI,vI,SI,Hr=V(()=>{"use strict";Pu();_d();bI=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),vI=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:sa.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:Ru.optional(),agentCommands:_e.array(Au).optional(),agentModes:_e.array(Cu).optional(),interactive:_e.boolean().optional(),originatingClient:Tu.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),SI=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:vI,history:_e.array(bI),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as LI}from"crypto";function Qu(n){if(Array.isArray(n))return n.map(Qu);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Qu(n[t]);return e}return n}function sr(n){let{tui:e,...t}=n,s=JSON.stringify(Qu(t));return LI("sha256").update(s).digest("hex").slice(0,16)}var ya=V(()=>{"use strict";Qe()});function Gu(n){return Math.floor(n/4)}function ug(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=Gu(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}function fg(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Xu=V(()=>{"use strict"});function wa(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var pg=V(()=>{"use strict"});import{posix as YI}from"path";import VI from"strip-ansi";function yt(n){return VI(n).replace(QI,"")}function Pe(n){return yt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ts(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return nx(t);case"agent_thought_chunk":case"agent_thought":return sx(t);case"user_message_chunk":return rx(t);case"prompt_received":return ix(t);case"tool_call":return ox(t,e);case"tool_call_update":return ux(t,e);case"plan":return hx(t);case"current_mode_update":return mx(t);case"current_model_update":return gx(t);case"turn_complete":return yx(t);case"usage_update":return tx(t);case"available_commands_update":return ZI(t);case"available_modes_update":return ex(t);case"session_info_update":return XI(t);case"config_option_update":return GI(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function GI(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];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}:{}})}t.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:t}}function XI(n){let e=dt(n,"title"),t=e!==void 0?Pe(e):void 0,s=n._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function rc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Pe(r)};typeof s.description=="string"&&(i.description=Pe(s.description)),e.push(i)}return e}function ZI(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:rc(e)}:null}function ex(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];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:Pe(r.id)};typeof r.name=="string"&&(i.name=Pe(r.name)),typeof r.description=="string"&&(i.description=Pe(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function tx(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function nx(n){let e=ba(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:wa(n)}}function sx(n){let e=typeof n.text=="string"?yt(n.text):ba(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:wa(n)}}function rx(n){let e=n._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 t=ba(n.content);return t===null?null:{kind:"user-text",text:t}}function ix(n){let e=wx(n.prompt);return e===null?null:{kind:"user-text",text:e}}function gg(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function hg(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function ic(n){let e=n.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=hg(r.oldText),o=hg(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 t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,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 yg(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:yt(t)}function ox(n,e={}){let t=dt(n,"toolCallId")??dt(n,"id");if(!t)return null;let s=dt(n,"title")??dt(n,"name")??dt(n,"label")??"tool call",r=dt(n,"name")??dt(n,"title");if(gg(r)){let h=yg(n);if(h!==null){let m=dt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=vg(Pe(s),n,e),o=dt(n,"status"),a=dt(n,"kind"),c={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=ic(n);d!==null&&(c.editDiff=d);let l=bg(n);l!==void 0&&(c.detail=l);let u=Zu(n);u!==void 0&&(c.detailFull=u);let f=wg(n);f!==void 0&&(c.locations=f);let p=wa(n);return p!==void 0&&(c.workerTaskId=p),c}function wg(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];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)),t.push(i)}return t.length>0?t:void 0}function bg(n){let e=Zu(n);if(e===void 0)return;let t=Pe(e),s=n.rawInput;return s&&typeof s.command=="string"?cx(t,mg):lx(t,mg)}function Zu(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return yt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return at(Pe(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return at(Pe(s))}}}function dx(n){for(let e of ax)if(n.startsWith(e))return!0;return!1}function vg(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return at(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;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===`/${n}`||o.endsWith(`/${n}`)||o===n))return at(o)}return dx(n)?at(`/${n}`):t.cwd&&t.cwd.length>0?at(YI.resolve(t.cwd,n)):n}function cx(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function lx(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function ux(n,e={}){let t=dt(n,"toolCallId")??dt(n,"id");if(!t)return null;let s=dt(n,"title"),r=s!==void 0?vg(Pe(s),n,e):void 0,i=dt(n,"status"),o=ic(n),a=bg(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=dt(n,"name")??s;if(gg(d)){let h={kind:"exit-plan-mode",toolCallId:t},m=yg(n);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=Zu(n);u!==void 0&&(l.detailFull=u);let f=wg(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=fx(n);h!==null&&(l.errorText=h),px(n,h)&&(l.upstreamInterrupted=!0)}let p=wa(n);return p!==void 0&&(l.workerTaskId=p),l}function fx(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ba(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return yt(s)}return null}function px(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function hx(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Pe(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),t.push(o)}return{kind:"plan",entries:t}}function mx(n){let e=dt(n,"currentModeId")??dt(n,"currentMode")??dt(n,"mode");return e?{kind:"mode-changed",mode:Pe(e)}:null}function gx(n){let e=dt(n,"currentModel")??dt(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.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:Pe(e),...s&&s.length>0?{availableModels:s}:{}}}function yx(n){let e=dt(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function ba(n){if(typeof n=="string")return yt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?yt(e.text):null}function wx(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=ba(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function dt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var QI,mg,ax,rr=V(()=>{"use strict";ve();pg();QI=/[\x00-\x08\x0b-\x1f\x7f]/g;mg=64;ax=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function eo(n){let e=new Map,t=new Map;for(let r of n){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=vx(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)bx(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function to(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function bx(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function vx(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.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=ic(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var oc=V(()=>{"use strict";rr()});function ns(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.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:j.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.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)=>{n.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var io=V(()=>{"use strict";Ft()});import{spawn as HA}from"child_process";import{setTimeout as UA}from"timers/promises";async function ay(){let n=await xs();if(n&&Fn(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function jA(n){let e=await jr(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===sr(n)?"match":"mismatch":"missing"}async function ar(n){let e=await jA(n);if(e!=="match"){if(e==="mismatch"){let t=Vn();throw new Error(`config changed since daemon started \u2014 run \`${t} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
102
- `),Sc(),await kc(n)}}async function vc(n){let e=await ay();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function jr(n,e=1e3){let t=await ay();if(t)try{let s=await fetch(t,{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 Sc(){let n=process.argv[1];if(!n)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");HA(process.execPath,[n,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function kc(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await vc(n))return;await UA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var qr=V(()=>{"use strict";Vo();ya();$i()});import*as dy from"fs";import*as co from"fs/promises";async function lo(n,e,t){let s=WA(e),r;try{r=await co.stat(n)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${t} (${n})
103
- `),process.exit(1);return}throw c}let i=await qA(n,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${n} --
104
- `);let o=!1,a=dy.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await co.stat(n);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await co.open(n,"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 qA(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await co.open(n,"r");try{let i=e,o="",a=0;for(;i>0&&a<=t;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
100
+ `:"")}async function Qm(n,e){let t=e.replace(/\n+$/,"");t.length!==0&&(await da.mkdir(Hu.dirname(n),{recursive:!0}),await da.appendFile(n,JSON.stringify(t)+`
101
+ `,{encoding:"utf8"}))}function Hd(n,e){if(e.length===0)return[...n];let t=new Set(e);return[...n.filter(r=>!t.has(r)),...e]}function Uu(n,e,t=Vm){if(e.length===0)return n;let s=new Set(n),r=n;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=la(r,o,t)))}return r}var Vm,Ud=V(()=>{"use strict";Vm=500});import{z as _e}from"zod";function ua(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function On(n){return AI.parse(n)}var II,xI,AI,qr=V(()=>{"use strict";Mu();$d();II=_e.object({method:_e.string(),params:_e.unknown(),recordedAt:_e.number()}),xI=_e.object({sessionId:_e.string(),lineageId:_e.string(),upstreamSessionId:_e.string().optional(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),synopsis:ra.optional(),summarizedThroughEntry:_e.number().int().nonnegative().optional(),currentModel:_e.string().optional(),currentMode:_e.string().optional(),currentUsage:Tu.optional(),agentCommands:_e.array(Cu).optional(),agentModes:_e.array(Ru).optional(),interactive:_e.boolean().optional(),originatingClient:Eu.optional(),priority:_e.number().int().nonnegative().optional(),createdAt:_e.string(),updatedAt:_e.string()}),AI=_e.object({version:_e.literal(1),exportedAt:_e.string(),exportedFrom:_e.object({hydraVersion:_e.string(),machine:_e.string(),hydraHost:_e.string().optional()}),session:xI,history:_e.array(II),promptHistory:_e.array(_e.string()).optional(),toolBlobs:_e.record(_e.string()).optional()})});import{createHash as HI}from"crypto";function Gu(n){if(Array.isArray(n))return n.map(Gu);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Gu(n[t]);return e}return n}function ir(n){let{tui:e,...t}=n,s=JSON.stringify(Gu(t));return HI("sha256").update(s).digest("hex").slice(0,16)}var wa=V(()=>{"use strict";Qe()});function Xu(n){return Math.floor(n/4)}function hg(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=Xu(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}function mg(n){return n>=1e3?`${Math.round(n/1e3)}K`:`${n}`}var Zu=V(()=>{"use strict"});function ba(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var gg=V(()=>{"use strict"});import{posix as XI}from"path";import ZI from"strip-ansi";function yt(n){return ZI(n).replace(ex,"")}function Pe(n){return yt(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function ns(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return ox(t);case"agent_thought_chunk":case"agent_thought":return ax(t);case"user_message_chunk":return dx(t);case"prompt_received":return cx(t);case"tool_call":return lx(t,e);case"tool_call_update":return mx(t,e);case"plan":return wx(t);case"current_mode_update":return bx(t);case"current_model_update":return vx(t);case"turn_complete":return Sx(t);case"usage_update":return ix(t);case"available_commands_update":return sx(t);case"available_modes_update":return rx(t);case"session_info_update":return nx(t);case"config_option_update":return tx(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function tx(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];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}:{}})}t.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:t}}function nx(n){let e=dt(n,"title"),t=e!==void 0?Pe(e):void 0,s=n._meta,r,i;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let d=a.pendingAgentSwap;typeof d=="string"?i=d:d===null&&(i=null)}}}if(t===void 0&&r===void 0&&i===void 0)return null;let o={kind:"session-info"};return t!==void 0&&(o.title=t),r!==void 0&&(o.agentId=r),i!==void 0&&(o.pendingAgentSwap=i),o}function ic(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Pe(r)};typeof s.description=="string"&&(i.description=Pe(s.description)),e.push(i)}return e}function sx(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:ic(e)}:null}function rx(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];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:Pe(r.id)};typeof r.name=="string"&&(i.name=Pe(r.name)),typeof r.description=="string"&&(i.description=Pe(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function ix(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function ox(n){let e=va(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ba(n)}}function ax(n){let e=typeof n.text=="string"?yt(n.text):va(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ba(n)}}function dx(n){let e=n._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 t=va(n.content);return t===null?null:{kind:"user-text",text:t}}function cx(n){let e=kx(n.prompt);return e===null?null:{kind:"user-text",text:e}}function bg(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function yg(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function oc(n){let e=n.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=yg(r.oldText),o=yg(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 t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,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 vg(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:yt(t)}function lx(n,e={}){let t=dt(n,"toolCallId")??dt(n,"id");if(!t)return null;let s=dt(n,"title")??dt(n,"name")??dt(n,"label")??"tool call",r=dt(n,"name")??dt(n,"title");if(bg(r)){let h=vg(n);if(h!==null){let m=dt(n,"status"),y={kind:"exit-plan-mode",toolCallId:t,plan:h};return m!==void 0&&(y.status=m),y}}let i=Ig(Pe(s),n,e),o=dt(n,"status"),a=dt(n,"kind"),c={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=oc(n);d!==null&&(c.editDiff=d);let l=kg(n);l!==void 0&&(c.detail=l);let u=ef(n);u!==void 0&&(c.detailFull=u);let f=Sg(n);f!==void 0&&(c.locations=f);let p=ba(n);return p!==void 0&&(c.workerTaskId=p),c}function Sg(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];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)),t.push(i)}return t.length>0?t:void 0}function kg(n){let e=ef(n);if(e===void 0)return;let t=Pe(e),s=n.rawInput;return s&&typeof s.command=="string"?px(t,wg):hx(t,wg)}function ef(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return yt(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return at(Pe(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return at(Pe(s))}}}function fx(n){for(let e of ux)if(n.startsWith(e))return!0;return!1}function Ig(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return at(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;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===`/${n}`||o.endsWith(`/${n}`)||o===n))return at(o)}return fx(n)?at(`/${n}`):t.cwd&&t.cwd.length>0?at(XI.resolve(t.cwd,n)):n}function px(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function hx(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function mx(n,e={}){let t=dt(n,"toolCallId")??dt(n,"id");if(!t)return null;let s=dt(n,"title"),r=s!==void 0?Ig(Pe(s),n,e):void 0,i=dt(n,"status"),o=oc(n),a=kg(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=dt(n,"name")??s;if(bg(d)){let h={kind:"exit-plan-mode",toolCallId:t},m=vg(n);return m!==null&&(h.plan=m),i!==void 0&&(h.status=i),h}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=ef(n);u!==void 0&&(l.detailFull=u);let f=Sg(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let h=gx(n);h!==null&&(l.errorText=h),yx(n,h)&&(l.upstreamInterrupted=!0)}let p=ba(n);return p!==void 0&&(l.workerTaskId=p),l}function gx(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=va(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return yt(s)}return null}function yx(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function wx(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Pe(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),t.push(o)}return{kind:"plan",entries:t}}function bx(n){let e=dt(n,"currentModeId")??dt(n,"currentMode")??dt(n,"mode");return e?{kind:"mode-changed",mode:Pe(e)}:null}function vx(n){let e=dt(n,"currentModel")??dt(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.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:Pe(e),...s&&s.length>0?{availableModels:s}:{}}}function Sx(n){let e=dt(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function va(n){if(typeof n=="string")return yt(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?yt(e.text):null}function kx(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=va(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function dt(n,e){let t=n[e];return typeof t=="string"?t:void 0}var ex,wg,ux,or=V(()=>{"use strict";ve();gg();ex=/[\x00-\x08\x0b-\x1f\x7f]/g;wg=64;ux=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function no(n){let e=new Map,t=new Map;for(let r of n){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=xx(o);if(d.length===0)continue;let l=d;if(c!==void 0){let u=e.get(c)??[],f=[];for(let p of d)u.some(h=>h.path===p.path&&h.oldText===p.oldText&&h.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)Ix(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function so(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Ix(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function xx(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.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=oc(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var ac=V(()=>{"use strict";or()});function ss(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.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:j.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.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)=>{n.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}var ao=V(()=>{"use strict";Ft()});import{spawn as zA}from"child_process";import{setTimeout as KA}from"timers/promises";async function uy(){let n=await Cs();if(n&&Fn(n.pid))return`http://127.0.0.1:${n.loopbackPort}/v1/health`}async function JA(n){let e=await zr(n,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===ir(n)?"match":"mismatch":"missing"}async function cr(n){let e=await JA(n);if(e!=="match"){if(e==="mismatch"){let t=Qn();throw new Error(`config changed since daemon started \u2014 run \`${t} daemon restart\` to apply.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
102
+ `),kc(),await Ic(n)}}async function Sc(n){let e=await uy();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function zr(n,e=1e3){let t=await uy();if(t)try{let s=await fetch(t,{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 kc(){let n=process.argv[1];if(!n)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");zA(process.execPath,[n,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Ic(n,e=15e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Sc(n))return;await KA(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Kr=V(()=>{"use strict";Qo();wa();Oi()});import*as fy from"fs";import*as uo from"fs/promises";async function fo(n,e,t){let s=VA(e),r;try{r=await uo.stat(n)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${t} (${n})
103
+ `),process.exit(1);return}throw c}let i=await YA(n,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${n} --
104
+ `);let o=!1,a=fy.watch(n,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await uo.stat(n);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await uo.open(n,"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 YA(n,e,t){if(t<=0||e===0)return e;let s=64*1024,r=await uo.open(n,"r");try{let i=e,o="",a=0;for(;i>0&&a<=t;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
105
105
  `).slice(-t-1);process.stdout.write(d.join(`
106
106
  `)),o.endsWith(`
107
107
  `)||process.stdout.write(`
108
- `)}finally{await r.close()}return e}function Ic(n){let e=new Set(["--tail","-n"]),t,s=[],r=0;for(;r<n.length;){let i=n[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<n.length){let o=n[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(t===void 0){t=i,r+=1;continue}s.push(i),r+=1}return{name:t,rest:s}}function WA(n){let e=50,t=!1,s=0;for(;s<n.length;){let r=n[s];if(r==="--tail"||r==="-n"){let i=n[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
108
+ `)}finally{await r.close()}return e}function xc(n){let e=new Set(["--tail","-n"]),t,s=[],r=0;for(;r<n.length;){let i=n[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<n.length){let o=n[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(t===void 0){t=i,r+=1;continue}s.push(i),r+=1}return{name:t,rest:s}}function VA(n){let e=50,t=!1,s=0;for(;s<n.length;){let r=n[s];if(r==="--tail"||r==="-n"){let i=n[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
109
109
  `),process.exit(2)),e=o,s+=2;continue}if(r==="--follow"||r==="-f"){t=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
110
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var Ia=V(()=>{"use strict"});import{WebSocket as JA}from"ws";async function Wr(n,e,t=YA){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=Go(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 JA(n,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new cf(n,Date.now()-a))},t),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var YA,cf,xa=V(()=>{"use strict";Xo();YA=1e4,cf=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}}});import*as xc from"fs/promises";function VA(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function fo(){let n=await xs();if(n&&Fn(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await xe();return my(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function my(n,e,t){return`${t?"https":"http"}://${VA(n)}:${e}`}async function Fe(n,e={}){let t=await Er(),s=await fo(),r=n.startsWith("http")?n:`${s}${n}`,i={Authorization:`Bearer ${t}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
110
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:t}}var xa=V(()=>{"use strict"});import{WebSocket as XA}from"ws";async function Jr(n,e,t=ZA){let s={};try{let r=new URL(n);if(r.protocol==="wss:"){let i=Xo(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 XA(n,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new lf(n,Date.now()-a))},t),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var ZA,lf,Aa=V(()=>{"use strict";Zo();ZA=1e4,lf=class extends Error{url;elapsedMs;constructor(e,t){super(`hydra-acp: websocket connect to ${e} timed out after ${t}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=t}}});import*as Ac from"fs/promises";function eC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"?"127.0.0.1":n}async function ho(){let n=await Cs();if(n&&Fn(n.pid))return`http://127.0.0.1:${n.loopbackPort}`;let e=await xe();return by(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function by(n,e,t){return`${t?"https":"http"}://${eC(n)}:${e}`}async function Fe(n,e={}){let t=await _r(),s=await ho(),r=n.startsWith("http")?n:`${s}${n}`,i={Authorization:`Bearer ${t}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
111
111
  `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let u=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(u=p)}let f=e.errorPrefix??"Daemon returned";process.stderr.write(`${f} ${u}
112
- `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function po(n){let e;n instanceof Date?e=n.getTime():typeof n=="string"?e=Date.parse(n):e=n;let t=Math.max(0,Date.now()-e),s=Math.floor(t/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 Ac(n,e){let t=e!=="agent",s=t?[]:void 0,r=[],i={},o=!0,a=0;for(;a<n.length;){let c=n[a];if(c==="--command"){let d=n[a+1];d===void 0&&(process.stderr.write(`--command requires a value
113
- `),process.exit(2)),s=t?QA(d):d,a+=2;continue}if(c==="--args"){let d=n[a+1];d===void 0&&(process.stderr.write(`--args requires a value
112
+ `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function mo(n){let e;n instanceof Date?e=n.getTime():typeof n=="string"?e=Date.parse(n):e=n;let t=Math.max(0,Date.now()-e),s=Math.floor(t/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 Cc(n,e){let t=e!=="agent",s=t?[]:void 0,r=[],i={},o=!0,a=0;for(;a<n.length;){let c=n[a];if(c==="--command"){let d=n[a+1];d===void 0&&(process.stderr.write(`--command requires a value
113
+ `),process.exit(2)),s=t?tC(d):d,a+=2;continue}if(c==="--args"){let d=n[a+1];d===void 0&&(process.stderr.write(`--args requires a value
114
114
  `),process.exit(2)),r=d.split(",").filter(l=>l.length>0),a+=2;continue}if(c==="--env"){let d=n[a+1];d===void 0&&(process.stderr.write(`--env requires KEY=VALUE
115
115
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
116
116
  `),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}
117
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function QA(n){return n.split(/\s+/).filter(e=>e.length>0)}async function ho(){let n=await xc.readFile(L.config(),"utf8");return JSON.parse(n)}async function lf(n){await xc.writeFile(L.config(),JSON.stringify(n,null,2)+`
118
- `,{encoding:"utf8",mode:384})}var dr=V(()=>{"use strict";Qe();ks();ve();$i();xa()});async function ln(n,e={},t=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()},t);try{return await s(n,{...e,signal:r.signal})}catch(c){throw o?new uf(n,t):c}finally{clearTimeout(a)}}async function ss(n,e={},t=fetch){let s=new URL(`${n.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 ln(s.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"warm",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function gy(n,e=fetch){let t=await ln(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 ln(`${n.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n.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 zr(n,e=fetch){let t=await ln(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 Cc(n,e,t={},s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},18e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function rs(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function yy(n,e,t,s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function wy(n,e,t,s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function by(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);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 vy(n,e,t={},s=fetch){let r={q:e};t.sessionIds&&t.sessionIds.length>0&&(r.sessionIds=t.sessionIds);let i=await ln(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Sy(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Rc(n,e){let t=n.filter(i=>i.cwd===e);if(t.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...t].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var uf,Aa=V(()=>{"use strict";uf=class extends Error{constructor(t,s){super(`daemon did not respond within ${s}ms (${t})`);this.url=t;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function ff(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function ky(n,e){let t=n??"?",s=ff(e);return s?`${t}${GA}${s}`:t}function Iy(n){return n??"?"}function xy(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:pf(e,t)}function pf(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var GA,hf=V(()=>{"use strict";GA="\u2022"});function Ay(n){let e=n.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,s=[];for(let r of e){if(!Ec.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Ec.join(", ")})`);if(t.has(r))throw new Error(`--columns: duplicate column "${r}"`);t.add(r),s.push(r)}return s}function yo(n,e=Date.now()){return{session:ft(n.sessionId),upstream:eC(n.upstreamSessionId,n.importedFromMachine),host:n.importedFromMachine??"-",state:tC(n.status,n.busy,n.awaitingInput,ZA(n.compactionState),n.forkSynthesisState),agent:Iy(n.agentId),model:ff(n.currentModel)??"-",age:nC(n.updatedAt,e),title:n.title??"-",cwd:at(n.cwd),cost:xy(n.currentUsage)}}function ZA(n){if(n==null||typeof n!="object")return!1;let e=n.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function eC(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function tC(n,e,t,s,r){return n==="cold"?"COLD":t?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function wo(n,e={}){let t=e.columns??mo,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 t)s[r]=sC(go[r],n.map(i=>i[r]));return s}function nC(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let s=Math.max(0,e-t),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 sC(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function cr(n,e,t,s={}){let r=s.columns??mo,i=s.cwdMaxWidth??XA,o=v=>v==="age"?n[v].padStart(e[v]):n[v].padEnd(e[v]);if(t===void 0)return r.map((S,x)=>x===r.length-1?n[S]:o(S)).join(Tc);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>mf.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(Tc);return v.length>t?v.slice(0,t):v}let d=r.filter(v=>!mf.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=t-d-l*Tc.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(x,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,x)=>{if(v==="cwd")return Ca(n[v],S).padEnd(S);let T=rC(n[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>mf.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(Tc);return b.length>t?b.slice(0,t):b}function rC(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function Ca(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),s=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-s)}var Ec,mo,mf,go,Tc,XA,Pc=V(()=>{"use strict";hf();ve();Xn();Ec=["session","upstream","host","state","agent","model","age","cwd","title","cost"],mo=["session","state","age","cwd","title","agent","cost"],mf=new Set(["cwd","title"]),go={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Tc=" ",XA=32});import{spawn as hC}from"child_process";import{Writable as mC}from"stream";function Mc(n={}){let e=n.isTTY??process.stdout.isTTY===!0;if(n.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let t=n.env??process.env,s=gC(t);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=n.spawn??hC,i={...t};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}
119
- `)});let c=new mC({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
120
- `)});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 gC(n){let e=n.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let t=n.PAGER;return t!==void 0?t.length===0?null:t:"less"}var gf=V(()=>{"use strict"});import yC from"chalk";import{highlight as wC,supportsLanguage as _c}from"cli-highlight";import Fc from"string-width";function lr(n,e={}){switch(n.kind){case"user-text":{let t=yf(n.text,"\u258E ","user",void 0,n.sentBy,!0);if(n.attachments&&n.attachments.length>0)for(let s of n.attachments)t.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return t}case"agent-text":return yf(n.text," ","agent");case"agent-thought":return yf(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return UC(n,e.maxPlanItems??DC);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${n.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 wf(n,e){return bo(n,e).styled}function bo(n,e){let t=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<n.length;){let f=n[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&n[u+1]==="*"){let p=n.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=n.slice(u+2,p),m=bo(h,e),y=c;a+=`^+${m.styled}${r}`;for(let b of m.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=n.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=n.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${t}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=n.indexOf("]",u+1);if(p!==-1&&n[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<n.length;){let b=n[y];if(b==="\\"&&y+1<n.length){y+=2;continue}if(b==="(")m+=1;else if(b===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=n.slice(u+1,p),y=n.slice(p+2,h),b=bo(m,e),v=c,S=y.startsWith("file://"),x=bC.test(y),T=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(y),E=!S&&!x&&!T;S||E?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let $ of b.links)l.push({start:v+$.start,end:v+$.end,url:$.url});c+=b.cleanLength,(S||x||E)&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function vC(n){switch(n){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 By(n){switch(n){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 Ny(n,e){let{proseStyle:t,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=n.replace(/^\s+/,"").split(`
121
- `),l=!1,u="",f=[],p=i!==" ",h=(b,v,S=" ",x,T)=>{let E={prefix:S,body:b,bodyStyle:v};r!==void 0&&(E.prefixStyle=r),x&&x.length>0&&(E.links=x),T&&(E.ansi=!0),c.push(E)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=Hy(u,f);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of f)h(b.replace(/\^/g,"^^"),t);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let D=x[1].length,B=x[2]??"",O=s?D===1?"heading-1":D===2?"heading-2":"heading-3":t,K=s?By(O):o;h(wf(B,K),O,m());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&SC(T)&&Ra(v).length===Ra(T).length){let D=Ra(v),B=[],O=b+2;for(;O<d.length&&d[O].includes("|");)B.push(Ra(d[O])),O++;let K=TC(D,B,a);for(let X of K)r!==void 0&&(X.prefixStyle=r),c.push(X);b=O-1;continue}let E=v.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let D=E[1]??"",B=E[2]??"",O=bo(B,o),K=D.length+2,X=O.links.map(Z=>({start:Z.start+K,end:Z.end+K,url:Z.url}));h(`${D}\u2022 ${O.styled}`,t,m(),X,O.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let D=$[1]??"",B=$[2]??"",O=$[3]??"",K=bo(O,o),X=D.length+B.length+2,Z=K.links.map(Q=>({start:Q.start+X,end:Q.end+X,url:Q.url}));h(`${D}${B}. ${K.styled}`,t,m(),Z,K.ansi);continue}let N=v.trim()==="",M=bo(v,o);h(M.styled,t,N?" ":m(),M.links,M.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function ur(n,e){return Ny(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function vo(n){return Ny(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Ra(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],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){t.push(s.trim()),s="";continue}s+=o}return t.push(s.trim()),t}function SC(n){if(!n.includes("|"))return!1;let e=Ra(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function $c(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Fc(e)}function xC(n){let e=[],t=0;for(;t<n.length;){let s=n[t];if(s===" "||s===" "){let o=t;for(;o<n.length&&(n[o]===" "||n[o]===" ");)o++;let a=n.slice(t,o);e.push({text:a,isWS:!0,width:Fc(a)}),t=o;continue}let r="",i=t;for(;i<n.length;){let o=n[i];if(o===" "||o===" ")break;if(n[i]==="*"&&n[i+1]==="*"){let a=n.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=n.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=n.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=n.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:$c(r)}),t=i}return e}function AC(n,e){let t=[],s="",r=0;for(let i of n){let o=Fc(i);r>0&&r+o>e?(t.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&t.push(s),t}function CC(n,e){if(e<=0)return n.length===0?[""]:[n.map(o=>o.text).join("")];let t=[],s="",r=0,i=()=>{t.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of n){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("`"))t.push(o.text);else{let c=AC(o.text,e);for(let l=0;l<c.length-1;l++)t.push(c[l]);let d=c[c.length-1]??"";s=d,r=Fc(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||t.length===0)&&i(),t}function RC(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let r=n.map(l=>Math.min(l,Dy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=n.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<t;f++){let p=n[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function TC(n,e,t){let s=n.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=$c(n[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=$c(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(t!==void 0){let d=Math.max(s*Dy,t-kC-(s-1)*IC);i=RC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",b=i[m],v=CC(xC(y),b);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let b=0;b<s;b++){let v=f[b][m]??"",S=i[b],x=$c(v),T=wf(v,u);y.push(T+" ".repeat(Math.max(0,S-x)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(n,"heading-3",By("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function Hy(n,e){if(n.length===0||!_c(n))return e.map(r=>({body:r,ansi:!1}));let t;try{t=wC(e.join(`
122
- `),{language:n,theme:EC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}t=t.replace(/\x1b\[39m/g,"\x1B[37m");let s=t.split(`
123
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function MC(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return _c("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return _c("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let s=e.slice(t),r=PC[s];return r&&_c(r)?r:""}function yf(n,e,t,s,r,i){let o=n.replace(/^\s+/,"").split(`
124
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??t,body:c,bodyStyle:t};i&&(d.fillRow=!0),a.push(d)}return a}function _C(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function is(n){let e=Math.floor(n/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;if(t<60)return s===0?`${t}m`:`${t}m ${s}s`;let r=Math.floor(t/60),i=t%60;return i===0?`${r}h`:`${r}h ${i}m`}function Uy(n){if(n.length<=4096&&n.split(`
117
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function tC(n){return n.split(/\s+/).filter(e=>e.length>0)}async function go(){let n=await Ac.readFile(L.config(),"utf8");return JSON.parse(n)}async function uf(n){await Ac.writeFile(L.config(),JSON.stringify(n,null,2)+`
118
+ `,{encoding:"utf8",mode:384})}var lr=V(()=>{"use strict";Qe();xs();ve();Oi();Aa()});async function ln(n,e={},t=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()},t);try{return await s(n,{...e,signal:r.signal})}catch(c){throw o?new ff(n,t):c}finally{clearTimeout(a)}}async function is(n,e={},t=fetch){let s=new URL(`${n.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 ln(s.toString(),{headers:{Authorization:`Bearer ${n.token}`},signal:e.signal},8e3,t);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"warm",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState,forkSynthesisState:o.forkSynthesisState})):[]}async function vy(n,e=fetch){let t=await ln(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 ln(`${n.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Yr(n,e=fetch){let t=await ln(`${n.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${n.token}`}},8e3,e);if(!t.ok)throw new Error(`daemon returned HTTP ${t.status}`);let s=await t.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 Rc(n,e,t={},s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify(t)},18e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function os(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function Sy(n,e,t,s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function ky(n,e,t,s=fetch){let r=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:t})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Iy(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,t);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 xy(n,e,t={},s=fetch){let r={q:e};t.sessionIds&&t.sessionIds.length>0&&(r.sessionIds=t.sessionIds);let i=await ln(`${n.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${n.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 Ay(n,e,t=fetch){let s=await ln(`${n.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${n.token}`}},8e3,t);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Tc(n,e){let t=n.filter(i=>i.cwd===e);if(t.length===0)return null;let s=i=>i.status==="warm"?1:0;return[...t].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var ff,Ca=V(()=>{"use strict";ff=class extends Error{constructor(t,s){super(`daemon did not respond within ${s}ms (${t})`);this.url=t;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function pf(n){if(!n)return;let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}function Cy(n,e){let t=n??"?",s=pf(e);return s?`${t}${nC}${s}`:t}function Ry(n){return n??"?"}function Ty(n){if(!n||typeof n.costAmount!="number")return"";let{costAmount:e,costCurrency:t}=n;return t===void 0||t==="USD"?`$${Math.round(e)}`:hf(e,t)}function hf(n,e){return`${e==="USD"||e===void 0?"$":""}${n.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var nC,mf=V(()=>{"use strict";nC="\u2022"});function Ey(n){let e=n.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let t=new Set,s=[];for(let r of e){if(!Pc.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${Pc.join(", ")})`);if(t.has(r))throw new Error(`--columns: duplicate column "${r}"`);t.add(r),s.push(r)}return s}function bo(n,e=Date.now()){return{session:ft(n.sessionId),upstream:iC(n.upstreamSessionId,n.importedFromMachine),host:n.importedFromMachine??"-",state:oC(n.status,n.busy,n.awaitingInput,rC(n.compactionState),n.forkSynthesisState),agent:Ry(n.agentId),model:pf(n.currentModel)??"-",age:aC(n.updatedAt,e),title:n.title??"-",cwd:at(n.cwd),cost:Ty(n.currentUsage)}}function rC(n){if(n==null||typeof n!="object")return!1;let e=n.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function iC(n,e){return n&&n.length>0?n:e&&e.length>0?`\u2190 ${e}`:"-"}function oC(n,e,t,s,r){return n==="cold"?"COLD":t?r==="failed"?"WARM\u25E6\u26A0":"WARM\u25E6":e?r==="failed"?"WARM\u2022\u26A0":"WARM\u2022":r==="running"?"WARM\u2728":r==="failed"?"WARM\u26A0":s?"WARM\u27F3":"WARM"}function vo(n,e={}){let t=e.columns??yo,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 t)s[r]=dC(wo[r],n.map(i=>i[r]));return s}function aC(n,e){if(!n)return"?";let t=Date.parse(n);if(Number.isNaN(t))return"?";let s=Math.max(0,e-t),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 dC(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function ur(n,e,t,s={}){let r=s.columns??yo,i=s.cwdMaxWidth??sC,o=v=>v==="age"?n[v].padStart(e[v]):n[v].padEnd(e[v]);if(t===void 0)return r.map((S,x)=>x===r.length-1?n[S]:o(S)).join(Ec);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>gf.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(Ec);return v.length>t?v.slice(0,t):v}let d=r.filter(v=>!gf.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=t-d-l*Ec.length;u<0&&(u=0);let f=new Map,p=u;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(x,Math.max(0,p-1));f.set(S,T),p=Math.max(0,p-T)}f.set(c,Math.max(0,p));let h=r.length-1,m=(v,S,x)=>{if(v==="cwd")return Ra(n[v],S).padEnd(S);let T=cC(n[v],S);return x?T:T.padEnd(S)},w=r.map((v,S)=>gf.has(v)?m(v,f.get(S)??0,S===h):o(v)).join(Ec);return w.length>t?w.slice(0,t):w}function cC(n,e){return e<=0?"":n.length<=e?n:e===1?"\u2026":n.slice(0,e-1)+"\u2026"}function Ra(n,e){if(e<=0)return"";if(n.length<=e)return n;if(e===1)return"\u2026";let t=Math.ceil((e-1)/2),s=e-1-t;return n.slice(0,t)+"\u2026"+n.slice(n.length-s)}var Pc,yo,gf,wo,Ec,sC,Mc=V(()=>{"use strict";mf();ve();Zn();Pc=["session","upstream","host","state","agent","model","age","cwd","title","cost"],yo=["session","state","age","cwd","title","agent","cost"],gf=new Set(["cwd","title"]),wo={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},Ec=" ",sC=32});import{spawn as bC}from"child_process";import{Writable as vC}from"stream";function _c(n={}){let e=n.isTTY??process.stdout.isTTY===!0;if(n.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let t=n.env??process.env,s=SC(t);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=n.spawn??bC,i={...t};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}
119
+ `)});let c=new vC({write(l,u,f){if(!a.writable){f();return}a.write(l,h=>{if(h&&h.code!=="EPIPE"){f(h);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
120
+ `)});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 SC(n){let e=n.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let t=n.PAGER;return t!==void 0?t.length===0?null:t:"less"}var yf=V(()=>{"use strict"});import kC from"chalk";import{highlight as IC,supportsLanguage as $c}from"cli-highlight";import Oc from"string-width";function fr(n,e={}){switch(n.kind){case"user-text":{let t=wf(n.text,"\u258E ","user",void 0,n.sentBy,!0);if(n.attachments&&n.attachments.length>0)for(let s of n.attachments)t.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return t}case"agent-text":return wf(n.text," ","agent");case"agent-thought":return wf(n.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return KC(n,e.maxPlanItems??WC);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${n.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 bf(n,e){return So(n,e).styled}function So(n,e){let t=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<n.length;){let f=n[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&n[u+1]==="*"){let p=n.indexOf("**",u+2);if(p!==-1&&p>u+2){let h=n.slice(u+2,p),m=So(h,e),y=c;a+=`^+${m.styled}${r}`;for(let w of m.links)l.push({start:y+w.start,end:y+w.end,url:w.url});c+=m.cleanLength,m.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=n.indexOf("`",u+1);if(p!==-1&&p>u+1){let h=n.slice(u+1,p),m=h.replace(/\^/g,"^^");a+=`${t}${m}${s}`,c+=h.length,u=p+1;continue}}if(f==="["){let p=n.indexOf("]",u+1);if(p!==-1&&n[p+1]==="("&&p>u+1){let h=-1;{let m=1,y=p+2;for(;y<n.length;){let w=n[y];if(w==="\\"&&y+1<n.length){y+=2;continue}if(w==="(")m+=1;else if(w===")"&&(m-=1,m===0)){h=y;break}y+=1}}if(h!==-1&&h>p+2){let m=n.slice(u+1,p),y=n.slice(p+2,h),w=So(m,e),v=c,S=y.startsWith("file://"),x=xC.test(y),T=/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(y),E=!S&&!x&&!T;S||E?a+=`${i}${w.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${w.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let $ of w.links)l.push({start:v+$.start,end:v+$.end,url:$.url});c+=w.cleanLength,(S||x||E)&&l.push({start:v,end:c,url:y}),u=h+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function AC(n){switch(n){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function Uy(n){switch(n){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 jy(n,e){let{proseStyle:t,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=n.replace(/^\s+/,"").split(`
121
+ `),l=!1,u="",f=[],p=i!==" ",h=(w,v,S=" ",x,T)=>{let E={prefix:S,body:w,bodyStyle:v};r!==void 0&&(E.prefixStyle=r),x&&x.length>0&&(E.links=x),T&&(E.ansi=!0),c.push(E)},m=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let w=Wy(u,f);for(let v of w){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 w of f)h(w.replace(/\^/g,"^^"),t);f=[],u=""}};for(let w=0;w<d.length;w++){let v=d[w],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let D=x[1].length,B=x[2]??"",O=s?D===1?"heading-1":D===2?"heading-2":"heading-3":t,K=s?Uy(O):o;h(bf(B,K),O,m());continue}let T=d[w+1];if(v.includes("|")&&T!==void 0&&CC(T)&&Ta(v).length===Ta(T).length){let D=Ta(v),B=[],O=w+2;for(;O<d.length&&d[O].includes("|");)B.push(Ta(d[O])),O++;let K=$C(D,B,a);for(let X of K)r!==void 0&&(X.prefixStyle=r),c.push(X);w=O-1;continue}let E=v.match(/^(\s*)[-*+]\s+(.*)$/);if(E){let D=E[1]??"",B=E[2]??"",O=So(B,o),K=D.length+2,X=O.links.map(Z=>({start:Z.start+K,end:Z.end+K,url:Z.url}));h(`${D}\u2022 ${O.styled}`,t,m(),X,O.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let D=$[1]??"",B=$[2]??"",O=$[3]??"",K=So(O,o),X=D.length+B.length+2,Z=K.links.map(Q=>({start:Q.start+X,end:Q.end+X,url:Q.url}));h(`${D}${B}. ${K.styled}`,t,m(),Z,K.ansi);continue}let N=v.trim()==="",M=So(v,o);h(M.styled,t,N?" ":m(),M.links,M.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function pr(n,e){return jy(n,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function ko(n){return jy(n,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function Ta(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let t=[],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){t.push(s.trim()),s="";continue}s+=o}return t.push(s.trim()),t}function CC(n){if(!n.includes("|"))return!1;let e=Ta(n);return e.length===0?!1:e.every(t=>/^:?-+:?$/.test(t))}function Fc(n){let e=n.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Oc(e)}function EC(n){let e=[],t=0;for(;t<n.length;){let s=n[t];if(s===" "||s===" "){let o=t;for(;o<n.length&&(n[o]===" "||n[o]===" ");)o++;let a=n.slice(t,o);e.push({text:a,isWS:!0,width:Oc(a)}),t=o;continue}let r="",i=t;for(;i<n.length;){let o=n[i];if(o===" "||o===" ")break;if(n[i]==="*"&&n[i+1]==="*"){let a=n.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=n.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=n.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=n.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:Fc(r)}),t=i}return e}function PC(n,e){let t=[],s="",r=0;for(let i of n){let o=Oc(i);r>0&&r+o>e?(t.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&t.push(s),t}function MC(n,e){if(e<=0)return n.length===0?[""]:[n.map(o=>o.text).join("")];let t=[],s="",r=0,i=()=>{t.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of n){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("`"))t.push(o.text);else{let c=PC(o.text,e);for(let l=0;l<c.length-1;l++)t.push(c[l]);let d=c[c.length-1]??"";s=d,r=Oc(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||t.length===0)&&i(),t}function _C(n,e){let t=n.length;if(n.reduce((l,u)=>l+u,0)<=e)return n.slice();let r=n.map(l=>Math.min(l,qy)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=n.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<t;f++){let p=n[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function $C(n,e,t){let s=n.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Fc(n[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Fc(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(t!==void 0){let d=Math.max(s*qy,t-RC-(s-1)*TC);i=_C(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let m=0;m<s;m++){let y=d[m]??"",w=i[m],v=MC(EC(y),w);f.push(v),v.length>p&&(p=v.length)}let h=[];for(let m=0;m<p;m++){let y=[];for(let w=0;w<s;w++){let v=f[w][m]??"",S=i[w],x=Fc(v),T=bf(v,u);y.push(T+" ".repeat(Math.max(0,S-x)))}h.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return h},a=[];a.push(...o(n,"heading-3",Uy("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function Wy(n,e){if(n.length===0||!$c(n))return e.map(r=>({body:r,ansi:!1}));let t;try{t=IC(e.join(`
122
+ `),{language:n,theme:FC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}t=t.replace(/\x1b\[39m/g,"\x1B[37m");let s=t.split(`
123
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function LC(n){if(!n)return"";let e=n.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return $c("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return $c("makefile")?"makefile":"";let t=e.lastIndexOf(".");if(t<0)return"";let s=e.slice(t),r=OC[s];return r&&$c(r)?r:""}function wf(n,e,t,s,r,i){let o=n.replace(/^\s+/,"").split(`
124
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??t,body:c,bodyStyle:t};i&&(d.fillRow=!0),a.push(d)}return a}function BC(n){return n<1024?`${n} B`:n<1024*1024?`${Math.round(n/1024)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function as(n){let e=Math.floor(n/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),s=e%60;if(t<60)return s===0?`${t}m`:`${t}m ${s}s`;let r=Math.floor(t/60),i=t%60;return i===0?`${r}h`:`${r}h ${i}m`}function zy(n){if(n.length<=4096&&n.split(`
125
125
  `).length<=40)return{text:n,truncated:!1};let s=n.slice(0,4096),r=n.length>4096,i=s.split(`
126
126
  `);return i.length>40&&(s=i.slice(0,40).join(`
127
- `),r=!0),{text:s,truncated:r}}function Ta(n,e=Date.now()){let t=n.initialTitle,s=n.latestTitle,r=t.toLowerCase(),i=s.toLowerCase(),o;s===t||i.includes(r)?o=s:r.includes(i)?o=t:o=`${t} \xB7 ${s}`;let a=[];if(n.detail){let l=n.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||n.detailFull!==void 0&&o.includes(n.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=n.locations?.[0]?.path??n.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(n.startedAt!==void 0){let l=n.endedAt??e;o=`${o} \xB7 ${is(l-n.startedAt)}`}let c={prefix:` ${LC(n.status)} `,prefixStyle:BC(n.status),body:o,bodyStyle:jC(n.status)};a.length>0&&(c.links=a);let d=[c];return n.status==="failed"&&n.errorText&&d.push({prefix:" ",body:Pe(n.errorText),bodyStyle:"tool-status-fail"}),d}function jy(n){if(n.editDiff!==void 0)return[];let e=[],t=n.detailFull??n.detail;if(t)for(let s of t.split(`
127
+ `),r=!0),{text:s,truncated:r}}function Ea(n,e=Date.now()){let t=n.initialTitle,s=n.latestTitle,r=t.toLowerCase(),i=s.toLowerCase(),o;s===t||i.includes(r)?o=s:r.includes(i)?o=t:o=`${t} \xB7 ${s}`;let a=[];if(n.detail){let l=n.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||n.detailFull!==void 0&&o.includes(n.detailFull);if(l.length>0&&!p){let h=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let m=n.locations?.[0]?.path??n.detailFull??"";(m.startsWith("/")||m.startsWith("~"))&&a.push({start:h,end:h+l.length,url:m})}}}if(n.startedAt!==void 0){let l=n.endedAt??e;o=`${o} \xB7 ${as(l-n.startedAt)}`}let c={prefix:` ${UC(n.status)} `,prefixStyle:jC(n.status),body:o,bodyStyle:JC(n.status)};a.length>0&&(c.links=a);let d=[c];return n.status==="failed"&&n.errorText&&d.push({prefix:" ",body:Pe(n.errorText),bodyStyle:"tool-status-fail"}),d}function Ky(n){if(n.editDiff!==void 0)return[];let e=[],t=n.detailFull??n.detail;if(t)for(let s of t.split(`
128
128
  `))e.push({prefix:" ",body:Pe(s),bodyStyle:"dim"});if(n.status==="failed"&&n.errorText&&e.push({prefix:" ",body:Pe(n.errorText),bodyStyle:"tool-status-fail"}),n.resultText){let s=n.resultText.split(`
129
- `),r=n.locations?.[0]?.path??n.detailFull??n.detail,i=MC(r);if(i.length>0){let o=Hy(i,s.map(a=>Pe(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:Pe(o),bodyStyle:"dim"});n.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Wy(n){qy=n>=0?n:0}function bf(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let d=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${_C(d)})`}else{let d=FC(n),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 ${Pe(at(n.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return n.path&&s.push(o(!1)),s;if(r)return n.path&&(s.push(o(!0)),s.push(t.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=vf(n,{maxLines:1/0});if(a.length===0)return n.path&&s.push(o(!1)),s;n.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...ur(c)),s.length>0&&s.unshift({body:""}),s}function zy(n){let e=yt(n.oldText).split(`
129
+ `),r=n.locations?.[0]?.path??n.detailFull??n.detail,i=LC(r);if(i.length>0){let o=Wy(i,s.map(a=>Pe(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:Pe(o),bodyStyle:"dim"});n.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Yy(n){Jy=n>=0?n:0}function vf(n,e,t={}){let s=[],r=n.oldRef!==void 0||n.newRef!==void 0,i;if(r){let d=(n.oldRef?.bytes??0)+(n.newRef?.bytes??0);i=` (~${BC(d)})`}else{let d=DC(n),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 ${Pe(at(n.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return n.path&&s.push(o(!1)),s;if(r)return n.path&&(s.push(o(!0)),s.push(t.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=Sf(n,{maxLines:1/0});if(a.length===0)return n.path&&s.push(o(!1)),s;n.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...pr(c)),s.length>0&&s.unshift({body:""}),s}function Vy(n){let e=yt(n.oldText).split(`
130
130
  `),t=yt(n.newText).split(`
131
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),t.length>0&&t[t.length-1]===""&&t.pop(),{oldLines:e,newLines:t}}function FC(n){let{oldLines:e,newLines:t}=zy(n),s=0,r=0;for(let i of Ky(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Ly(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function vf(n,e={}){let t=e.maxLines??$C,s=e.contextLines??qy,{oldLines:r,newLines:i}=zy(n),o=Ky(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(Ly(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(Ly(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=t-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
132
- `)}function Ky(n,e){let t=0,s=Math.min(n.length,e.length);for(;t<s&&n[t]===e[t];)t++;let r=n.length,i=e.length;for(;r>t&&i>t&&n[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<t;a++)o.push({op:"=",text:n[a]});o.push(...OC(n.slice(t,r),e.slice(t,i)));for(let a=r;a<n.length;a++)o.push({op:"=",text:n[a]});return o}function OC(n,e){let t=n.length,s=e.length;if(t===0||s===0){let c=[];for(let d of n)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c--)for(let d=s-1;d>=0;d--)n[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<t&&a<s;)n[o]===e[a]?(i.push({op:"=",text:n[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:n[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<t;)i.push({op:"-",text:n[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function Sf(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function LC(n){switch(n){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 BC(n){switch(n){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 Jy(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...ur(n.plan));let t=n.status;if(t!==void 0){let s=NC(t);s!==null&&e.push(s)}return e}function NC(n){switch(n){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 HC(n,e){let t=n.length;if(e<=0||t<=e)return{start:0,end:t};let s=n.findIndex(d=>(d.status??"pending")==="in_progress"),r=n.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:t-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(t,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function UC(n,e){let t=n.stopped===!0,r=n.amended===!0?"tool-status-cancelled":"tool-status-fail",o=n.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":t?r:"plan",a=n.entries.length,{start:c,end:d}=HC(n.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of n.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=n.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",b=m==="completed"?"plan-done":m==="in_progress"?t?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=wf(v,vC(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function jC(n){switch(n){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 bC,Dy,kC,IC,ct,EC,PC,$C,qy,DC,So=V(()=>{"use strict";ve();rr();bC=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;Dy=6,kC=2,IC=3;ct=new yC.Instance({level:3}),EC={keyword:ct.blueBright,built_in:ct.cyan,type:ct.cyanBright,literal:ct.blue,number:ct.greenBright,string:ct.yellow,regexp:ct.red,comment:ct.gray,function:ct.yellow,title:ct.yellow,class:ct.yellowBright,attr:ct.cyan,attribute:ct.cyan,variable:ct.white,params:ct.white,meta:ct.magenta,symbol:ct.magenta,addition:ct.greenBright,deletion:ct.redBright,section:ct.cyan,tag:ct.cyan,name:ct.cyanBright};PC={".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"};$C=40,qy=Number.POSITIVE_INFINITY;DC=5});import{highlight as qC,supportsLanguage as WC}from"cli-highlight";async function Vy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
131
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),t.length>0&&t[t.length-1]===""&&t.pop(),{oldLines:e,newLines:t}}function DC(n){let{oldLines:e,newLines:t}=Vy(n),s=0,r=0;for(let i of Qy(e,t))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function Hy(n){return n.op==="="?` ${n.text}`:n.op==="-"?`- ${n.text}`:`+ ${n.text}`}function Sf(n,e={}){let t=e.maxLines??NC,s=e.contextLines??Jy,{oldLines:r,newLines:i}=Vy(n),o=Qy(r,i),a=[];if(Number.isFinite(s)){if(!o.some(f=>f.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let f=0;f<o.length;f++)if(o[f].op!=="="){let p=Math.max(0,f-s),h=Math.min(o.length-1,f+s);for(let m=p;m<=h;m++)l[m]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(Hy(o[u])),u++;continue}let f=u;for(;f<o.length&&!l[f];)f++;let p=f-u;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),u=f}}else for(let d of o)a.push(Hy(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=t-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
132
+ `)}function Qy(n,e){let t=0,s=Math.min(n.length,e.length);for(;t<s&&n[t]===e[t];)t++;let r=n.length,i=e.length;for(;r>t&&i>t&&n[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<t;a++)o.push({op:"=",text:n[a]});o.push(...HC(n.slice(t,r),e.slice(t,i)));for(let a=r;a<n.length;a++)o.push({op:"=",text:n[a]});return o}function HC(n,e){let t=n.length,s=e.length;if(t===0||s===0){let c=[];for(let d of n)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c--)for(let d=s-1;d>=0;d--)n[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<t&&a<s;)n[o]===e[a]?(i.push({op:"=",text:n[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:n[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<t;)i.push({op:"-",text:n[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function kf(n){switch(n){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function UC(n){switch(n){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 jC(n){switch(n){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 Gy(n){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...pr(n.plan));let t=n.status;if(t!==void 0){let s=qC(t);s!==null&&e.push(s)}return e}function qC(n){switch(n){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 zC(n,e){let t=n.length;if(e<=0||t<=e)return{start:0,end:t};let s=n.findIndex(d=>(d.status??"pending")==="in_progress"),r=n.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:t-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(t,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function KC(n,e){let t=n.stopped===!0,r=n.amended===!0?"tool-status-cancelled":"tool-status-fail",o=n.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":t?r:"plan",a=n.entries.length,{start:c,end:d}=zC(n.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let m of n.entries)(m.status??"pending")==="completed"&&(p+=1);let h=a-p;u=h===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${h} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let h=n.entries[p];if(!h)continue;let m=h.status??"pending",y=m==="completed"?"[x]":m==="in_progress"?"[~]":"[ ]",w=m==="completed"?"plan-done":m==="in_progress"?t?"plan-pending":"plan":"plan-pending",v=h.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=bf(v,AC(w));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:w})}return f}function JC(n){switch(n){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 xC,qy,RC,TC,ct,FC,OC,NC,Jy,WC,Io=V(()=>{"use strict";ve();or();xC=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/;qy=6,RC=2,TC=3;ct=new kC.Instance({level:3}),FC={keyword:ct.blueBright,built_in:ct.cyan,type:ct.cyanBright,literal:ct.blue,number:ct.greenBright,string:ct.yellow,regexp:ct.red,comment:ct.gray,function:ct.yellow,title:ct.yellow,class:ct.yellowBright,attr:ct.cyan,attribute:ct.cyan,variable:ct.white,params:ct.white,meta:ct.magenta,symbol:ct.magenta,addition:ct.greenBright,deletion:ct.redBright,section:ct.cyan,tag:ct.cyan,name:ct.cyanBright};OC={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};NC=40,Jy=Number.POSITIVE_INFINITY;WC=5});import{highlight as YC,supportsLanguage as VC}from"cli-highlight";async function Zy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
133
133
  `),process.exit(2));let t=e.fold===!0?"?fold=true":"",s=await Fe(`/v1/sessions/${encodeURIComponent(n)}/diff${t}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Fe(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,l;try{l=On(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
134
- `),process.exit(1)}let u=eo(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:to(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
134
+ `),process.exit(1)}let u=no(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:so(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
135
135
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
136
- `);return}let i=Mc({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(kf(r,a)),await i.flush()}function kf(n,e){if(n.length===0)return`No file edits found in this session.
137
- `;let t=[],s=[...n].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=JC(r,e);i!==null&&t.push(i)}return t.length===0?`No file edits found in this session.
138
- `:t.join("")}function zC(n){let e=[];for(let t of n.hunks){let s=vf(t,{maxLines:1/0});KC(s)&&e.push({body:s,oldCount:Yy(t.oldText),newCount:Yy(t.newText)})}return e}function KC(n){if(n.length===0)return!1;for(let e of n.split(`
139
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function JC(n,e){let t=zC(n);if(t.length===0)return null;let s=[];s.push(`diff --hydra a/${n.path} b/${n.path}`),n.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${n.path}`)):(s.push(`--- a/${n.path}`),s.push(`+++ b/${n.path}`));let r=t.length;t.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
136
+ `);return}let i=_c({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(If(r,a)),await i.flush()}function If(n,e){if(n.length===0)return`No file edits found in this session.
137
+ `;let t=[],s=[...n].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=XC(r,e);i!==null&&t.push(i)}return t.length===0?`No file edits found in this session.
138
+ `:t.join("")}function QC(n){let e=[];for(let t of n.hunks){let s=Sf(t,{maxLines:1/0});GC(s)&&e.push({body:s,oldCount:Xy(t.oldText),newCount:Xy(t.newText)})}return e}function GC(n){if(n.length===0)return!1;for(let e of n.split(`
139
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function XC(n,e){let t=QC(n);if(t.length===0)return null;let s=[];s.push(`diff --hydra a/${n.path} b/${n.path}`),n.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${n.path}`)):(s.push(`--- a/${n.path}`),s.push(`+++ b/${n.path}`));let r=t.length;t.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(`
140
140
  `)+`
141
141
 
142
- `;return!e||!WC("diff")?i:qC(i,{language:"diff"})}function Yy(n){if(n.length===0)return 0;let e=n.split(`
143
- `);return e[e.length-1]===""&&e.pop(),e.length}var If=V(()=>{"use strict";dr();Hr();oc();So();gf()});async function Qy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
142
+ `;return!e||!VC("diff")?i:YC(i,{language:"diff"})}function Xy(n){if(n.length===0)return 0;let e=n.split(`
143
+ `);return e[e.length-1]===""&&e.pop(),e.length}var xf=V(()=>{"use strict";lr();qr();ac();Io();yf()});async function ew(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
144
144
  `),process.exit(2));let t=await Fe(`/v1/sessions/${encodeURIComponent(n)}`,{expectStatus:[200,404]}),s=t.status===200?t.body.status:void 0,i=(await Fe(`/v1/sessions/${encodeURIComponent(n)}/export`,{expectStatus:200})).body,o;try{o=On(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
145
- `),process.exit(1)}let a=Cf(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=eo(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:to(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
146
- `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=Mc({disabled:e.noPager===!0});f.stream.write(Oc(a,e.verbose===!0)),f.stream.write(`
147
- `),f.stream.write(kf(d??[],u)),await f.flush();return}process.stdout.write(Oc(a,e.verbose===!0))}function Cf(n,e){let t=n.session,s=n.history,r=Fm(s),i=Mu(s),o=_u(s),a=t.currentUsage,c=Date.parse(t.createdAt),d=Date.parse(t.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:t.sessionId,...t.upstreamSessionId!==void 0?{upstreamSessionId:t.upstreamSessionId}:{},...t.title!==void 0?{title:t.title}:{},cwd:t.cwd,agentId:t.agentId,...t.currentModel!==void 0?{currentModel:t.currentModel}:{},status:e,createdAt:t.createdAt,updatedAt:t.updatedAt,synopsis:t.synopsis??null,summarizedThroughEntry:t.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 Oc(n,e){let t=[],s=a=>a.padEnd(14);t.push(`${s("Session:")}${n.sessionId}`),n.upstreamSessionId&&t.push(`${s("Upstream:")}${n.upstreamSessionId}`),n.title&&t.push(`${s("Title:")}${n.title}`),t.push(`${s("Cwd:")}${n.cwd}`);let r=n.currentModel?` \xB7 ${n.currentModel}`:"";t.push(`${s("Agent:")}${n.agentId}${r}`),t.push(`${s("Status:")}${n.status}`),t.push(`${s("Created:")}${n.createdAt}`),t.push(`${s("Last active:")}${n.updatedAt}`),n.duration.totalMs!==null&&t.push(`${s("Duration:")}${VC(n.duration.totalMs)}`),t.push(`${s("Turns:")}${n.turns}`);let i=[];if(n.cost.amount!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.amount.toFixed(4)}`)}else if(n.cost.cumulative!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.cumulative.toFixed(4)} (cumulative)`)}if(n.cost.inputTokens!==null||n.cost.outputTokens!==null){let a=[];n.cost.inputTokens!==null&&a.push(`${n.cost.inputTokens.toLocaleString()} in`),n.cost.outputTokens!==null&&a.push(`${n.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&t.push(`${s("Cost:")}${i.join(" | ")}`),n.synopsis){t.push(""),t.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(n.synopsis.goal&&t.push(`${a}${c("Goal:")}${n.synopsis.goal}`),n.synopsis.outcome&&t.push(`${a}${c("Outcome:")}${n.synopsis.outcome}`),n.synopsis.rejected_approaches&&n.synopsis.rejected_approaches.length>0){t.push(`${a}${c("Rejected approaches:")}`);for(let d of n.synopsis.rejected_approaches)t.push(`${a} - ${d}`)}if(n.synopsis.open_threads&&n.synopsis.open_threads.length>0){t.push(`${a}${c("Open threads:")}`);for(let d of n.synopsis.open_threads)t.push(`${a} - ${d}`)}if(n.synopsis.files_touched&&n.synopsis.files_touched.length>0){t.push(`${a}${c("Files touched:")}`);for(let d of n.synopsis.files_touched)t.push(`${a} - ${d}`)}if(n.synopsis.tools_used&&n.synopsis.tools_used.length>0){t.push(`${a}${c("Tools used:")}`);for(let d of n.synopsis.tools_used)t.push(`${a} - ${d}`)}}else t.push(""),t.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(n.tools.length>0){t.push("");let a=n.tools.reduce((l,u)=>l+u.count,0);t.push(`Tools (${a} calls):`);let c=e?n.tools:n.tools.slice(0,xf),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)t.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&n.tools.length>xf&&t.push(` ... ${n.tools.length-xf} more (use --verbose to see all)`)}let o=e?n.files:n.files.map(a=>{let c=a.byTool.filter(l=>YC.has(l.name)),d=c.reduce((l,u)=>l+u.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){t.push("");let a=e?"Files touched":"Files edited";t.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Af),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");t.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else t.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Af&&t.push(` ... ${o.length-Af} more (use --verbose to see all)`)}return t.join(`
145
+ `),process.exit(1)}let a=Rf(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=no(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:so(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
146
+ `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=_c({disabled:e.noPager===!0});f.stream.write(Lc(a,e.verbose===!0)),f.stream.write(`
147
+ `),f.stream.write(If(d??[],u)),await f.flush();return}process.stdout.write(Lc(a,e.verbose===!0))}function Rf(n,e){let t=n.session,s=n.history,r=Bm(s),i=_u(s),o=$u(s),a=t.currentUsage,c=Date.parse(t.createdAt),d=Date.parse(t.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:t.sessionId,...t.upstreamSessionId!==void 0?{upstreamSessionId:t.upstreamSessionId}:{},...t.title!==void 0?{title:t.title}:{},cwd:t.cwd,agentId:t.agentId,...t.currentModel!==void 0?{currentModel:t.currentModel}:{},status:e,createdAt:t.createdAt,updatedAt:t.updatedAt,synopsis:t.synopsis??null,summarizedThroughEntry:t.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 Lc(n,e){let t=[],s=a=>a.padEnd(14);t.push(`${s("Session:")}${n.sessionId}`),n.upstreamSessionId&&t.push(`${s("Upstream:")}${n.upstreamSessionId}`),n.title&&t.push(`${s("Title:")}${n.title}`),t.push(`${s("Cwd:")}${n.cwd}`);let r=n.currentModel?` \xB7 ${n.currentModel}`:"";t.push(`${s("Agent:")}${n.agentId}${r}`),t.push(`${s("Status:")}${n.status}`),t.push(`${s("Created:")}${n.createdAt}`),t.push(`${s("Last active:")}${n.updatedAt}`),n.duration.totalMs!==null&&t.push(`${s("Duration:")}${eR(n.duration.totalMs)}`),t.push(`${s("Turns:")}${n.turns}`);let i=[];if(n.cost.amount!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.amount.toFixed(4)}`)}else if(n.cost.cumulative!==null){let a=n.cost.currency??"USD";i.push(`${a} ${n.cost.cumulative.toFixed(4)} (cumulative)`)}if(n.cost.inputTokens!==null||n.cost.outputTokens!==null){let a=[];n.cost.inputTokens!==null&&a.push(`${n.cost.inputTokens.toLocaleString()} in`),n.cost.outputTokens!==null&&a.push(`${n.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&t.push(`${s("Cost:")}${i.join(" | ")}`),n.synopsis){t.push(""),t.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(n.synopsis.goal&&t.push(`${a}${c("Goal:")}${n.synopsis.goal}`),n.synopsis.outcome&&t.push(`${a}${c("Outcome:")}${n.synopsis.outcome}`),n.synopsis.rejected_approaches&&n.synopsis.rejected_approaches.length>0){t.push(`${a}${c("Rejected approaches:")}`);for(let d of n.synopsis.rejected_approaches)t.push(`${a} - ${d}`)}if(n.synopsis.open_threads&&n.synopsis.open_threads.length>0){t.push(`${a}${c("Open threads:")}`);for(let d of n.synopsis.open_threads)t.push(`${a} - ${d}`)}if(n.synopsis.files_touched&&n.synopsis.files_touched.length>0){t.push(`${a}${c("Files touched:")}`);for(let d of n.synopsis.files_touched)t.push(`${a} - ${d}`)}if(n.synopsis.tools_used&&n.synopsis.tools_used.length>0){t.push(`${a}${c("Tools used:")}`);for(let d of n.synopsis.tools_used)t.push(`${a} - ${d}`)}}else t.push(""),t.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(n.tools.length>0){t.push("");let a=n.tools.reduce((l,u)=>l+u.count,0);t.push(`Tools (${a} calls):`);let c=e?n.tools:n.tools.slice(0,Af),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)t.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&n.tools.length>Af&&t.push(` ... ${n.tools.length-Af} more (use --verbose to see all)`)}let o=e?n.files:n.files.map(a=>{let c=a.byTool.filter(l=>ZC.has(l.name)),d=c.reduce((l,u)=>l+u.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){t.push("");let a=e?"Files touched":"Files edited";t.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,Cf),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");t.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else t.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>Cf&&t.push(` ... ${o.length-Cf} more (use --verbose to see all)`)}return t.join(`
148
148
  `)+`
149
- `}function VC(n){if(n<0)return"0s";let e=Math.floor(n/1e3),t=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return t>0&&o.push(`${t}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 xf,Af,YC,Rf=V(()=>{"use strict";dr();Hr();$u();oc();gf();If();xf=10,Af=15,YC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var gw={};Pl(gw,{assertKnownAgent:()=>Dc,canonicalAgentId:()=>Ea,resolveAgentIdOrExit:()=>Hc,runAgentsAdd:()=>Of,runAgentsInstall:()=>Pf,runAgentsList:()=>Ef,runAgentsLogs:()=>_f,runAgentsPin:()=>Ff,runAgentsRefresh:()=>Uc,runAgentsRemove:()=>Lf,runAgentsSet:()=>$f,runAgentsSync:()=>Mf,runAgentsUninstall:()=>Bf,runRegistryPin:()=>jc});import*as Nc from"fs/promises";import*as hw from"path";async function Ef(){let e=(await Fe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
150
- `);return}let t=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:Rs(s.id,t.map(a=>a.id)),name:Rs(s.name,t.map(a=>a.name)),version:Rs(s.version,t.map(a=>a.version)),source:Rs(s.source,t.map(a=>a.source)),distributions:Rs(s.distributions,t.map(a=>a.distributions)),installed:Rs(s.installed,t.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
149
+ `}function eR(n){if(n<0)return"0s";let e=Math.floor(n/1e3),t=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return t>0&&o.push(`${t}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 Af,Cf,ZC,Tf=V(()=>{"use strict";lr();qr();Fu();ac();yf();xf();Af=10,Cf=15,ZC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var vw={};Ml(vw,{assertKnownAgent:()=>Hc,canonicalAgentId:()=>Pa,resolveAgentIdOrExit:()=>Uc,runAgentsAdd:()=>Lf,runAgentsInstall:()=>Mf,runAgentsList:()=>Pf,runAgentsLogs:()=>$f,runAgentsPin:()=>Of,runAgentsRefresh:()=>jc,runAgentsRemove:()=>Bf,runAgentsSet:()=>Ff,runAgentsSync:()=>_f,runAgentsUninstall:()=>Nf,runRegistryPin:()=>qc});import*as Dc from"fs/promises";import*as ww from"path";async function Pf(){let e=(await Fe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
150
+ `);return}let t=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:Es(s.id,t.map(a=>a.id)),name:Es(s.name,t.map(a=>a.name)),version:Es(s.version,t.map(a=>a.version)),source:Es(s.source,t.map(a=>a.source)),distributions:Es(s.distributions,t.map(a=>a.distributions)),installed:Es(s.installed,t.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)+`
151
151
  `);for(let a of t)process.stdout.write(i(a)+`
152
- `);let o=e.fetchedAt!==void 0?` (synced ${po(e.fetchedAt)})`:"";process.stdout.write(`
152
+ `);let o=e.fetchedAt!==void 0?` (synced ${mo(e.fetchedAt)})`:"";process.stdout.write(`
153
153
  Registry version: ${e.version}${o}
154
- `)}function Ea(n,e){if(e.includes(n))return n;let t=n.toLowerCase();if(t.length===0)return;let s=e.filter(r=>r.toLowerCase().startsWith(t));if(s.length===1)return s[0]}async function Dc(n){if((await xe()).agents[n]!==void 0)return;let t;try{let s=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;t=s.body.agents.map(i=>i.id)}catch{return}Ea(n,t)===void 0&&(process.stderr.write(`hydra-acp: unknown agent '${n}'. Run 'hydra-acp agent list' to see available agents.
155
- `),process.exit(2))}async function Hc(n,e){let t;try{let i=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!i.ok)return n;t=i.body.agents.map(a=>a.id)}catch{return n}let s=Ea(n,t);if(s!==void 0)return s;let r=n.toLowerCase();if(r.length>0){let i=t.filter(o=>o.toLowerCase().startsWith(r));i.length>1&&(process.stderr.write(`${e}: '${n}' is ambiguous (matches ${i.join(", ")}).
154
+ `)}function Pa(n,e){if(e.includes(n))return n;let t=n.toLowerCase();if(t.length===0)return;let s=e.filter(r=>r.toLowerCase().startsWith(t));if(s.length===1)return s[0]}async function Hc(n){if((await xe()).agents[n]!==void 0)return;let t;try{let s=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;t=s.body.agents.map(i=>i.id)}catch{return}Pa(n,t)===void 0&&(process.stderr.write(`hydra-acp: unknown agent '${n}'. Run 'hydra-acp agent list' to see available agents.
155
+ `),process.exit(2))}async function Uc(n,e){let t;try{let i=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!i.ok)return n;t=i.body.agents.map(a=>a.id)}catch{return n}let s=Pa(n,t);if(s!==void 0)return s;let r=n.toLowerCase();if(r.length>0){let i=t.filter(o=>o.toLowerCase().startsWith(r));i.length>1&&(process.stderr.write(`${e}: '${n}' is ambiguous (matches ${i.join(", ")}).
156
156
  `),process.exit(2))}process.stderr.write(`${e}: unknown agent '${n}'. Run 'hydra-acp agent list' to see available agents.
157
- `),process.exit(2)}async function Pf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
158
- `),process.exit(2);return}let e=await Hc(n,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
157
+ `),process.exit(2)}async function Mf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
158
+ `),process.exit(2);return}let e=await Uc(n,"hydra agent install");process.stdout.write(`Installing ${e}\u2026
159
159
  `);let s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${n}:`})).body;if(!s.installed){process.stdout.write(`${s.agentId} (${s.version}, ${s.distribution}): ${s.message??"nothing to install"}
160
160
  `);return}process.stdout.write(`Installed ${s.agentId} (${s.version}, ${s.distribution})
161
161
  `),s.command&&process.stdout.write(` \u2192 ${s.command}
162
- `)}async function Mf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
163
- `),process.exit(2);return}let e=await Hc(n,"hydra agent sync"),s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${n}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
164
- `);return}let r=s.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:Rs(i.id,r.map(c=>c.id)),upstream:Rs(i.upstream,r.map(c=>c.upstream)),cwd:Rs(i.cwd,r.map(c=>c.cwd))},a=c=>[c.id.padEnd(o.id),c.upstream.padEnd(o.upstream),c.cwd.padEnd(o.cwd),c.title].join(" ");process.stdout.write(a(i)+`
162
+ `)}async function _f(n){if(!n){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
163
+ `),process.exit(2);return}let e=await Uc(n,"hydra agent sync"),s=(await Fe(`/v1/agents/${encodeURIComponent(e)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${n}:`})).body;if(s.synced.length===0){process.stdout.write(`Nothing new to sync (${s.skipped} already tracked).
164
+ `);return}let r=s.synced.map(c=>({id:c.sessionId,upstream:c.upstreamSessionId,cwd:c.cwd,title:c.title??"-"})),i={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},o={id:Es(i.id,r.map(c=>c.id)),upstream:Es(i.upstream,r.map(c=>c.upstream)),cwd:Es(i.cwd,r.map(c=>c.cwd))},a=c=>[c.id.padEnd(o.id),c.upstream.padEnd(o.upstream),c.cwd.padEnd(o.cwd),c.title].join(" ");process.stdout.write(a(i)+`
165
165
  `);for(let c of r)process.stdout.write(a(c)+`
166
166
  `);process.stdout.write(`
167
167
  Synced ${s.synced.length} session(s); skipped ${s.skipped} already tracked.
168
- `)}async function _f(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
169
- `),process.exit(2);return}let t=L.agentLogFile(n);await lo(t,e,"No log file (agent never ran?)")}async function $f(n,e){let t=await xe();if(!n){let c=await pw()??Tf(await ho());process.stdout.write(`${fw(c)}
168
+ `)}async function $f(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
169
+ `),process.exit(2);return}let t=L.agentLogFile(n);await fo(t,e,"No log file (agent never ran?)")}async function Ff(n,e){let t=await xe();if(!n){let c=await yw()??Ef(await go());process.stdout.write(`${gw(c)}
170
170
  `);return}let s;try{let a=await Fe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(t.agents[n]!==void 0)&&s!==void 0&&!s.includes(n)){let a=n.toLowerCase(),c=a.length>0?s.filter(d=>d.toLowerCase().startsWith(a)):[];if(c.length===1)n=c[0];else if(c.length>1){process.stderr.write(`hydra agent set: '${n}' is ambiguous (matches ${c.join(", ")}).
171
171
  `),process.exit(1);return}else{process.stderr.write(`hydra agent set: '${n}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
172
- `),process.exit(1);return}}e!==void 0?await zp(n,e):await Mi(n);let i=Tf(await ho());e!==void 0&&n!==i.agent&&process.stdout.write(`Default model for ${n} is now ${e}.
173
- `),process.stdout.write(`${fw(i)}
174
- `);let o=await pw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${mw(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
175
- `))}function fw(n){return`Default agent is ${mw(n)}`}function mw(n){return n.model!==void 0?`${n.agent} with ${n.model}`:n.agent}function Tf(n){let e=typeof n.defaultAgent=="string"?n.defaultAgent:"(unset)",s=(n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function pw(){try{let n=await Fe("/v1/config",{rethrowNetworkError:!0});return n.ok?Tf(n.body):void 0}catch{return}}async function Uc(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
176
- `)}async function Ff(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
177
- `),process.exit(2);return}await Kp(n,e),e===void 0?process.stdout.write(`Cleared version pin for ${n}.
172
+ `),process.exit(1);return}}e!==void 0?await Yp(n,e):await $i(n);let i=Ef(await go());e!==void 0&&n!==i.agent&&process.stdout.write(`Default model for ${n} is now ${e}.
173
+ `),process.stdout.write(`${gw(i)}
174
+ `);let o=await yw();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${bw(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
175
+ `))}function gw(n){return`Default agent is ${bw(n)}`}function bw(n){return n.model!==void 0?`${n.agent} with ${n.model}`:n.agent}function Ef(n){let e=typeof n.defaultAgent=="string"?n.defaultAgent:"(unset)",s=(n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function yw(){try{let n=await Fe("/v1/config",{rethrowNetworkError:!0});return n.ok?Ef(n.body):void 0}catch{return}}async function jc(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
176
+ `)}async function Of(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
177
+ `),process.exit(2);return}await Vp(n,e),e===void 0?process.stdout.write(`Cleared version pin for ${n}.
178
178
  `):process.stdout.write(`Pinned ${n} to ${e}.
179
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Of(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
179
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Lf(n,e){if(!n){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
180
180
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(n)){process.stderr.write(`Invalid agent id '${n}': must match [A-Za-z0-9._-]+
181
- `),process.exit(2);return}let t=Ac(e,"agent"),s=t.command,r={};s!==void 0&&(r.command=s),t.args.length>0&&(r.args=t.args),Object.keys(t.env).length>0&&(r.env=t.env),await Ol(n,r);let i=s??`${n} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${n} \u2192 ${i}${t.args.length>0?" "+t.args.join(" "):""}
182
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Lf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent remove <id>
183
- `),process.exit(2);return}await Ol(n,void 0),process.stdout.write(`Removed local agent ${n}.
184
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Bf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
185
- `),process.exit(2);return}let e=await Hc(n,"hydra agent uninstall"),t=wn();if(t===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
186
- `),process.exit(1);return}let s=hw.join(L.agentsDir(),t,e),r=!1;try{await Nc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
187
- `);return}await Nc.rm(s,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${t}). Next session using it will re-install.
188
- `)}async function jc(n){await Jp(n),process.stdout.write(n?"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.
189
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Rs(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}var qc=V(()=>{"use strict";Qe();ve();Li();Ia();dr()});var Wc,Ts,Io,Pa,yw,Ma,Nf,zc,Yr,ww,Vr,bw,Qr,vw,Gr,xo,Ao,Sw,Co,kw,Iw,xw,Df,Aw,Kc,Jc,_a,Cw,Rw,$a=V(()=>{"use strict";Wc="\x1B[?2004h",Ts="\x1B[?2004l",Io="\x1B[200~",Pa="\x1B[201~",yw="\x1B[?1049l",Ma="\x1B[?7h",Nf="\x1B[?7l",zc="\x1B[?25h",Yr="\x1B[?1l",ww="\x1B[>1u",Vr="\x1B[<u",bw="\x1B[>4;2m",Qr="\x1B[>4;0m",vw="\x1B[>5;1m",Gr="\x1B[>5;0m",xo="\x1B[?1000l",Ao="\x1B[?1002l",Sw="\x1B[?1003l",Co="\x1B[?1006l",kw="\x1B[?1015l",Iw="\x1B[?w",xw="\x1B[=24;1w",Df="\x1B[=0;0w",Aw="\x1B]22;pointer\x07",Kc="\x1B]22;default\x07",Jc="\x1B[?1004h",_a="\x1B[?1004l",Cw="\x1B[?2026h",Rw="\x1B[?2026l"});function Ln(){process.stdout.write(Vr),process.stdout.write(Ts),process.stdout.write(Qr),process.stdout.write(Gr),process.stdout.write(xo),process.stdout.write(Ao),process.stdout.write(Co),process.stdout.write(Yr),process.stdout.write("\x1B>")}function Jt(n){return n.width??80}function Es(n){return n.height??24}function Bn(n,e){let t=Jt(n),s=Es(n),r=e.contentWidth??GC,i=Math.max(10,t-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((t-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=Tw.repeat(a-2),p=nR(f,e.title);n.moveTo(l,u),n.dim.noFormat(XC),sR(n,p),n.dim.noFormat(ZC);for(let h=1;h<=c;h++)n.moveTo(l,u+h),n.dim.noFormat(Ew),e.overlay&&n.noFormat(" ".repeat(o)),n.moveTo(l+a-1,u+h),n.dim.noFormat(Ew);return n.moveTo(l,u+d-1),n.dim.noFormat(eR+Tw.repeat(a-2)+tR),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function nR(n,e){if(!e)return{dashes:n};let t=` ${e} `;if(t.length+4>n.length)return{dashes:n};let s=2;return{dashes:n.slice(0,s)+" ".repeat(t.length)+n.slice(s+t.length),title:{offset:s,text:t}}}function sR(n,e){if(!e.title){n.dim.noFormat(e.dashes);return}n.dim.noFormat(e.dashes.slice(0,e.title.offset)),n.brightCyan.noFormat(e.title.text),n.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function Ge(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function Fa(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function os(n){let{term:e,render:t,onKey:s,onResize:r,onMouse:i}=n,o=n.hideCursor!==!1;return t(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??t)()},l=(h,m,y)=>{c||s(h,m,y,p)},u=(h,m)=>{c||!i||i(h,m,p)},f=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",u),e.grabInput(!1),oe({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),n.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{f(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",u)):e.grabInput({}),oe({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var GC,Tw,Ew,XC,ZC,eR,tR,Xr=V(()=>{"use strict";Or();$a();GC=64,Tw="\u2500",Ew="\u2502",XC="\u250C",ZC="\u2510",eR="\u2514",tR="\u2518"});function Pw(n){let e=(n.name&&n.name.length>0?n.name:void 0)??(n.description&&n.description.length>0?n.description:void 0);return e?`${e} (${n.id})`:n.id}function oR(n,e,t){let s={title:`Agent "${n}" needs to be set up`,description:e?.description??rR,footer:iR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),t&&t.length>0){s.authMethods=t;let r=t.map((c,d)=>({index:d,label:`[${d+1}] ${Pw(c)}`,method:c}));s.methodLines=r;let i=Math.min(t.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=t.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function aR(n,e,t=0){if(n==="CTRL_C"||n==="CTRL_D")return{kind:"cancel"};if(n==="ESCAPE")return{kind:"back"};if(n==="ENTER"||n==="KP_ENTER")return t===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(n)){let s=Number(n)-1;return s<t?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&n.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function dR(n){return typeof n!="object"||n===null?!1:n.code===j.AuthRequired}function Mw(n){if(typeof n!="object"||n===null)return;let e=n.data;if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let s=t[$t];if(!(typeof s!="object"||s===null))return s}function cR(n){let e=Mw(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function lR(n){let e=Mw(n);if(!e)return;let t=e.authMethods;if(!Array.isArray(t))return;let s=[];for(let r of t){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 _w(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!dR(e))throw e;let t=cR(e)??n.fallbackAgentId??"",s=lR(e),r=await n.resolveOnboarding(t),i=await n.showBanner(t,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function uR(n,e,t){n.grabInput(!1),oe({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Ln(),n.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+`
181
+ `),process.exit(2);return}let t=Cc(e,"agent"),s=t.command,r={};s!==void 0&&(r.command=s),t.args.length>0&&(r.args=t.args),Object.keys(t.env).length>0&&(r.env=t.env),await Ll(n,r);let i=s??`${n} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${n} \u2192 ${i}${t.args.length>0?" "+t.args.join(" "):""}
182
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Bf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent remove <id>
183
+ `),process.exit(2);return}await Ll(n,void 0),process.stdout.write(`Removed local agent ${n}.
184
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Nf(n){if(!n){process.stderr.write(`Usage: hydra-acp agent uninstall <id>
185
+ `),process.exit(2);return}let e=await Uc(n,"hydra agent uninstall"),t=wn();if(t===void 0){process.stderr.write(`hydra agent uninstall: cannot determine current platform; nothing removed.
186
+ `),process.exit(1);return}let s=ww.join(L.agentsDir(),t,e),r=!1;try{await Dc.stat(s),r=!0}catch{}if(!r){process.stdout.write(`Nothing to remove: ${e} is not installed on ${t}.
187
+ `);return}await Dc.rm(s,{recursive:!0,force:!0}),process.stdout.write(`Uninstalled ${e} (${t}). Next session using it will re-install.
188
+ `)}async function qc(n){await Qp(n),process.stdout.write(n?"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.
189
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Es(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}var Wc=V(()=>{"use strict";Qe();ve();Ni();xa();lr()});var zc,Ps,Ao,Ma,Sw,_a,Df,Kc,Gr,kw,Xr,Iw,Zr,xw,ei,Co,Ro,Aw,To,Cw,Rw,Tw,Hf,Ew,Jc,Yc,$a,Pw,Mw,Fa=V(()=>{"use strict";zc="\x1B[?2004h",Ps="\x1B[?2004l",Ao="\x1B[200~",Ma="\x1B[201~",Sw="\x1B[?1049l",_a="\x1B[?7h",Df="\x1B[?7l",Kc="\x1B[?25h",Gr="\x1B[?1l",kw="\x1B[>1u",Xr="\x1B[<u",Iw="\x1B[>4;2m",Zr="\x1B[>4;0m",xw="\x1B[>5;1m",ei="\x1B[>5;0m",Co="\x1B[?1000l",Ro="\x1B[?1002l",Aw="\x1B[?1003l",To="\x1B[?1006l",Cw="\x1B[?1015l",Rw="\x1B[?w",Tw="\x1B[=24;1w",Hf="\x1B[=0;0w",Ew="\x1B]22;pointer\x07",Jc="\x1B]22;default\x07",Yc="\x1B[?1004h",$a="\x1B[?1004l",Pw="\x1B[?2026h",Mw="\x1B[?2026l"});function Ln(){process.stdout.write(Xr),process.stdout.write(Ps),process.stdout.write(Zr),process.stdout.write(ei),process.stdout.write(Co),process.stdout.write(Ro),process.stdout.write(To),process.stdout.write(Gr),process.stdout.write("\x1B>")}function Jt(n){return n.width??80}function Ms(n){return n.height??24}function Bn(n,e){let t=Jt(n),s=Ms(n),r=e.contentWidth??nR,i=Math.max(10,t-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((t-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);e.overlay||n.moveTo(1,1).eraseDisplayBelow();let f=_w.repeat(a-2),p=aR(f,e.title);n.moveTo(l,u),n.dim.noFormat(sR),dR(n,p),n.dim.noFormat(rR);for(let h=1;h<=c;h++)n.moveTo(l,u+h),n.dim.noFormat($w),e.overlay&&n.noFormat(" ".repeat(o)),n.moveTo(l+a-1,u+h),n.dim.noFormat($w);return n.moveTo(l,u+d-1),n.dim.noFormat(iR+_w.repeat(a-2)+oR),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function aR(n,e){if(!e)return{dashes:n};let t=` ${e} `;if(t.length+4>n.length)return{dashes:n};let s=2;return{dashes:n.slice(0,s)+" ".repeat(t.length)+n.slice(s+t.length),title:{offset:s,text:t}}}function dR(n,e){if(!e.title){n.dim.noFormat(e.dashes);return}n.dim.noFormat(e.dashes.slice(0,e.title.offset)),n.brightCyan.noFormat(e.title.text),n.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function Ge(n,e){return e<=1?"":n.length<=e?n:n.slice(0,Math.max(0,e-1))+"\u2026"}function Oa(n,e){return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}async function ds(n){let{term:e,render:t,onKey:s,onResize:r,onMouse:i}=n,o=n.hideCursor!==!1;return t(),o&&e.hideCursor(),await new Promise(a=>{let c=!1,d=()=>{c||(r??t)()},l=(h,m,y)=>{c||s(h,m,y,p)},u=(h,m)=>{c||!i||i(h,m,p)},f=()=>{c||(c=!0,e.off("key",l),e.off("resize",d),i&&e.off("mouse",u),e.grabInput(!1),oe({src:"grab",site:"runModalPrompt.cleanup",on:!1}),e.hideCursor(!1),n.overlay||e.moveTo(1,1).eraseDisplayBelow())},p=h=>{f(),a(h)};i?(e.grabInput({mouse:"motion"}),e.on("mouse",u)):e.grabInput({}),oe({src:"grab",site:"runModalPrompt.install",on:!0}),e.on("key",l),e.on("resize",d)})}var nR,_w,$w,sR,rR,iR,oR,ti=V(()=>{"use strict";Nr();Fa();nR=64,_w="\u2500",$w="\u2502",sR="\u250C",rR="\u2510",iR="\u2514",oR="\u2518"});function Fw(n){let e=(n.name&&n.name.length>0?n.name:void 0)??(n.description&&n.description.length>0?n.description:void 0);return e?`${e} (${n.id})`:n.id}function uR(n,e,t){let s={title:`Agent "${n}" needs to be set up`,description:e?.description??cR,footer:lR};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),t&&t.length>0){s.authMethods=t;let r=t.map((c,d)=>({index:d,label:`[${d+1}] ${Fw(c)}`,method:c}));s.methodLines=r;let i=Math.min(t.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=t.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function fR(n,e,t=0){if(n==="CTRL_C"||n==="CTRL_D")return{kind:"cancel"};if(n==="ESCAPE")return{kind:"back"};if(n==="ENTER"||n==="KP_ENTER")return t===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(n)){let s=Number(n)-1;return s<t?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&n.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function pR(n){return typeof n!="object"||n===null?!1:n.code===j.AuthRequired}function Ow(n){if(typeof n!="object"||n===null)return;let e=n.data;if(typeof e!="object"||e===null)return;let t=e._meta;if(typeof t!="object"||t===null)return;let s=t[$t];if(!(typeof s!="object"||s===null))return s}function hR(n){let e=Ow(n);if(!e)return;let t=e.agentId;return typeof t=="string"?t:void 0}function mR(n){let e=Ow(n);if(!e)return;let t=e.authMethods;if(!Array.isArray(t))return;let s=[];for(let r of t){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 Lw(n){for(;;)try{return{kind:"ok",result:await n.request()}}catch(e){if(!pR(e))throw e;let t=hR(e)??n.fallbackAgentId??"",s=mR(e),r=await n.resolveOnboarding(t),i=await n.showBanner(t,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function gR(n,e,t){n.grabInput(!1),oe({src:"grab",site:"runTerminalAuthSpawn.release",on:!1}),Ln(),n.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+`
190
190
  `);let r=t?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{n.grabInput({}),oe({src:"grab",site:"runTerminalAuthSpawn.reGrab",on:!0})}catch{}};try{let a=r(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",c=>{o(),i({exitCode:c})}),a.on("error",c=>{o(),process.stdout.write(`
191
191
  failed to spawn ${e.command}: ${c.message}
192
192
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
193
193
  failed to spawn ${e.command}: ${a.message}
194
- `),i({exitCode:-1})}})}function fR(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function Hf(n,e){let t;try{t=await e.authenticate(n.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(fR(t)){let s={command:t.command,args:t.args,env:t.env,cwd:t.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function $w(n,e,t,s,r){Ln();let i=oR(e,t,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=Bn(n,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(n.moveTo(f.contentX,f.contentY+h),n.brightYellow.noFormat(Ge(` ${a}`,p)),h++),c&&(n.moveTo(f.contentX,f.contentY+h),n.brightRed.noFormat(Ge(` ${c}`,p)),h++),n.moveTo(f.contentX,f.contentY+h),n.brightWhite.bold.noFormat(Ge(` ${i.title}`,p)),h+=2,n.moveTo(f.contentX,f.contentY+h),n.noFormat(Ge(` ${i.description}`,p)),h++,i.command&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Run: "),n.brightWhite.noFormat(Ge(i.command,p-7)),h++),i.url&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Docs: "),n.brightWhite.noFormat(Ge(i.url,p-7)),h++),i.methodLines){n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" "),n.noFormat(Ge(m.label,p-3)),h++}return h++,n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return os({term:n,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=aR(u,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${Pw(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>uR(n,v));(async()=>{let v=await Hf(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var rR,iR,Uf=V(()=>{"use strict";Or();Sd();Id();Xr();rR="This agent requires authentication before use.",iR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Nw}from"timers/promises";function SR(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var yR,wR,bR,vR,To,jf=V(()=>{"use strict";xa();io();yR=200,wR=5e3,bR=2,vR=60,To=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 t=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(t,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(t),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),Nw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=yR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Wr(s,this.opts.subprotocols);this.bindStream(ns(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>=vR)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 ${t}ms`),await Nw(t),this.destroyed)return;t=Math.min(t*bR,wR)}}bindStream(e){this.current=e,e.onMessage(t=>{if(SR(t)&&t.id!==null){let s=this.pendingRequests.get(t.id);s&&(this.pendingRequests.delete(t.id),s.resolve(t))}for(let s of this.messageHandlers)s(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=t??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}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(t){this.scheduleReconnect(t);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(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let s of this.closeHandlers)s(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
195
- `)}}});function Dw(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let i of e){let o=t.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=t.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 Zr(n){return{outcome:{outcome:"selected",optionId:Dw(n,["allow_once","allow_always"])}}}function Hw(n){return{outcome:{outcome:"selected",optionId:Dw(n,["reject_once","reject_always"])}}}function Qc(n){return n&&typeof n=="object"?n:void 0}function Oa(n){return typeof n=="string"&&n.length>0?n:void 0}function Uw(n){let e=Qc(n),t=Qc(e?.toolCall),s={paths:[]};if(!t)return s;let r=Oa(t.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Oa(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let d of a)o(Qc(d)?.path);let c=Qc(t.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Oa(c.command);d&&(s.command=d);let l=Oa(c.url);l&&(s.url=l);let u=Oa(c.description);u&&(s.description=u)}return s}function jw(n){let e=[];return n.command?e.push(`$ ${n.command}`):n.url?e.push(n.url):n.paths.length===1?e.push(n.paths[0]):n.paths.length>1?e.push(`${n.paths[0]} (+${n.paths.length-1} more)`):n.description&&e.push(n.description),e.join(" ").replace(/\s+/g," ").trim()}var Gc=V(()=>{"use strict"});function v0(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function ab(n){let t=(n.split("-",1)[0]??n).split("."),s=Number(t[0]),r=Number(t[1]),i=Number(t[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function S0(n,e){let t=ab(n),s=ab(e);if(!t||!s)return n!==e;for(let r=0;r<3;r++){let i=t[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function La(){if(pr!==void 0)return pr;if(v0())return pr=null,pr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:db,version:ye}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&S0(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}pr={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{t.config?.set?.("update",void 0)}catch{}pr=null}}catch{pr=null}return pr}function Ba(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${db}`}var db,pr,zf=V(()=>{"use strict";an();db="@hydra-acp/cli"});import*as Na from"fs/promises";import*as Kf from"path";async function Da(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Kf.resolve(et(e)),s;try{s=await Na.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return s.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function cb(n){let e=[],t=new Set,s=r=>{t.has(r)||(t.add(r),e.push(r))};s(n),n.startsWith("/Users/")?s("/home/"+n.slice(7)):n.startsWith("/home/")&&s("/Users/"+n.slice(6));for(let r of e)try{if((await Na.stat(r)).isDirectory())return r}catch{}return null}async function lb(n){let e=n.lastIndexOf("/"),t,s,r;e===-1?(t="",s=n,r="."):(t=n.slice(0,e+1),s=n.slice(e+1),r=e===0?"/":t);let i=Kf.resolve(et(r)),o;try{o=(await Na.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,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:t,basePrefix:s,matches:c}}var Jf=V(()=>{"use strict";Qe()});var ub,fb,pb,hb=V(()=>{"use strict";ub="hydra-acp/question/list",fb="hydra-acp/question/answer",pb="hydra-acp/question/dismiss"});import{EventEmitter as k0}from"events";import{WebSocket as I0}from"ws";function x0(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=Go(s.hostname);r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(t.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(t.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new I0(n,e,t),o=()=>{i.off("error",a),s(ns(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function mb(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??x0,c=["acp.v1",`hydra-acp-token.${n.token}`],d=await a(n.wsUrl,c),l=new Kt(d),u;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)u=s.reuseSessionId;else{let m=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Cc(n,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let f=new Yf(l,d,u,n,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),rs(n,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[$t]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var Yf,gb=V(()=>{"use strict";Xo();Aa();Br();io();Ft();Yf=class extends k0{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,s,r,i){super(),this._conn=e,this._stream=t,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(()=>{}),rs(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,t){return super.once(e,t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}}});var Vf,nl,yb=V(()=>{"use strict";So();rr();Vf=class{_listeners=new Map;on(e,t){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},nl=class extends Vf{_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 t=ts(e);if(!t)return 0;switch(t.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),t.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),t.kind){case"agent-text":{let s=t.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=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=vo(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=vo(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(s.detail=t.detail),this._toolStates.set(t.toolCallId,s);let r=Ta(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(t.toolCallId);if(!s)return 0;t.title!==void 0&&(s.latestTitle=t.title),t.status!==void 0&&(s.status=t.status),t.detail!==void 0&&(s.detail=t.detail),t.errorText!==void 0&&(s.errorText=t.errorText);let r=Ta(s),i=this._toolRanges.get(t.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(t.toolCallId,i,r),r.length}default:{let s=lr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return ur(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t,s){let r=s.length-t.length;if(this._lines.splice(t.start,t.length,...s),t.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>t.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.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 t=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function T0(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Ha(n,e,t,s){Ln();let r=T0(e,t??A0),i=0,o=null,a=null,c=()=>{let E=Es(n)-8;return Math.max(1,Math.min(C0,e.length,E))},d=()=>{let E=c(),$=Math.max(0,e.length-E);i>$&&(i=$),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},u=null,f=0,p=(E,$)=>{if(E<i||E>=i+f)return;let N=e[E];if(!N)return;let M=$.contentW,D=$.contentY+2+(E-i);n.moveTo($.contentX,D);let B=E===r?"\u276F":" ",O=N.description??N.name,K=` ${B} ${N.id}`;if(E===r){let X=`${K} ${O}`;n.brightWhite.bgBlue.noFormat(Fa(Ge(X,M),M))}else{let X=M-K.length-2,Z=X>1?` ${Ge(O,X)}`:"";n.noFormat(K),Z.length>0&&n.dim.noFormat(Z);let Q=K.length+Z.length;Q<M&&n.noFormat(" ".repeat(M-Q))}},h=(E,$)=>{let N=E.contentY+2+f+1;n.moveTo(E.contentX,N);let D=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>$?` (${r+1}/${e.length})`:""}`,B=Fa(Ge(D,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{d();let E=c(),$=E+4,N=Math.min(R0,Math.max(40,Jt(n)-8)),M=Bn(n,{contentHeight:$,contentWidth:N,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=M,u=M,f=Math.min(E,e.length-i),o=M.contentY+2,n.moveTo(M.contentX,M.contentY),n.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let D=Math.min(e.length,i+E);for(let B=i;B<D;B++)p(B,M);return h(M,E),M},y=()=>m(),b=E=>{let $=u;if($===null){m();return}let N=c(),M=i;if(l(),i!==M){m();return}f=Math.min(N,e.length-i),E!==r&&(p(E,$),p(r,$)),h($,N)},v=()=>{if(r<e.length-1){let E=r;r++,b(E)}},S=()=>{if(r>0){let E=r;r--,b(E)}},x=()=>{let E=u;if(E===null){m();return}let $=c();d(),f=Math.min($,e.length-i);let N=Math.min(e.length,i+$);for(let M=i;M<N;M++)p(M,E);for(let M=f;M<$;M++){let D=E.contentY+2+M;n.moveTo(E.contentX,D),n.noFormat(" ".repeat(E.contentW))}h(E,$)},T=E=>{let $=c(),N=Math.max(0,e.length-$);if(N===0)return;let M=Math.max(0,Math.min(N,i+E));M!==i&&(i=M,x())};return os({term:n,render:y,overlay:s?.overlay===!0,onKey:(E,$,N,M)=>{if(E==="CTRL_C"||E==="CTRL_D"){M({kind:"cancel"});return}if(E==="ESCAPE"){M({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let D=e[r];D&&M({kind:"select",agentId:D.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){v();return}if(N?.isCharacter){let D=E.toLowerCase();if(D==="s"){let B=e[r];B&&M({kind:"select",agentId:B.id,persist:!0});return}if(D==="j"){v();return}if(D==="k"){S();return}}},onMouse:(E,$,N)=>{if(E==="MOUSE_WHEEL_UP"){T(-1);return}if(E==="MOUSE_WHEEL_DOWN"){T(1);return}if(E==="MOUSE_MOTION"){let X=$?.y;if(typeof X!="number"||o===null)return;let Z=X-o;if(Z<0||Z>=f)return;let Q=i+Z;if(Q<0||Q>=e.length)return;if(Q!==r){let fe=r;r=Q,b(fe)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let M=$?.x,D=$?.y;if(a!==null&&typeof M=="number"&&typeof D=="number"&&(M<a.x||M>=a.x+a.w||D<a.y||D>=a.y+a.h)){N({kind:"back"});return}if(typeof D!="number"||o===null)return;let B=D-o;if(B<0||B>=f)return;let O=i+B;if(O<0||O>=e.length)return;let K=e[O];K&&N({kind:"select",agentId:K.id,persist:!1})}})}var A0,C0,R0,Qf=V(()=>{"use strict";Xr();A0="opencode",C0=20,R0=88});import E0 from"path";function Ua(n){return wb[E0.extname(n).toLowerCase()]??null}function P0(n){return Ua(n)!==null}function Gf(n){let e=n.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let t=e[1].toLowerCase();if(!M0.has(t))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:t,data:s,sizeBytes:i}}function _0(n){return Gf(n)!==null}function kn(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function bb(n){let e=n.trim();if(e.length===0)return null;let t=[],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(!_0(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!P0(o))return null;t.push(o)}return t.length>0?t:null}var as,wb,M0,sl=V(()=>{"use strict";as=10*1024*1024,wb={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};M0=new Set(Object.values(wb))});import{spawn as $0}from"child_process";import Xf from"fs/promises";import F0 from"os";import O0 from"path";async function il(n={}){let e={...Zf,...n};return e.platform==="darwin"?D0(e):e.platform==="linux"?H0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function kb(n={}){let e={...Zf,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Mo(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Mo(e,"xclip"))t="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 ja(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:ep(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Ib(n,e={}){let{target:t="both",...s}=e,r={...Zf,...s},i=await L0(r,n,t);if(i.ok)return i;let o=B0(r,n,t);return o.ok||o.reason!==xb?o:i}async function L0(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await rl(n.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let r=t==="clipboard"||t==="both",i=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await Mo(n,"wl-copy")?Sb(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await Mo(n,"xclip")?Sb(n,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 ${n.platform}`}}async function Sb(n,e,t,s,r,i,o){let a=t;if(i){try{await rl(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await rl(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await rl(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function B0(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>vb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${vb} bytes)`};let i=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${s}\x07`;return n.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??N0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:xb}}function N0(n){let e=[process.stderr,process.stdout];for(let t of e)if(t&&t.isTTY)try{return t.write(n),!0}catch{}return!1}async function D0(n){let e=O0.join(n.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),t=["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 t)s.push("-e",r);try{await Ab(n.spawn,"osascript",s);let r=await z0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Xf.unlink(e).catch(()=>{})}try{let r=await ja(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ep(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function H0(n){let e=await U0(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await W0(n,e),s=q0(t);if(s)try{let r=await ja(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>as?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(as)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await ja(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:ep(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function U0(n){return n.env.WAYLAND_DISPLAY&&await Mo(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await Mo(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function q0(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of j0)if(e.has(t))return t;return null}async function W0(n,e){try{return(await ja(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
196
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function ep(n){return n.replace(/\r\n?/g,`
197
- `)}async function Mo(n,e){try{return await Ab(n.spawn,"which",[e]),!0}catch{return!1}}async function z0(n,e){try{let t=await Xf.readFile(n);return e&&await Xf.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>as?{ok:!1,reason:`clipboard image is ${kn(t.length)}, max ${kn(as)}`}:{ok:!0,kind:"image",attachment:{mimeType:Ua(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Ab(n,e,t){return new Promise((s,r)=>{let i=n(e,t);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 rl(n,e,t,s){return new Promise((r,i)=>{let o=n(e,t,{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 ja(n,e,t){return new Promise((s,r)=>{let i=n(e,t),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var Zf,vb,xb,j0,ol=V(()=>{"use strict";sl();Zf={platform:process.platform,env:process.env,spawn:$0,tmpdir:F0.tmpdir};vb=74994;xb="no TTY available for OSC 52 clipboard write";j0=["image/png","image/jpeg","image/gif","image/webp"]});function J0(n,e){return`[pasted #${n} +${e} lines]`}var K0,qa,tp,Y0,Ps,np=V(()=>{"use strict";K0=/\[pasted #(\d+) \+\d+ lines\]/g,qa=/\[pasted #(\d+) \+\d+ lines\]$/,tp=/^\[pasted #(\d+) \+\d+ lines\]/;Y0=500,Ps=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>Y0&&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,t,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,t=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...t],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){if(this.clearDoubleTap(),e.text.length===0)return[{type:"attachment-request",source:"clipboard"}];this.recordEdit();let t=e.text.split(`
198
- `).length;if(this.collapsePastes&&t>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(J0(s,t))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(this.moveLeft(),[]);case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
199
- `)}expandPastes(e){return e.replace(K0,(t,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:t})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
194
+ `),i({exitCode:-1})}})}function yR(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function Uf(n,e){let t;try{t=await e.authenticate(n.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(yR(t)){let s={command:t.command,args:t.args,env:t.env,cwd:t.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Bw(n,e,t,s,r){Ln();let i=uR(e,t,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=Bn(n,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,h=0;if(a&&(n.moveTo(f.contentX,f.contentY+h),n.brightYellow.noFormat(Ge(` ${a}`,p)),h++),c&&(n.moveTo(f.contentX,f.contentY+h),n.brightRed.noFormat(Ge(` ${c}`,p)),h++),n.moveTo(f.contentX,f.contentY+h),n.brightWhite.bold.noFormat(Ge(` ${i.title}`,p)),h+=2,n.moveTo(f.contentX,f.contentY+h),n.noFormat(Ge(` ${i.description}`,p)),h++,i.command&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Run: "),n.brightWhite.noFormat(Ge(i.command,p-7)),h++),i.url&&(n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Docs: "),n.brightWhite.noFormat(Ge(i.url,p-7)),h++),i.methodLines){n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" Methods reported by the agent:"),h++;for(let m of i.methodLines)n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(" "),n.noFormat(Ge(m.label,p-3)),h++}return h++,n.moveTo(f.contentX,f.contentY+h),n.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return ds({term:n,render:()=>{d()},onKey:(u,f,p,h)=>{if(o)return;let m=fR(u,p,l);if(m.kind!=="ignore"){if(m.kind==="retry"||m.kind==="back"||m.kind==="cancel"){h(m.kind);return}if(m.kind==="selectMethod"){let y=i.methodLines?.[m.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${Fw(y)}\u2026`,d();let w=r.runTerminalAuth??(v=>gR(n,v));(async()=>{let v=await Uf(y,{authenticate:r.authenticate,runTerminalAuth:w});if(v.kind==="terminal-completed"){h("terminal-completed");return}if(v.kind==="retry"){h("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var cR,lR,jf=V(()=>{"use strict";Nr();kd();xd();ti();cR="This agent requires authentication before use.",lR="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as jw}from"timers/promises";function CR(n){return!("method"in n)&&"id"in n&&n.id!==void 0}var kR,IR,xR,AR,Po,qf=V(()=>{"use strict";Aa();ao();kR=200,IR=5e3,xR=2,AR=60,Po=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 t=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(t,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(t),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),jw(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:t}of this.pendingRequests.values())t(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,t=kR;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await Jr(s,this.opts.subprotocols);this.bindStream(ss(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>=AR)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 ${t}ms`),await jw(t),this.destroyed)return;t=Math.min(t*xR,IR)}}bindStream(e){this.current=e,e.onMessage(t=>{if(CR(t)&&t.id!==null){let s=this.pendingRequests.get(t.id);s&&(this.pendingRequests.delete(t.id),s.resolve(t))}for(let s of this.messageHandlers)s(t)}),e.onClose(t=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=t??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(t)}})}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(t){this.scheduleReconnect(t);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(t){this.log(`hydra-acp: onDisconnect handler threw: ${t.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(t){for(let s of this.closeHandlers)s(t);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
195
+ `)}}});function qw(n,e){let t=n&&typeof n=="object"?n.options:void 0;if(Array.isArray(t)){for(let i of e){let o=t.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=t.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 ni(n){return{outcome:{outcome:"selected",optionId:qw(n,["allow_once","allow_always"])}}}function Ww(n){return{outcome:{outcome:"selected",optionId:qw(n,["reject_once","reject_always"])}}}function Gc(n){return n&&typeof n=="object"?n:void 0}function La(n){return typeof n=="string"&&n.length>0?n:void 0}function zw(n){let e=Gc(n),t=Gc(e?.toolCall),s={paths:[]};if(!t)return s;let r=La(t.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=La(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=t.locations;if(Array.isArray(a))for(let d of a)o(Gc(d)?.path);let c=Gc(t.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=La(c.command);d&&(s.command=d);let l=La(c.url);l&&(s.url=l);let u=La(c.description);u&&(s.description=u)}return s}function Kw(n){let e=[];return n.command?e.push(`$ ${n.command}`):n.url?e.push(n.url):n.paths.length===1?e.push(n.paths[0]):n.paths.length>1?e.push(`${n.paths[0]} (+${n.paths.length-1} more)`):n.description&&e.push(n.description),e.join(" ").replace(/\s+/g," ").trim()}var Xc=V(()=>{"use strict"});function A0(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function ub(n){let t=(n.split("-",1)[0]??n).split("."),s=Number(t[0]),r=Number(t[1]),i=Number(t[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function C0(n,e){let t=ub(n),s=ub(e);if(!t||!s)return n!==e;for(let r=0;r<3;r++){let i=t[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function Ba(){if(mr!==void 0)return mr;if(A0())return mr=null,mr;try{let n=await import("update-notifier"),t=(n.default??n)({pkg:{name:fb,version:ye}}),s=t.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&C0(s.latest,s.current)){try{t.config?.set?.("update",s)}catch{}mr={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{t.config?.set?.("update",void 0)}catch{}mr=null}}catch{mr=null}return mr}function Na(n){return`hydra-acp ${n.latest} available (current ${n.current}) \xB7 run: npm update -g ${fb}`}var fb,mr,Kf=V(()=>{"use strict";an();fb="@hydra-acp/cli"});import*as Da from"fs/promises";import*as Jf from"path";async function Ha(n){let e=n.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let t=Jf.resolve(et(e)),s;try{s=await Da.stat(t)}catch{return{ok:!1,reason:`${t} does not exist`}}return s.isDirectory()?{ok:!0,path:t}:{ok:!1,reason:`${t} is not a directory`}}async function pb(n){let e=[],t=new Set,s=r=>{t.has(r)||(t.add(r),e.push(r))};s(n),n.startsWith("/Users/")?s("/home/"+n.slice(7)):n.startsWith("/home/")&&s("/Users/"+n.slice(6));for(let r of e)try{if((await Da.stat(r)).isDirectory())return r}catch{}return null}async function hb(n){let e=n.lastIndexOf("/"),t,s,r;e===-1?(t="",s=n,r="."):(t=n.slice(0,e+1),s=n.slice(e+1),r=e===0?"/":t);let i=Jf.resolve(et(r)),o;try{o=(await Da.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:t,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:t,basePrefix:s,matches:c}}var Yf=V(()=>{"use strict";Qe()});var mb,gb,yb,wb=V(()=>{"use strict";mb="hydra-acp/question/list",gb="hydra-acp/question/answer",yb="hydra-acp/question/dismiss"});import{EventEmitter as R0}from"events";import{WebSocket as T0}from"ws";function E0(n,e){let t={};try{let s=new URL(n);if(s.protocol==="wss:"){let r=Xo(s.hostname);r.rejectUnauthorized!==void 0&&(t.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(t.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(t.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new T0(n,e,t),o=()=>{i.off("error",a),s(ss(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function bb(n,e,t,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??E0,c=["acp.v1",`hydra-acp-token.${n.token}`],d=await a(n.wsUrl,c),l=new Kt(d),u;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)u=s.reuseSessionId;else{let m=t.replace(/\s+/g," ").trim().slice(0,60);u=(await Rc(n,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${m}`,mode:"verbatim"},o)).sessionId}}catch(m){throw d.close().catch(()=>{}),m}let f=new Vf(l,d,u,n,o),p=!1,h=m=>{p||(p=!0,f.emit("event",m),d.close().catch(()=>{}))};l.onNotification("session/update",m=>{let y=m?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||h({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(m){throw d.close().catch(()=>{}),os(n,u,o).catch(()=>{}),m}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:t}],_meta:{[$t]:{ancillary:!0}}}).then(m=>{let y=m&&typeof m=="object"?m.stopReason:void 0;h(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(m=>{h({kind:"errored",error:m instanceof Error?m:new Error(String(m))})})})})().catch(i)})}var Vf,vb=V(()=>{"use strict";Zo();Ca();Hr();ao();Ft();Vf=class extends R0{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,t,s,r,i){super(),this._conn=e,this._stream=t,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(()=>{}),os(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,t){return super.once(e,t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}}});var Qf,sl,Sb=V(()=>{"use strict";Io();or();Qf=class{_listeners=new Map;on(e,t){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(t)}off(e,t){this._listeners.get(e)?.delete(t)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},sl=class extends Qf{_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 t=ns(e);if(!t)return 0;switch(t.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),t.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),t.kind){case"agent-text":{let s=t.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=t.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=ko(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=ko(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:t.title,latestTitle:t.title,status:t.status??"pending"};t.detail!==void 0&&(s.detail=t.detail),this._toolStates.set(t.toolCallId,s);let r=Ea(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(t.toolCallId);if(!s)return 0;t.title!==void 0&&(s.latestTitle=t.title),t.status!==void 0&&(s.status=t.status),t.detail!==void 0&&(s.detail=t.detail),t.errorText!==void 0&&(s.errorText=t.errorText);let r=Ea(s),i=this._toolRanges.get(t.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(t.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(t.toolCallId,i,r),r.length}default:{let s=fr(t);return this._pushLines(s),s.length}}}_parseAgent(e){let t=this._getMaxWidth?.();return pr(e,t!==void 0&&t>0?{maxWidth:t}:void 0)}_replaceAgentRange(e,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t){let s=t.length-e.length;if(this._lines.splice(e.start,e.length,...t),e.length=t.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,t,s){let r=s.length-t.length;if(this._lines.splice(t.start,t.length,...s),t.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>t.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>t.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>t.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 t=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>t&&this.emit("changed")}}});function $0(n,e){let t=n.findIndex(s=>s.id===e);return t===-1?0:t}async function Ua(n,e,t,s){Ln();let r=$0(e,t??P0),i=0,o=null,a=null,c=()=>{let E=Ms(n)-8;return Math.max(1,Math.min(M0,e.length,E))},d=()=>{let E=c(),$=Math.max(0,e.length-E);i>$&&(i=$),i<0&&(i=0)},l=()=>{let E=c();r<i?i=r:r>=i+E&&(i=r-E+1),d()},u=null,f=0,p=(E,$)=>{if(E<i||E>=i+f)return;let N=e[E];if(!N)return;let M=$.contentW,D=$.contentY+2+(E-i);n.moveTo($.contentX,D);let B=E===r?"\u276F":" ",O=N.description??N.name,K=` ${B} ${N.id}`;if(E===r){let X=`${K} ${O}`;n.brightWhite.bgBlue.noFormat(Oa(Ge(X,M),M))}else{let X=M-K.length-2,Z=X>1?` ${Ge(O,X)}`:"";n.noFormat(K),Z.length>0&&n.dim.noFormat(Z);let Q=K.length+Z.length;Q<M&&n.noFormat(" ".repeat(M-Q))}},h=(E,$)=>{let N=E.contentY+2+f+1;n.moveTo(E.contentX,N);let D=` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${e.length>$?` (${r+1}/${e.length})`:""}`,B=Oa(Ge(D,E.contentW),E.contentW);n.dim.noFormat(B)},m=()=>{d();let E=c(),$=E+4,N=Math.min(_0,Math.max(40,Jt(n)-8)),M=Bn(n,{contentHeight:$,contentWidth:N,title:s?.title??"Select agent",overlay:s?.overlay===!0});a=M,u=M,f=Math.min(E,e.length-i),o=M.contentY+2,n.moveTo(M.contentX,M.contentY),n.noFormat(` ${s?.intro??"Which agent should this session use?"}`);let D=Math.min(e.length,i+E);for(let B=i;B<D;B++)p(B,M);return h(M,E),M},y=()=>m(),w=E=>{let $=u;if($===null){m();return}let N=c(),M=i;if(l(),i!==M){m();return}f=Math.min(N,e.length-i),E!==r&&(p(E,$),p(r,$)),h($,N)},v=()=>{if(r<e.length-1){let E=r;r++,w(E)}},S=()=>{if(r>0){let E=r;r--,w(E)}},x=()=>{let E=u;if(E===null){m();return}let $=c();d(),f=Math.min($,e.length-i);let N=Math.min(e.length,i+$);for(let M=i;M<N;M++)p(M,E);for(let M=f;M<$;M++){let D=E.contentY+2+M;n.moveTo(E.contentX,D),n.noFormat(" ".repeat(E.contentW))}h(E,$)},T=E=>{let $=c(),N=Math.max(0,e.length-$);if(N===0)return;let M=Math.max(0,Math.min(N,i+E));M!==i&&(i=M,x())};return ds({term:n,render:y,overlay:s?.overlay===!0,onKey:(E,$,N,M)=>{if(E==="CTRL_C"||E==="CTRL_D"){M({kind:"cancel"});return}if(E==="ESCAPE"){M({kind:"back"});return}if(E==="ENTER"||E==="KP_ENTER"){let D=e[r];D&&M({kind:"select",agentId:D.id,persist:!1});return}if(E==="UP"||E==="SHIFT_TAB"){S();return}if(E==="DOWN"||E==="TAB"){v();return}if(N?.isCharacter){let D=E.toLowerCase();if(D==="s"){let B=e[r];B&&M({kind:"select",agentId:B.id,persist:!0});return}if(D==="j"){v();return}if(D==="k"){S();return}}},onMouse:(E,$,N)=>{if(E==="MOUSE_WHEEL_UP"){T(-1);return}if(E==="MOUSE_WHEEL_DOWN"){T(1);return}if(E==="MOUSE_MOTION"){let X=$?.y;if(typeof X!="number"||o===null)return;let Z=X-o;if(Z<0||Z>=f)return;let Q=i+Z;if(Q<0||Q>=e.length)return;if(Q!==r){let fe=r;r=Q,w(fe)}return}if(E!=="MOUSE_LEFT_BUTTON_PRESSED")return;let M=$?.x,D=$?.y;if(a!==null&&typeof M=="number"&&typeof D=="number"&&(M<a.x||M>=a.x+a.w||D<a.y||D>=a.y+a.h)){N({kind:"back"});return}if(typeof D!="number"||o===null)return;let B=D-o;if(B<0||B>=f)return;let O=i+B;if(O<0||O>=e.length)return;let K=e[O];K&&N({kind:"select",agentId:K.id,persist:!1})}})}var P0,M0,_0,Gf=V(()=>{"use strict";ti();P0="opencode",M0=20,_0=88});import F0 from"path";function ja(n){return kb[F0.extname(n).toLowerCase()]??null}function O0(n){return ja(n)!==null}function Xf(n){let e=n.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let t=e[1].toLowerCase();if(!L0.has(t))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:t,data:s,sizeBytes:i}}function B0(n){return Xf(n)!==null}function kn(n){return n>=1024*1024?`${(n/(1024*1024)).toFixed(1)}MB`:n>=1024?`${(n/1024).toFixed(0)}KB`:`${n}B`}function Ib(n){let e=n.trim();if(e.length===0)return null;let t=[],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(!B0(i))return null;t.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!O0(o))return null;t.push(o)}return t.length>0?t:null}var cs,kb,L0,rl=V(()=>{"use strict";cs=10*1024*1024,kb={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};L0=new Set(Object.values(kb))});import{spawn as N0}from"child_process";import Zf from"fs/promises";import D0 from"os";import H0 from"path";async function ol(n={}){let e={...ep,...n};return e.platform==="darwin"?W0(e):e.platform==="linux"?z0(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Cb(n={}){let e={...ep,...n},t,s;if(e.platform==="darwin")t="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await $o(e,"wl-paste"))t="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await $o(e,"xclip"))t="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 qa(e.spawn,t,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:tp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Rb(n,e={}){let{target:t="both",...s}=e,r={...ep,...s},i=await U0(r,n,t);if(i.ok)return i;let o=j0(r,n,t);return o.ok||o.reason!==Tb?o:i}async function U0(n,e,t){let s=Buffer.from(e,"utf-8");if(n.platform==="darwin")try{return await il(n.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(n.platform==="linux"){let r=t==="clipboard"||t==="both",i=t==="primary"||t==="both";return n.env.WAYLAND_DISPLAY&&await $o(n,"wl-copy")?Ab(n,s,"wl-copy",[],["--primary"],r,i):n.env.DISPLAY&&await $o(n,"xclip")?Ab(n,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 ${n.platform}`}}async function Ab(n,e,t,s,r,i,o){let a=t;if(i){try{await il(n.spawn,t,s,e)}catch{return{ok:!1,reason:`${t} failed`}}if(o)try{await il(n.spawn,t,r,e)}catch{}return{ok:!0,method:a}}try{return await il(n.spawn,t,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${t} failed`}}}function j0(n,e,t){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>xb)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${xb} bytes)`};let i=`\x1B]52;${t==="both"?"cp":t==="primary"?"p":"c"};${s}\x07`;return n.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(n.ttyWrite??q0)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Tb}}function q0(n){let e=[process.stderr,process.stdout];for(let t of e)if(t&&t.isTTY)try{return t.write(n),!0}catch{}return!1}async function W0(n){let e=H0.join(n.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),t=["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 t)s.push("-e",r);try{await Eb(n.spawn,"osascript",s);let r=await Q0(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Zf.unlink(e).catch(()=>{})}try{let r=await qa(n.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:tp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function z0(n){let e=await K0(n);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let t=await V0(n,e),s=Y0(t);if(s)try{let r=await qa(n.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>cs?{ok:!1,reason:`clipboard image is ${kn(r.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await qa(n.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:tp(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function K0(n){return n.env.WAYLAND_DISPLAY&&await $o(n,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:n.env.DISPLAY&&await $o(n,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function Y0(n){let e=new Set(n.map(t=>t.toLowerCase()));for(let t of J0)if(e.has(t))return t;return null}async function V0(n,e){try{return(await qa(n.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
196
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function tp(n){return n.replace(/\r\n?/g,`
197
+ `)}async function $o(n,e){try{return await Eb(n.spawn,"which",[e]),!0}catch{return!1}}async function Q0(n,e){try{let t=await Zf.readFile(n);return e&&await Zf.unlink(n).catch(()=>{}),t.length===0?{ok:!1,reason:"no image on clipboard"}:t.length>cs?{ok:!1,reason:`clipboard image is ${kn(t.length)}, max ${kn(cs)}`}:{ok:!0,kind:"image",attachment:{mimeType:ja(n)??"image/png",data:t.toString("base64"),sizeBytes:t.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Eb(n,e,t){return new Promise((s,r)=>{let i=n(e,t);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 il(n,e,t,s){return new Promise((r,i)=>{let o=n(e,t,{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 qa(n,e,t){return new Promise((s,r)=>{let i=n(e,t),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var ep,xb,Tb,J0,al=V(()=>{"use strict";rl();ep={platform:process.platform,env:process.env,spawn:N0,tmpdir:D0.tmpdir};xb=74994;Tb="no TTY available for OSC 52 clipboard write";J0=["image/png","image/jpeg","image/gif","image/webp"]});function X0(n,e){return`[pasted #${n} +${e} lines]`}var G0,Wa,np,Z0,_s,sp=V(()=>{"use strict";G0=/\[pasted #(\d+) \+\d+ lines\]/g,Wa=/\[pasted #(\d+) \+\d+ lines\]$/,np=/^\[pasted #(\d+) \+\d+ lines\]/;Z0=500,_s=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastTapKey=null;lastTapAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>Z0&&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,t,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(t,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,t=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...t],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.clearDoubleTap(),this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){if(this.clearDoubleTap(),e.text.length===0)return[{type:"attachment-request",source:"clipboard"}];this.recordEdit();let t=e.text.split(`
198
+ `).length;if(this.collapsePastes&&t>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(X0(s,t))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(this.lastTapKey!==null&&this.lastTapKey!==e&&this.clearDoubleTap(),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.bufferIsEmpty()?this.consumeDoubleTap("left")?[{type:"switch-session"}]:(this.armDoubleTap("left"),[]):(this.moveLeft(),[]);case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"alt-backspace":return this.recordEdit(),this.killWordAlpha(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":return this.turnRunning?(this.clearDoubleTap(),[{type:"cancel",prefill:!0}]):this.consumeDoubleTap("escape")?[{type:"switch-session"}]:(this.armDoubleTap("escape"),[])}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
199
+ `)}expandPastes(e){return e.replace(G0,(t,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:t})}armDoubleTap(e){this.lastTapKey=e,this.lastTapAt=Date.now()}consumeDoubleTap(e){return this.lastTapKey===e&&this.lastTapAt!==null&&Date.now()-this.lastTapAt<=500?(this.clearDoubleTap(),!0):!1}clearDoubleTap(){this.lastTapKey=null,this.lastTapAt=null}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
200
200
  `)){this.insertText(e);return}let t=this.currentLine();this.setCurrentLine(t.slice(0,this.col)+e+t.slice(this.col)),this.col+=e.length}insertText(e){let t=e.split(`
201
- `);if(t.length===1){this.insertChar(t[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=t[0]??"",a=t[t.length-1]??"",c=t.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=t.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),t=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(t),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(qa);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]??"",t=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+t}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(tp);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 t=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+t)}}killLine(){if(this.col>0){let t=this.currentLine();this.killBuffer=t.slice(0,this.col),this.setCurrentLine(t.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
201
+ `);if(t.length===1){this.insertChar(t[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=t[0]??"",a=t[t.length-1]??"",c=t.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=t.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),t=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(t),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(Wa);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]??"",t=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+t}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(np);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 t=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+t)}}killLine(){if(this.col>0){let t=this.currentLine();this.killBuffer=t.slice(0,this.col),this.setCurrentLine(t.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
202
202
  `,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+`
203
203
  `,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=`
204
204
  `,this.buffer.splice(this.row,1);return}let t=this.buffer[this.row+1]??"";this.killBuffer=`
205
- `+t,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(qa);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}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(qa);if(s!==null){this.killBuffer=s[0];let a=this.col-s[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let r=/[A-Za-z0-9_]/,i=this.col;for(;i>0&&!r.test(e[i-1]??"");)i-=1;for(;i>0&&r.test(e[i-1]??"");)i-=1;let o=e.slice(i,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let t=this.currentLine().slice(0,this.col).match(qa);if(t!==null){this.col-=t[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(tp);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(),t=this.col;for(;t>0&&/\s/.test(e[t-1]??"");)t-=1;let r=e.slice(0,t).match(qa);if(r!==null){this.col=t-r[0].length;return}for(;t>0&&!/\s/.test(e[t-1]??"");)t-=1;this.col=t}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 t=this.col;for(;t<e.length&&/\s/.test(e[t]??"");)t+=1;let r=e.slice(t).match(tp);if(r!==null){this.col=t+r[0].length;return}for(;t<e.length&&!/\s/.test(e[t]??"");)t+=1;this.col=t}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 t=this.findHistoryMatches(e);return t.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:t,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[t[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 t=this.findHistoryMatches(e);if(t.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=t,this.historySearch.cursor=0,this.loadEntry(this.history[t[0]]??""),[]}findHistoryMatches(e){let t=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&t.push(s)}return t}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(`
206
- `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:t,displayText:e,attachments:o}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=t.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:t,displayText:e,planMode:o,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,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,t=(this.buffer[e]??"").length;return this.row!==e||this.col!==t?(this.row=e,this.col=t,[]):[{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 _o,al,sp=V(()=>{"use strict";_o=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,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}paintRow(e,t,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==t&&(this.lastFrameRows.set(e,t),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},al=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 V0 from"string-width";function Cb(n,e){if(!n||e<=0)return 0;let t=0;for(let s of Q0.segment(n)){let r=V0(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function Rb(n,e){if(e<=0)return 0;let t=0,s=0;for(let r of n)if(r.width>0&&e<t+r.width||(t+=r.width,s+=r.text.length,r.width>0&&e===t))return s;return s}var Q0,Tb=V(()=>{"use strict";Q0=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function G0(){Wa===0&&process.stdout.write(Cw),Wa++}function X0(){Wa!==0&&(Wa--,Wa===0&&process.stdout.write(Rw))}function Oe(n){G0();try{n()}finally{X0()}}var Wa,rp=V(()=>{"use strict";$a();Wa=0});import{spawn as Z0}from"child_process";import{statSync as Eb}from"fs";import{homedir as Pb}from"os";import{isAbsolute as Mb,resolve as eT}from"path";import Ye from"string-width";import tT from"wrap-ansi";function uT(n){let e=n.replace(/\r\n?$|\n$/,"");return lT.test(e)?e:null}function fT(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function pT(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function hT(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let t=n.iterm2Image,s=e.iterm2Image;if(t===void 0!=(s===void 0)||t&&s&&(t.data!==s.data||t.heightCells!==s.heightCells))return!1;let r=n.links,i=e.links;if(r===void 0!=(i===void 0))return!1;if(r&&i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++){let a=r[o],c=i[o];if(a.start!==c.start||a.end!==c.end||a.url!==c.url)return!1}}return!0}function $b(n,e,t,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!t)return`${n}|${e}|empty|${s??""}|${o}|${a}`;let c=t.iterm2Image?`i${t.iterm2Image.heightCells}:${t.iterm2Image.data.length}`:"";return`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function ds(n,e){let t=[];for(let s=0;s<n.length;s++){let r=n[s]??"";if(r.length===0){t.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){t.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),t.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function _s(n,e,t){let s=0,r=0,i=-1;for(let c=0;c<n.length;c++){let d=n[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=n[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(t,Math.max(1,n.length)),a=0;return n.length>o&&(a=Math.max(0,Math.min(n.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 Fb(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){Ms(n,e,t,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){Ms(n,e.slice(c),t,o);return}d>c&&Ms(n,e.slice(c,d),t,o);let l=r!==null&&d===r;Ms(n,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function za(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function Ms(n,e,t,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{n.noFormat(a)};switch(t){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),n.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),n.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),n.brightYellow.noFormat(e),o(i);return;case"tool":o(r),n.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),n.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);n.bgColorGrayscale(25)(a);return}case"code":{n.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}switch(t){case"user":n.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":n(e);return;case"thought":n.brightBlack(e);return;case"tool":n.brightBlue.noFormat(e);return;case"tool-status-ok":n.dim.noFormat(e);return;case"tool-status-fail":n.bold.red.noFormat(e);return;case"tool-status-pending":n.dim.noFormat(e);return;case"tool-status-running":n.brightYellow.noFormat(e);return;case"tool-status-cancelled":n.dim.noFormat(e);return;case"plan":n.brightYellow(e);return;case"plan-done":n.green(e);return;case"plan-pending":n.dim(e);return;case"system":n.brightYellow.noFormat(e);return;case"info":n.cyan.noFormat(e);return;case"dim":n.dim.noFormat(e);return;case"code":n.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":n.bold.brightYellow(e);return;case"heading-2":n.bold.brightCyan(e);return;case"heading-3":n.bold(e);return;case"search-highlight":n.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":n.inverse.noFormat(e);return;case"search-highlight-active":n.bgRed.brightWhite.noFormat(e);return;default:n.noFormat(e)}}}function mT(n,e){return e<=0?[n]:n.length===0?[""]:tT(n,e,{hard:!0,trim:!1}).split(`
207
- `)}function qb(n){jb=n}function Wb(n,e){if(n==="wide")return!0;if(n==="narrow")return!1;let t=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(t)||e.TERM_PROGRAM==="Apple_Terminal")}function hr(n){return Ye(n,{ambiguousIsNarrow:!jb})}function yT(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function wT(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let r=n.charCodeAt(t);if(r<48||r>63)break;t+=1}for(;t<n.length;){let r=n.charCodeAt(t);if(r<32||r>47)break;t+=1}if(t>=n.length)return null;let s=n.charCodeAt(t);return s<64||s>126?null:n.slice(e,t+1)}function $o(n,e){if(n.charCodeAt(e)===27){let s=yT(n,e);if(s!==null)return{text:s,width:0};let r=wT(n,e);return r!==null?{text:r,width:0}:null}if(n.charCodeAt(e)!==94)return null;let t=n[e+1];if(t===void 0)return null;if(t==="^")return{text:"^^",width:1};if(t==="["){let s=n.indexOf("]",e+2);if(s!==-1)return{text:n.slice(e,s+1),width:0}}return gT.test(t)?{text:n.slice(e,e+2),width:0}:null}function pp(n){let e=new Array(n.length+1).fill(0),t="",s=0;for(;s<n.length;){e[s]=t.length;let r=$o(n,s);if(r){r.width>0&&(t+="^");for(let i=1;i<r.text.length;i++)e[s+i]=t.length;s+=r.text.length;continue}t+=n[s],s+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function Ob(n){if(!n.includes("^")&&!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let s=$o(n,t);if(s){s.width>0&&(e+="^"),t+=s.text.length;continue}e+=n[t],t+=1}return e}function bT(n){if(!n.includes("^")&&!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let s=$o(n,t);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}t+=s.text.length;continue}t+=1}return e}function zb(n){if(!n.includes("^")&&!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if($o(n,e))return!0;return!1}function Lb(n,e){let t=n.indexOf("^",e),s=n.indexOf("\x1B",e);return t===-1?s:s===-1?t:Math.min(t,s)}function*mp(n){let e=0;for(;e<n.length;){let t=$o(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let s=n.length,r=Lb(n,e);for(;r!==-1&&r<n.length;){if($o(n,r)){s=r;break}r=Lb(n,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of hp.segment(n.slice(e,s)))yield{text:i,width:hr(i)};e=s}}function vT(n,e,t){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${n}\x07`;return t?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function ST(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let s=t.stripMarkup===!0&&zb(n);return!s&&!Ub.test(n)?kT(n,e):IT(n,e,s)}function kT(n,e){let t=[],s=n;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?(t.push(s.slice(0,e)),s=s.slice(e)):(t.push(s.slice(0,i)),s=s.slice(i+1))}return t.push(s),t}function IT(n,e,t){let s=[],r=t?[...mp(n)]:xT(n),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 xT(n){let e=[];for(let{segment:t}of hp.segment(n))e.push({text:t,width:hr(t)});return e}function At(n,e,t={}){if(e<=0)return"";let s=t.stripMarkup===!0&&zb(n);if(!s&&n.length<=e&&!Ub.test(n))return n;if(!s)return hr(n)<=e?n:e<=1?Bb(n,e):Bb(n,e-1)+"\u2026";let r=[...mp(n)],i=0;for(let o of r)i+=o.width;return i<=e?n:e<=1?Nb(r,e):Nb(r,e-1)+"\u2026"}function Bb(n,e){if(e<=0)return"";let t="",s=0;for(let{segment:r}of hp.segment(n)){let i=hr(r);if(s+i>e)break;t+=r,s+=i}return t}function Nb(n,e){if(e<=0)return"";let t="",s=0;for(let r of n){if(s+r.width>e)break;t+=r.text,s+=r.width}return t}function AT(n){let e=n.indexOf(`
208
- `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function Db(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${ul(n.used)}/${ul(n.size)}`):e.push(ul(n.used)):typeof n.size=="number"&&e.push(`/${ul(n.size)}`),typeof n.costAmount=="number"&&e.push(pf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function ul(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function pl(n){switch(n){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"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function ti(){let n=[xo,Ao,Sw,Co,kw,Df,Ts,Qr,Gr,Vr,Yr,"\x1B>",Ma,zc,Kc,"\x1B]9;4;0\x07",yw].join("");try{process.stdout.write(n)}catch{}}function Kb(n){let e=[["width",80],["height",24]];for(let[t,s]of e){let r=Object.getOwnPropertyDescriptor(n,t);if(r&&r.get)continue;let i=Symbol(`raw-${t}`),o=n;o[i]=r?r.value:void 0,Object.defineProperty(n,t,{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 Hb(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===95?"alt-underscore":null:null}var ip,dl,cl,op,ap,nT,_b,sT,Je,tt,rT,nt,dp,cp,iT,oT,aT,lp,up,fp,dT,cT,lT,fl,Ub,hp,jb,gT,ll,gp=V(()=>{"use strict";sp();hf();ve();Xn();sl();So();Tb();ol();rp();Or();$a();ip=500,dl=1,cl=/[A-Za-z0-9_]/,op=/[A-Za-z0-9_./\-~+@]/,ap=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,nT=/[.,;:!?)\]}'"]/,_b=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,sT=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Je=1,tt=0,rT=1,nt=1,dp=8,cp=5,iT=12,oT=12,aT=30,lp=6,up=4,fp=2,dT=1e3,cT=1e4,lT=/^(https?|ftp):\/\/\S+$/;fl=class n{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),t(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??dT,this.painter=new _o(this.term),this.scheduler=new al({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??cT,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(Nf),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),oe({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),oe({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Kc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Ma),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(ti(),this.term.fullscreen(!1),this.term(`
209
- `)))}installBracketedPaste(){process.stdout.write(Wc),process.stdout.write(bw),process.stdout.write(vw),process.stdout.write(ww),process.stdout.write(Jc);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(Ts),process.stdout.write(Qr),process.stdout.write(Gr),process.stdout.write(Vr),process.stdout.write(_a),process.stdout.write(Yr),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(Iw),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(Df),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>ti(),this.onProcessSignal=e=>{ti(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{ti(),process.stderr.write(`
205
+ `+t,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(Wa);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}killWordAlpha(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(Wa);if(s!==null){this.killBuffer=s[0];let a=this.col-s[0].length;this.setCurrentLine(e.slice(0,a)+e.slice(this.col)),this.col=a;return}let r=/[A-Za-z0-9_]/,i=this.col;for(;i>0&&!r.test(e[i-1]??"");)i-=1;for(;i>0&&r.test(e[i-1]??"");)i-=1;let o=e.slice(i,this.col);o.length>0&&(this.killBuffer=o),this.setCurrentLine(e.slice(0,i)+e.slice(this.col)),this.col=i}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let t=this.currentLine().slice(0,this.col).match(Wa);if(t!==null){this.col-=t[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(np);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(),t=this.col;for(;t>0&&/\s/.test(e[t-1]??"");)t-=1;let r=e.slice(0,t).match(Wa);if(r!==null){this.col=t-r[0].length;return}for(;t>0&&!/\s/.test(e[t-1]??"");)t-=1;this.col=t}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 t=this.col;for(;t<e.length&&/\s/.test(e[t]??"");)t+=1;let r=e.slice(t).match(np);if(r!==null){this.col=t+r[0].length;return}for(;t<e.length&&!/\s/.test(e[t]??"");)t+=1;this.col=t}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 t=this.findHistoryMatches(e);return t.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:t,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[t[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 t=this.findHistoryMatches(e);if(t.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=t,this.historySearch.cursor=0,this.loadEntry(this.history[t[0]]??""),[]}findHistoryMatches(e){let t=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&t.push(s)}return t}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(`
206
+ `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),t.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:t,displayText:e,attachments:o}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:t,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),t=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=t.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:t,displayText:e,planMode:o,attachments:a}]}if(t.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:t,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,t=(this.buffer[e]??"").length;return this.row!==e||this.col!==t?(this.row=e,this.col=t,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.recordEdit(),this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});var Fo,dl,rp=V(()=>{"use strict";Fo=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,t){return e!==this.lastFrameW||t!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=t,!0):!1}paintRow(e,t,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==t&&(this.lastFrameRows.set(e,t),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},dl=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 eT from"string-width";function Pb(n,e){if(!n||e<=0)return 0;let t=0;for(let s of tT.segment(n)){let r=eT(s.segment);if(e<t+r)return s.index;if(t+=r,e===t)return s.index+s.segment.length}return n.length}function Mb(n,e){if(e<=0)return 0;let t=0,s=0;for(let r of n)if(r.width>0&&e<t+r.width||(t+=r.width,s+=r.text.length,r.width>0&&e===t))return s;return s}var tT,_b=V(()=>{"use strict";tT=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function nT(){za===0&&process.stdout.write(Pw),za++}function sT(){za!==0&&(za--,za===0&&process.stdout.write(Mw))}function Oe(n){nT();try{n()}finally{sT()}}var za,ip=V(()=>{"use strict";Fa();za=0});import{spawn as rT}from"child_process";import{statSync as $b}from"fs";import{homedir as Fb}from"os";import{isAbsolute as Ob,resolve as iT}from"path";import Ye from"string-width";import oT from"wrap-ansi";function gT(n){let e=n.replace(/\r\n?$|\n$/,"");return mT.test(e)?e:null}function yT(n,e){return!n||typeof n!="object"?!1:n[e]===!0}function wT(n){return n.includes("LEFT")?"left":n.includes("RIGHT")?"right":n.includes("MIDDLE")?"middle":n==="MOUSE_DRAG"||n==="MOUSE_BUTTON_RELEASED"?"left":"other"}function bT(n,e){if(n.body!==e.body||(n.prefix??"")!==(e.prefix??"")||(n.bodyStyle??"")!==(e.bodyStyle??"")||(n.prefixStyle??"")!==(e.prefixStyle??"")||!!n.ansi!=!!e.ansi||!!n.fillRow!=!!e.fillRow||!!n.collapsed!=!!e.collapsed||(n.blockKey??"")!==(e.blockKey??"")||(n.hoverSubKey??"")!==(e.hoverSubKey??""))return!1;let t=n.iterm2Image,s=e.iterm2Image;if(t===void 0!=(s===void 0)||t&&s&&(t.data!==s.data||t.heightCells!==s.heightCells))return!1;let r=n.links,i=e.links;if(r===void 0!=(i===void 0))return!1;if(r&&i){if(r.length!==i.length)return!1;for(let o=0;o<r.length;o++){let a=r[o],c=i[o];if(a.start!==c.start||a.end!==c.end||a.url!==c.url)return!1}}return!0}function Bb(n,e,t,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!t)return`${n}|${e}|empty|${s??""}|${o}|${a}`;let c=t.iterm2Image?`i${t.iterm2Image.heightCells}:${t.iterm2Image.data.length}`:"";return`${n}|${e}|${t.prefix??""}|${t.prefixStyle??""}|${t.body}|${t.bodyStyle??""}|${t.ansi?"1":"0"}|${t.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function ls(n,e){let t=[];for(let s=0;s<n.length;s++){let r=n[s]??"";if(r.length===0){t.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){t.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),t.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return t.length===0&&t.push({bufferIdx:0,startCol:0,endCol:0}),t}function Fs(n,e,t){let s=0,r=0,i=-1;for(let c=0;c<n.length;c++){let d=n[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=n[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(t,Math.max(1,n.length)),a=0;return n.length>o&&(a=Math.max(0,Math.min(n.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 Nb(n,e,t,s,r=null,i=0,o=!1){if(e.length===0)return;if(s.length===0){$s(n,e,t,o);return}let a=e.toLowerCase(),c=0;for(;c<e.length;){let d=a.indexOf(s,c);if(d===-1){$s(n,e.slice(c),t,o);return}d>c&&$s(n,e.slice(c,d),t,o);let l=r!==null&&d===r;$s(n,e.slice(d,d+s.length),l?"search-highlight-active":"search-highlight",o),c=d+s.length}}function Ka(n){return n==="agent"||n==="thought"||n==="heading-1"||n==="heading-2"||n==="heading-3"||n==="plan"||n==="plan-done"||n==="plan-pending"}function $s(n,e,t,s=!1){if(e.length!==0){if(s){let r="\x1B[48;5;236m",i="\x1B[49m",o=a=>{n.noFormat(a)};switch(t){case"dim":case"tool-status-ok":case"tool-status-pending":case"tool-status-cancelled":o(r),n.dim.noFormat(e),o(i);return;case"tool-status-fail":o(r),n.bold.red.noFormat(e),o(i);return;case"tool-status-running":o(r),n.brightYellow.noFormat(e),o(i);return;case"tool":o(r),n.brightBlue.noFormat(e),o(i);return;case"plan-pending":o(r),n.dim(e),o(i);return;case"thought":{let a=e.replace(/\^\^|\^K/g,c=>c==="^K"?"\x1B[39m":c);n.bgColorGrayscale(25)(a);return}case"code":{n.noFormat(`\x1B[48;2;22;25;36m${e}\x1B[49m`);return}}}switch(t){case"user":n.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":n(e);return;case"thought":n.brightBlack(e);return;case"tool":n.brightBlue.noFormat(e);return;case"tool-status-ok":n.dim.noFormat(e);return;case"tool-status-fail":n.bold.red.noFormat(e);return;case"tool-status-pending":n.dim.noFormat(e);return;case"tool-status-running":n.brightYellow.noFormat(e);return;case"tool-status-cancelled":n.dim.noFormat(e);return;case"plan":n.brightYellow(e);return;case"plan-done":n.green(e);return;case"plan-pending":n.dim(e);return;case"system":n.brightYellow.noFormat(e);return;case"info":n.cyan.noFormat(e);return;case"dim":n.dim.noFormat(e);return;case"code":n.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":n.bold.brightYellow(e);return;case"heading-2":n.bold.brightCyan(e);return;case"heading-3":n.bold(e);return;case"search-highlight":n.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":n.inverse.noFormat(e);return;case"search-highlight-active":n.bgRed.brightWhite.noFormat(e);return;default:n.noFormat(e)}}}function vT(n,e){return e<=0?[n]:n.length===0?[""]:oT(n,e,{hard:!0,trim:!1}).split(`
207
+ `)}function Jb(n){Kb=n}function Yb(n,e){if(n==="wide")return!0;if(n==="narrow")return!1;let t=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(t)||e.TERM_PROGRAM==="Apple_Terminal")}function gr(n){return Ye(n,{ambiguousIsNarrow:!Kb})}function kT(n,e){if(!n.startsWith("\x1B]8;",e))return null;for(let t=e+4;t<n.length;t++){if(n[t]==="\x07")return n.slice(e,t+1);if(n[t]==="\x1B"&&n[t+1]==="\\")return n.slice(e,t+2)}return null}function IT(n,e){if(!n.startsWith("\x1B[",e))return null;let t=e+2;for(;t<n.length;){let r=n.charCodeAt(t);if(r<48||r>63)break;t+=1}for(;t<n.length;){let r=n.charCodeAt(t);if(r<32||r>47)break;t+=1}if(t>=n.length)return null;let s=n.charCodeAt(t);return s<64||s>126?null:n.slice(e,t+1)}function Nn(n,e){if(n.charCodeAt(e)===27){let s=kT(n,e);if(s!==null)return{text:s,width:0};let r=IT(n,e);return r!==null?{text:r,width:0}:null}if(n.charCodeAt(e)!==94)return null;let t=n[e+1];if(t===void 0)return null;if(t==="^")return{text:"^^",width:1};if(t==="["){let s=n.indexOf("]",e+2);if(s!==-1)return{text:n.slice(e,s+1),width:0}}return ST.test(t)?{text:n.slice(e,e+2),width:0}:null}function hp(n){let e=new Array(n.length+1).fill(0),t="",s=0;for(;s<n.length;){e[s]=t.length;let r=Nn(n,s);if(r){r.width>0&&(t+="^");for(let i=1;i<r.text.length;i++)e[s+i]=t.length;s+=r.text.length;continue}t+=n[s],s+=1}return e[n.length]=t.length,{clean:t,rawToClean:e}}function mp(n,e,t){let s=0,r=e;for(;r<t;){let i=Nn(n,r);if(i){r+=i.text.length,i.width>0&&(s+=1);continue}s+=1,r+=1}return s}function gp(n,e,t){let s=e;for(;t>0&&s<n.length;){let r=Nn(n,s);if(r){s+=r.text.length,r.width>0&&(t-=1);continue}s+=1,t-=1}return s}function Db(n){if(!n.includes("^")&&!n.includes("\x1B"))return n;let e="",t=0;for(;t<n.length;){let s=Nn(n,t);if(s){s.width>0&&(e+="^"),t+=s.text.length;continue}e+=n[t],t+=1}return e}function xT(n){if(!n.includes("^")&&!n.includes("\x1B"))return"";let e="",t=0;for(;t<n.length;){let s=Nn(n,t);if(s){if(s.width===0){let r=s.text.charCodeAt(0);(r===94||r===27&&s.text.charCodeAt(1)===91)&&(e+=s.text)}t+=s.text.length;continue}t+=1}return e}function Vb(n){if(!n.includes("^")&&!n.includes("\x1B"))return!1;for(let e=0;e<n.length;e++)if(Nn(n,e))return!0;return!1}function Hb(n,e){let t=n.indexOf("^",e),s=n.indexOf("\x1B",e);return t===-1?s:s===-1?t:Math.min(t,s)}function*wp(n){let e=0;for(;e<n.length;){let t=Nn(n,e);if(t){yield{text:t.text,width:t.width},e+=t.text.length;continue}let s=n.length,r=Hb(n,e);for(;r!==-1&&r<n.length;){if(Nn(n,r)){s=r;break}r=Hb(n,r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of yp.segment(n.slice(e,s)))yield{text:i,width:gr(i)};e=s}}function AT(n,e,t){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${n}\x07`;return t?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function CT(n,e,t={}){if(e<=0)return[n];if(n.length===0)return[""];let s=t.stripMarkup===!0&&Vb(n);return!s&&!zb.test(n)?RT(n,e):TT(n,e,s)}function RT(n,e){let t=[],s=n;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?(t.push(s.slice(0,e)),s=s.slice(e)):(t.push(s.slice(0,i)),s=s.slice(i+1))}return t.push(s),t}function TT(n,e,t){let s=[],r=t?[...wp(n)]:ET(n),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 ET(n){let e=[];for(let{segment:t}of yp.segment(n))e.push({text:t,width:gr(t)});return e}function At(n,e,t={}){if(e<=0)return"";let s=t.stripMarkup===!0&&Vb(n);if(!s&&n.length<=e&&!zb.test(n))return n;if(!s)return gr(n)<=e?n:e<=1?Ub(n,e):Ub(n,e-1)+"\u2026";let r=[...wp(n)],i=0;for(let o of r)i+=o.width;return i<=e?n:e<=1?jb(r,e):jb(r,e-1)+"\u2026"}function Ub(n,e){if(e<=0)return"";let t="",s=0;for(let{segment:r}of yp.segment(n)){let i=gr(r);if(s+i>e)break;t+=r,s+=i}return t}function jb(n,e){if(e<=0)return"";let t="",s=0;for(let r of n){if(s+r.width>e)break;t+=r.text,s+=r.width}return t}function PT(n){let e=n.indexOf(`
208
+ `);return e===-1?n:`${n.slice(0,e)} \u21B5`}function qb(n){if(!n)return null;let e=[];return typeof n.used=="number"?typeof n.size=="number"&&n.size>0?e.push(`${fl(n.used)}/${fl(n.size)}`):e.push(fl(n.used)):typeof n.size=="number"&&e.push(`/${fl(n.size)}`),typeof n.costAmount=="number"&&e.push(hf(n.costAmount,n.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function fl(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(1)}k`:`${n}`}function hl(n){switch(n){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"ALT_BACKSPACE":case"META_BACKSPACE":return"alt-backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function yr(){let n=[Co,Ro,Aw,To,Cw,Hf,Ps,Zr,ei,Xr,Gr,"\x1B>",_a,Kc,Jc,"\x1B]9;4;0\x07",Sw].join("");try{process.stdout.write(n)}catch{}}function Qb(n){let e=[["width",80],["height",24]];for(let[t,s]of e){let r=Object.getOwnPropertyDescriptor(n,t);if(r&&r.get)continue;let i=Symbol(`raw-${t}`),o=n;o[i]=r?r.value:void 0,Object.defineProperty(n,t,{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 Wb(n,e){let t={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?t[n]??null:n===27?"escape":n===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:n===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:n===127&&e===1?"backspace":n===127&&e===3||n===8&&e===3?"alt-backspace":(n===95||n===47)&&e===5?"ctrl-underscore":(n===95||n===47)&&e===7?"alt-underscore":e===3?n===98||n===66?"alt-b":n===102||n===70?"alt-f":n===110||n===78?"alt-n":n===95?"alt-underscore":null:null}var op,cl,ll,ap,dp,aT,Lb,dT,Je,tt,cT,nt,cp,lp,lT,uT,fT,up,fp,pp,pT,hT,mT,pl,zb,yp,Kb,ST,ul,bp=V(()=>{"use strict";rp();mf();ve();Zn();rl();Io();_b();al();ip();Nr();Fa();op=500,cl=1,ll=/[A-Za-z0-9_]/,ap=/[A-Za-z0-9_./\-~+@]/,dp=/[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%\-]/,aT=/[.,;:!?)\]}'"]/,Lb=/^hydra:\/\/(?:[^/\s]+\/)?sessions\/([A-Za-z0-9_-]+)(?:#turn-(\d+))?$/,dT=/^[A-Za-z0-9][A-Za-z0-9_-]{7,}$/,Je=1,tt=0,cT=1,nt=1,cp=8,lp=5,lT=12,uT=12,fT=30,up=6,fp=4,pp=2,pT=1e3,hT=1e4,mT=/^(https?|ftp):\/\/\S+$/;pl=class n{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onHydraLinkClick;onMouse;onHoverRun;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;synthesisIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;hoveredBannerHit=null;hoveredBlockKey=null;hoveredSubKey=null;hoveredRunKeys=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;pendingClickCount=1;doubleClickPending=!1;lastLeftClick=null;autoscrollTimer=null;autoscrollCell=null;autoscrollDir=1;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;terminalFocused=!0;lastFocusInAt=0;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let t=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),t(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onHydraLinkClick=e.onHydraLinkClick,this.onMouse=e.onMouse,this.onHoverRun=e.onHoverRun,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??pT,this.painter=new Fo(this.term),this.scheduler=new dl({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??hT,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(Df),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),oe({src:"grab",site:"screen.start",on:!0}),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.stopAutoscroll(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),oe({src:"grab",site:"screen.stop",on:!1}),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Jc),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(_a),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(yr(),this.term.fullscreen(!1),this.term(`
209
+ `)))}installBracketedPaste(){process.stdout.write(zc),process.stdout.write(Iw),process.stdout.write(xw),process.stdout.write(kw),process.stdout.write(Yc);let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){process.stdout.write(Ps),process.stdout.write(Zr),process.stdout.write(ei),process.stdout.write(Xr),process.stdout.write($a),process.stdout.write(Gr),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(Rw),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(Hf),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>yr(),this.onProcessSignal=e=>{yr(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{yr(),process.stderr.write(`
210
210
  uncaught: ${e.stack??e.message}
211
- `),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(xw),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=t.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){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");oe({tag:"raw",bytes:s,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=t.indexOf("\x1B[I"),i=t.indexOf("\x1B[O"),o=r===-1?i:i===-1?r:Math.min(r,i);if(o===-1)break;let a=o===r;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),t=t.slice(0,o)+t.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(Io)){this.handleRawStdinSegment(t);return}if(t.includes(`
211
+ `),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(Tw),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let t=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=t.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){if(process.env.HYDRA_TUI_KEY_TRACE){let s=Array.from(e).map(r=>"0x"+r.toString(16).padStart(2,"0")).join(" ");oe({tag:"raw",bytes:s,len:e.length})}let t=e.toString("binary");if(t=this.consumeSelectiveMouseSequences(t),t.includes("\x1B[I")||t.includes("\x1B[O")){let s=this.terminalFocused;for(;;){let r=t.indexOf("\x1B[I"),i=t.indexOf("\x1B[O"),o=r===-1?i:i===-1?r:Math.min(r,i);if(o===-1)break;let a=o===r;this.terminalFocused=a,a&&(this.lastFocusInAt=Date.now()),t=t.slice(0,o)+t.slice(o+"\x1B[I".length)}this.terminalFocused!==s&&this.scheduleRepaint()}if(t.length!==0){if(this.pasteActive){this.handleRawStdinSegment(t);return}if(t===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(t==="\x1B[27;5;122~"||t==="\x1B[122;5u")){this.onSuspend();return}if(t===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(t==="\x1B"||t==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(t==="\x1B\x7F"||t==="\x1B\b"){this.onKey([{type:"key",name:"alt-backspace"}]);return}if(t.startsWith("\x1B\x7F")||t.startsWith("\x1B\b")){this.onKey([{type:"key",name:"alt-backspace"}]),this.handleRawStdin(Buffer.from(t.slice(2),"binary"));return}if(/\x1b\[27;\d+;\d+~/.test(t)){this.handleCsi27Stdin(t);return}if(t.includes(Ao)){this.handleRawStdinSegment(t);return}if(t.includes(`
212
212
  `)){let s=t.split(`
213
- `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:t.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(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=t.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=Hb(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 t=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=t.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=Hb(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 t=Io,s=Pa;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,`
214
- `);this.pasteBuffer="";let a=bb(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(t);if(r===-1){let i=uT(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+t.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 t=this.term.width;return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let s of e)t+=this.wrappedRowsOf(s);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let s of t)this.forgetLine(s);this.invalidateSelectionIfTouches(t);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let o of t)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=t.length-s.count,d=this.lines.slice(s.start,o),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=d[f],h=t[f];p!==void 0&&hT(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=t.length;f<d.length;f++)u.push(d[f]);this.lines.splice(s.start,s.count,...l);for(let f of u)this.forgetLine(f);for(let f of l)this.lineIds.has(f)||this.trackLine(f);if(this.invalidateSelectionIfTouches(u),s.count=t.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=c);i=this.wrappedRowsOfMany(t)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),i=this.wrappedRowsOfMany(t);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,s,r){if(e.length===0)return;let i=e.split(`
215
- `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),c+=this.wrappedRowsOf(p)}}let l={prefix:t,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(t.length);for(let l of a){let u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=ll(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:t,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Oe(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),oe({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,t){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.sourceLineId),i=s<r||s===r&&e.offset<=t.offset,o=i?e:t,a=i?t:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let t=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.startLineId),i=this.lineIndexById(t.endLineId);if(s<0||r<0||i<0)return null;let o=(u,f,p,h)=>u!==p?u-p:f-h,a=o(s,e.offset,r,t.startOffset),c=o(s,e.offset,i,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(c>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-t.endOffset)>=d?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];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 c=(r.body??"").slice(o.start,o.end);(za(r.bodyStyle)||r.ansi)&&(c=Ob(c)),t.push(c)}return t.join(`
216
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(t===-1||s===-1)return null;let r=t,i=s,o=e.startOffset,a=e.endOffset;t>s&&(r=s,i=t,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=t.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,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let s=this.lineIds.get(t);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 t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(t.start,s)),o=this.lines.splice(t.start,t.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>t.start&&(c.start-=t.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 t=e.start+e.count;if(t>=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>=t&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),i=this.lines.splice(t.start,t.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>t.start&&(o.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let s=[...t].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=c&&u.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,t,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=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(Nf),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&this.clearSelection(),this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(t=>({...t}))}: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 t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!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},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let t=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){t=!1;break}if(t)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;t&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=t!==void 0&&t.start+t.count===this.lines.length,r=s?t.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(t.start,0,o),t.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,t){if(process.env.HYDRA_TUI_KEY_TRACE&&oe({tag:"key",name:e,isChar:!!t.isCharacter}),t.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=pl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(t),a=pT(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(l===null&&c==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let u=this.nearestKeyAboveRow(o.y),f=this.nearestKeyBelowRow(o.y);u!==null&&f!==null&&this.hoveredRunKeys.has(u)&&this.hoveredRunKeys.has(f)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback()));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=dl&&Math.abs(o.y-d.y)<=dl&&Date.now()-d.t<=ip||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,fT(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let u=this.btwHeaderSidRegion();if(u!==null&&this.onHydraLinkClick&&o.y===u.row&&o.x>=u.colStart&&o.x<=u.colEnd)this.onHydraLinkClick(u.sessionId);else if(this.onBlockClick){let f=this.keyAtRow(o.y);if(f!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===f;)p-=1;this.schedulePendingBlockClick(f,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=ip&&Math.abs(e.x-i.x)<=dl&&Math.abs(e.y-i.y)<=dl&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let u=e.y;for(;u>1&&this.keyAtRow(u-1)===l;)u-=1;let f=e.y-u;if(this.onBlockDoubleClick(l,f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&_b.test(l)){let f=l.match(_b)?.[1]??null;if(f&&this.onHydraLinkClick(f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let s=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),c=Math.max(0,t-a.length),d=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=d<c;if(d===0&&l||f){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(d>=t-1&&u){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=this.term.width,i=Math.max(1,Math.min(r,e));for(let o=1;o<s;o++){let a=t-o;if(a>=1){let d=this.resolveCellToSource(i,a);if(d!==null){let l=this.lineById(d.sourceLineId);return l?{sourceLineId:d.sourceLineId,offset:(l.body??"").length}:d}}let c=t+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=pp(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),!cl.test(r[a])&&!ap.test(r[a]))return null;let c=a;for(;c>0&&ap.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&ap.test(r[d]);)d++;for(;d>c+1&&nT.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!cl.test(r[a]))return null;let u=a;for(;u>0&&cl.test(r[u-1]);)u--;let f=a+1;for(;f<r.length&&cl.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,u,f)}projectCleanRangeToRaw(e,t,s,r){let i=t,o=t;for(let a=0;a<e.length;a++)if(e[a]===s&&i===t&&(i=a),e[a]===r&&o===t){o=a;break}return{start:i,end:o}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=pp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(t.links){for(let p of t.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,b=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return b&&(m=b[1],y=Number.parseInt(b[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!op.test(r[a]))return null;let c=a;for(;c>0&&op.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&op.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi||!t.links)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=pp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of t.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Pb():`${Pb()}/${t.slice(2)}`);let s=Mb(t)||e.startsWith("~"),r=Mb(t)?t:eT(this.sessionbar.cwd,t);if(s)return r;try{if(Eb(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.raw;if(!sT.test(s))return!1;let r=s.startsWith(Ut)?[s]:[Ut+s,s],i=null;for(let o of r)try{if(Eb(L.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(t=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(t);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=Z0(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.message}`)}return!0}schedulePendingBlockClick(e,t){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,t)},ip);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:t}}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 t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let s=this.lines[t];if(s&&this.lineIds.get(s)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Ib(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,s=Number(t.x),r=Number(t.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"?Aw:Kc))}keyAtRow(e){let t=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(t,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;return u<0||u>=d.length?null:d[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let s=this.keyAtRow(t);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(e){let t=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(t,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=hr(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let v=za(p.bodyStyle)||p.ansi===!0?Rb(mp(p.body),y):Cb(p.body,y);return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+v}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),s=Math.min(t,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 t=e.toLowerCase(),s=[];if(t.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(t,c);if(d===-1)break;a.push(d),c=d+t.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=t.length>0?t: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 t=this.lines[e.lineIdx];if(!t)return null;let s=this.lineIds.get(t);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==t.lineId)return null;let r=t.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let t=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,t).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Je-nt-tt-rT-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-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,t,s){this.started&&this.painter.paintRow(e,t,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),Oe(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-tt-nt-Je;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Je),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),t=this.term.height,s=this.sessionbar.title?.trim(),r=ky(this.sessionbar.agent,this.sessionbar.model),i=at(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Ye(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=Ye(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=At(i,f),m=s?At(s,p):"",y=Ye(h)+(s?u+Ye(m):0),b=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(b)),this.term.noFormat(r)})}drawSeparator(e){let t=this.term.width,s=ll(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?is(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=Db(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Ye(o)+Ye(u)+f.length+Ye(s);for(let T of c)y+=Ye(" \xB7 ")+Ye(T.text);y+=Ye(p);let b=Ye(h)+Ye(d)+Ye(m),v=Math.max(0,t-y-b),S="\u2500".repeat(v),x=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,x,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let t=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=Ye(i)+Ye(a)+Ye(o),d=Math.max(0,t-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${t}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.terminalFocused?this.hoveredBannerHit:null;for(let b=0;b<m.length;b++){b>0&&this.term.dim(" \xB7 ");let v=m[b];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Ye(i)+1,y=r.split(" \xB7 ");for(let b of y){let v=Ye(b),S=[m,m+v-1];b.includes("mode")&&h.mode===null?h.mode=S:b.includes("pick")&&h.pick===null?h.pick=S:b.includes("guide")&&h.guide===null?h.guide=S:b.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+Ye(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?ll(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=Db(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Ye(t)+i.length+Ye(r)+o.length+Ye(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:t,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-tt-nt-Je,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=ll(this.btwOverlaySessionId),u=1+c.length+Ye(a)+" \xB7 ".length,f=u+Ye(d)-1;return{row:o,colStart:u,colEnd:f,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.term.width,t=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let h=Math.max(0,r.length-s);this.scrollOffset>h&&(this.scrollOffset=h)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let f=-1,p=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let h=0;h<c.length;h++){let m=c[h]?.blockKey;m===void 0||!(m===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m))||(f===-1&&(f=h),p=h)}for(let h=0;h<s;h++){let m=t+h,y=h-d,b=y>=0?c[y]:void 0,v=this.activeMatchCol(b,l),S=b?this.selectionRangeForChunk(b):null,x=b!==void 0&&b.blockKey!==void 0&&(b.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(b.blockKey)),T=b!==void 0&&b.blockKey===void 0&&f!==-1&&y>=f&&y<=p,E=x||T,$=this.terminalFocused&&E&&(this.hoveredSubKey===null||(b.hoverSubKey??null)===this.hoveredSubKey),N=$b("sb",e,b,this.scrollbackHighlight,v,S)+($?"|H":"");this.paintRow(m,N,()=>{b&&this.writeFormattedLine(b,e,v,u,S,$)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(cp,this.queuedTexts.length)}chipRows(){return Math.min(up,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,s)=>t===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(lp,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Je-nt-tt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>lp,h=this.completions.length-lp+1,m=f?p?`comp|${t}|overflow|${h}`:`comp|${t}|${d}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=t-y.length-4,S=v>0?At(b,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Je-nt-tt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>up,u=this.attachments.length-up,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${kn(f.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${u}`:f?`chip|${t}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${t}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,t){process.stdout.write(vT(e,t,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Je-nt-tt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>cp,p=this.queuedTexts.length-cp,h=u===void 0?"":f?`+ ${p+1} more queued`:At(AT(u),t-4),m=!f&&d===c,y=u===void 0?`queued|${t}|empty`:`queued|${t}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${h}`,v=b+" ".repeat(Math.max(0,t-1-b.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ds(s.buffer,t),i=_s(r,s,dp),o=this.term.height-i.rendered-tt-nt-Je+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,s=this.term.height-fp-tt-nt-Je+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${At(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${At(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,s=this.compactionRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${At(e.message,t-2)}`)}),o(`cpct|q|${t}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,u=` ${d?"\u276F":" "} ${a+1}. ${At(c.label,t-8)}`;o(`cpct|o|${t}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${t}`,()=>{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 t=this.term.width,s=this.helpRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${At(e.title,t-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|${t}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${t}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${At(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${At(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(aT,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,s=this.permissionRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${At(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${t}|${a}`,()=>{this.term.dim(` ${At(a,t-2)}`)}),o(`perm|q|${t}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,f=` ${l?"\u276F":" "} ${c+1}. ${At(d.label,t-8)}`;o(`perm|o|${t}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${t}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}bannerHitAt(e,t){let s=this.bannerHits;if(!s||t!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,t=this.promptRows(),s=e-t-tt-nt-Je;this.drawSeparator(s),this.drawBottomSeparator(e-Je)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-tt-nt-Je+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-tt-nt-Je+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-fp-tt-nt-Je+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-tt-nt-Je+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-tt-nt-Je+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ds(s.buffer,t),i=_s(r,s,dp),a=this.term.height-i.rendered-tt-nt-Je+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-tt-nt-Je;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 fp;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ds(s.buffer,t);return Math.min(dp,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(iT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(oT,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let t=this.term.width,s=this.optionsRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${At(e.title,t-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let l=e.options[d];if(!l)continue;let u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=t-p.length-3,y=`${p}${At(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${t}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,s=this.wrapBtwTail(t,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,t){if(e<=4){let o=Math.min(t,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(t<=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>=t)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>t?i.slice(i.length-t):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let t=this.term.width,r=this.term.height-this.promptRows()-tt-nt-Je,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(t,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=$b(`btw|c${f}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let u of this.lines)s(u)||d.push(u);let l=Math.min(t,d.length);return{rows:d.slice(d.length-l),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=d,i>=t)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,t){let s=this.lineIds.get(e);if(s!==void 0){let u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=hr(r),o=Math.max(1,t-i-1),a=za(e.bodyStyle),c=e.ansi?mT(e.body,o):ST(e.body,o,{stripMarkup:a}),d=[],l=0;for(let u=0;u<c.length;u++){let f=c[u]??"",p={prefix:u===0?e.prefix:" ".repeat(i),body:f};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(p.hoverSubKey=e.hoverSubKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let h=e.body.indexOf(f,l),m=h===-1?l:h;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:m}),l=m+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1){e.prefix&&Ms(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,t-hr(e.prefix??"")),c=za(e.bodyStyle),d=e.ansi?e.body:At(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;Fb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else Ms(this.term,u,e.bodyStyle,o)};if(i!==null){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=za(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Ob(m)),Ms(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=bT(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Fb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):Ms(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?Ye(d):hr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Ms(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Ub=/[^\x20-\x7e]/,hp=new Intl.Segmenter(void 0,{granularity:"grapheme"}),jb=!1;gT=/[a-zA-Z+\-:_!#/]/;ll=ft});function CT(n,e,t=hl){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=t[n];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,n-1)};let r=t.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=t[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:n}}async function Jb(n,e){Ln();let t=ft(e.sessionId),s=e.importedFromMachine??"another machine",r=at(e.cwd),i=hl.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+hl.length*2+2,d=Bn(n,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)n.moveTo(d.contentX,d.contentY+f),n.dim.noFormat(` ${p.label}`),n.noFormat(Ge(p.value,l-p.label.length-2)),f++;return f++,Yb(n,d,f,{intro:"What do you want to do?",choices:hl,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return os({term:n,render:o,onKey:(a,c,d,l)=>{let u=RT(a,d);if(!u)return;let f=CT(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function Yb(n,e,t,s){let r=e.contentW,i=t;n.moveTo(e.contentX,e.contentY+i),n.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}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Fa(d,r)):n.noFormat(d),i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${a.description}`),i++}i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${s.footer}`)}function RT(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function Vb(n,e,t){let s=ft(e.sessionId),r=e.title??at(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=Bn(n,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;n.moveTo(c.contentX,c.contentY+l),n.dim.noFormat(" session: "),n.noFormat(Ge(s,d-10)),l++,n.moveTo(c.contentX,c.contentY+l),n.noFormat(" "+Ge(r,d-2)),l++,l++,Yb(n,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(),n.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),t.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};t.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var hl,yp=V(()=>{"use strict";ve();Xn();Xr();hl=[{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 Ja(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let s=n[t]??"",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 Qb(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let s=t.indexOf(" "),r=s===-1?t:t.slice(0,s),i=s===-1?"":t.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Ja(e);return o.length<=r.length?null:o+i}var ml=V(()=>{"use strict"});var Fo,wp=V(()=>{"use strict";Fo=class{buffer;cur;killBuf="";undoStack=[];redoStack=[];constructor(e=""){this.buffer=e,this.cur=e.length}get text(){return this.buffer}get cursor(){return this.cur}setText(e,t={}){t.recordUndo&&this.recordEdit(),this.buffer=e,this.cur=e.length}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}snap(){return{text:this.buffer,cursor:this.cur}}restore(e){this.buffer=e.text,this.cur=e.cursor}recordEdit(){this.undoStack.push(this.snap()),this.undoStack.length>500&&this.undoStack.shift(),this.redoStack=[]}undo(){let e=this.undoStack.pop();return e===void 0?!1:(this.redoStack.push(this.snap()),this.restore(e),!0)}redo(){let e=this.redoStack.pop();return e===void 0?!1:(this.undoStack.push(this.snap()),this.restore(e),!0)}moveLeft(){this.cur>0&&(this.cur-=1)}moveRight(){this.cur<this.buffer.length&&(this.cur+=1)}moveHome(){this.cur=0}moveEnd(){this.cur=this.buffer.length}moveWordBackward(){let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;this.cur=e}moveWordForward(){let e=this.buffer.length,t=this.cur;for(;t<e&&/\s/.test(this.buffer[t]??"");)t+=1;for(;t<e&&!/\s/.test(this.buffer[t]??"");)t+=1;this.cur=t}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,t){if(t)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as Gb from"os";async function si(n,e,t={}){let s=t.defaultCwd??(e?await cb(e.cwd):void 0)??Gb.homedir();Ln();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:ft(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:at(e.cwd)}]:[],a=new Fo(s),c=null,d=!1,l=null,u=null,f=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",b=h.indexOf(m),v=h.indexOf(y),S=()=>{let M=o.length+6;l=Bn(n,{contentHeight:M,title:r,overlay:t.overlay===!0});let D=l.contentW,B=0;for(let K of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${K.label}`),n.noFormat(Ge(K.value,D-K.label.length-2)),B++;B++,n.moveTo(l.contentX,l.contentY+B),n.noFormat(` ${i}`),B+=2,E(B),B+=2;let O=l.contentY+B;c!==null?(n.moveTo(l.contentX,O),n.red.noFormat(` ${Ge(c,D-2)}`),u=null,f=null,p=null):(n.moveTo(l.contentX,O),n.dim.noFormat(h),u=O,f={start:l.contentX+b,end:l.contentX+b+m.length-1},p={start:l.contentX+v,end:l.contentX+v+y.length-1})},x=()=>o.length+3,T=0,E=M=>{if(!l)return;let D=M??x();n.moveTo(l.contentX,l.contentY+D).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+D),n.dim.noFormat("\u2502"),n.moveTo(l.contentX,l.contentY+D),n.noFormat(" ");let O=Math.max(1,l.contentW-1-2),K=a.text,X=a.cursor;X<T&&(T=X),X-T>=O&&(T=X-O+1),T<0&&(T=0);let Z=K.slice(T,T+O);T>0&&Z.length>0&&(Z="\u2026"+Z.slice(1));let Q=X-T;if(d){n.noFormat(Z);return}Q>=Z.length?(n.noFormat(Z),n.bgWhite(" ")):(n.noFormat(Z.slice(0,Q)),n.bgWhite.noFormat(Z[Q]??" "),n.noFormat(Z.slice(Q+1)))},$=()=>{if(E(),!l)return;let M=x()+2;n.moveTo(l.contentX,l.contentY+M).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+M),n.dim.noFormat("\u2502");let D=l.contentY+M;n.moveTo(l.contentX,D),c!==null?(n.red.noFormat(` ${Ge(c,l.contentW-2)}`),u=null,f=null,p=null):(n.dim.noFormat(h),u=D,f={start:l.contentX+b,end:l.contentX+b+m.length-1},p={start:l.contentX+v,end:l.contentX+v+y.length-1})},N=M=>{if(d)return;let D=a.text;d=!0,c=null,$(),Da(D).then(B=>{if(d=!1,B.ok){M({kind:"ok",path:B.path});return}c=B.reason,$()})};return os({term:n,render:S,overlay:t.overlay===!0,onKey:(M,D,B,O)=>{if(!d){if(M==="ENTER"||M==="KP_ENTER"){N(O);return}if(M==="ESCAPE"){O({kind:"back"});return}if(M==="CTRL_C"||M==="CTRL_D"){O({kind:"cancel"});return}if(M==="TAB"){d=!0,lb(a.text).then(K=>{if(d=!1,K.matches.length===0)return;let X;if(K.matches.length===1)X=K.prefix+K.matches[0];else{let Z=Ja(K.matches);if(Z.length<=K.basePrefix.length)return;X=K.prefix+Z}X!==a.text&&(a.setText(X,{recordUndo:!0}),c=null,$())});return}if(a.handleKey(M,B?.isCharacter===!0)){c=null,$();return}}},onMouse:(M,D,B)=>{if(d||M!=="MOUSE_LEFT_BUTTON_PRESSED")return;let O=D?.x,K=D?.y;if(!(typeof O!="number"||typeof K!="number")){if(l!==null&&(O<l.x||O>=l.x+l.w||K<l.y||K>=l.y+l.h)){B({kind:"back"});return}if(u!==null&&K===u){if(f!==null&&O>=f.start&&O<=f.end){N(B);return}if(p!==null&&O>=p.start&&O<=p.end){B({kind:"back"});return}}}}})}var bp=V(()=>{"use strict";ve();Xn();Jf();ml();Xr();wp()});import*as Zb from"fs";import*as ev from"os";import*as gl from"path";function yl(n,e){let t=e;for(;t>0;){let s=n[t-1]??"";if(/\s/.test(s)){if(s===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function TT(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function ET(n){return n.replace(/\\ /g," ")}function Xb(n){return n.replace(/ /g,"\\ ")}function PT(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function MT(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=ev.homedir()+t.slice(1)),gl.isAbsolute(t)?t:gl.resolve(e,t)}function _T(n){let e;try{e=Zb.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function wl(n,e,t=_T){let s=ET(n),{dirPrefix:r,base:i}=PT(s);if(r.length===0&&!TT(n)&&i.length===0)return null;let o=MT(r,e),a=t(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:Xb(r+p),candidates:l}}let u=Ja(d.map(f=>f.name));return{replacement:Xb(r+u),candidates:l}}var vp=V(()=>{"use strict";ml()});function $T(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function FT(n,e,t){let s=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${s} via npm\u2026`:t.phase==="installed"?`${n} ${s} installed`:`${n} installing ${s} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let r=t.receivedBytes??0,i=t.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${c}%)`}return`${n} downloading ${s} ${o} MB`}return t.phase==="download_done"?`${n} downloaded ${s}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${s}\u2026`:t.phase==="installed"?`${n} ${s} installed`:e||n}function bl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,$T(a))};return{write(a){t||(i=a,s=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=FT(i,s,a);s=d,e.write(d)},finalize(){t||(t=!0,o(0),e.finalize())}}}function tv(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),n.brightYellow(t))},finalize(){e||(e=!0,process.stdout.write(`
217
- `))}}}var Sp=V(()=>{"use strict"});function Ip(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function xp(n,e){let t=()=>{process.stdout.write(Vr),process.stdout.write(Ts),process.stdout.write(Qr),process.stdout.write(Gr),process.stdout.write(xo),process.stdout.write(Ao),process.stdout.write(Co),process.stdout.write(Yr),process.stdout.write("\x1B>")};t();let s=e.prefs??Ip();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=vl(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(U=>U.interactive===!0)),P=DT(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??mo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>yo(R,Date.now())),l=wo(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,b=!1,v=0,S="normal",x=null,T=!1,E="input",$=new Ps({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,O=null,K=!1,X=null,Z=null,Q=null,fe=null,Me=()=>{if(fe!==null){let R=fe;return{plain:R,render:()=>{n.brightYellow.noFormat(` ${R}`)}}}if(h){let R=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${R} \xB7 ^c clears`,render:()=>{n.brightYellow.noFormat(` /${m}`),n.bgBrightYellow(" "),n.dim.noFormat(` ${R} \xB7 ^c clears`)}}}return Q!==null?{plain:Q,render:()=>{n.dim.noFormat(` ${Q}`)}}:null},In=!1,De=new Ps({history:[]});if(e.initialPrompt&&De.setBuffer(e.initialPrompt),e.initialAttachments)for(let R of e.initialAttachments)De.addAttachment(R);let cs=e.config.tui.promptHistoryMaxEntries;da(L.globalTuiHistoryFile()).then(R=>{let P=R.length>cs?R.slice(R.length-cs):R;De.setHistory(P)}).catch(()=>{});let Se=new _o(n),G=Es(n),Ie=Jt(n),je=0,Yt="",$s=0,un=[],wt=1,Fs=0,Os=0,ls=0,ii="",Oo=[],xn=1,Xa=0,Lo=[],me=1,Ls=0,Za=0,oi=0,ai=()=>{G=Es(n),Ie=Jt(n);let R=Math.max(10,Ie-kp-1);$s=Math.max(10,Ie-nv);let P=Math.max(10,Ie-8),U=De.state().attachments.length,Y=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",re=Math.max(10,P-Y.length);Yt=NT(r,re)+Y;let ie=De.state();un=ds(ie.buffer,$s);let we=_s(un,ie,Ya);wt=we.rendered,Fs=we.windowStart,Os=we.cursorVisualRow,ls=we.cursorVisualCol;let Ce=6+wt,Ze=Math.max(3,G-Ce);je=Math.min(a.length,Ze),ii=cr(go,l,R,c).padEnd(R),Oo=d.map(ht=>cr(ht,l,R,c).padEnd(R))},di=()=>{d=a.map(R=>yo(R,Date.now())),l=wo(d,c),u=1+a.length,ai()},Ct=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>HT(P,m)):a=R,di(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An()},us=R=>{if(R!==void 0){let P=a.findIndex(U=>U.sessionId===R);if(P>=0){f=P+1,An();return}}f=a.length>0?1:0,p=0,An()},An=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+je?p=R-je+1:p+je>a.length&&(p=Math.max(0,a.length-je))},he=()=>Math.max(2,Ie-3),Ke=!1,qe=!0,gt=!1,Bs=[],fs=e.composerAgentId,ps=e.composerModel,ci=()=>{let R=fs;if(!R)return"";let P=ps;return P?`${R}\u2022${P}`:R},Ns=null,hs=null,Lt=null,li=()=>{let R=he(),P=`\u2500 ${Yt} `,U=ci(),Y="";if(U.length>0){let Ve=`\u2500 ${U} `;Ve.length+P.length+1<=R&&(Y=Ve)}let re=Math.max(1,R-P.length-Y.length),ie="\u2500".repeat(re),we=(f===0||Ke)&&qe;if(Ns=P.length>0?{start:2,end:1+P.length}:null,Y.length>0){let Ve=1+P.length+re+1;hs={start:Ve,end:Ve+Y.length-1}}else hs=null;let Ce=we?n.brightBlue:n.dim,Ze=we?n.brightBlue.bold:n.dim.bold,ht=(Ve,Ws)=>{(Ws?Ze:Ce).noFormat(Ve)};Ce.noFormat("\u256D"),ht(P,Lt==="cwd"),Ce.noFormat(ie),Y&&ht(Y,Lt==="agent"),Ce.noFormat("\u256E")},Dn=()=>{let R=he(),P="\u2500".repeat(R);(f===0||Ke)&&qe?n.brightBlue.noFormat(`\u2570${P}\u256F`):n.dim.noFormat(`\u2570${P}\u256F`)},Bo=()=>{let R=Me();if(R===null)return;let P=Math.max(0,Jt(n)-2);if(R.plain.length>P){let U=R.plain.slice(0,Math.max(0,P-1))+"\u2026";n.dim.noFormat(` ${U}`);return}R.render()},Ds=R=>{let P=un[R];return P?(De.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},ui=R=>{let P=he(),U=Ds(R),Y=Math.max(0,P-1-U.length),re=" ".repeat(Y);(f===0||Ke)&&qe?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${U}${re}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${U}${re}`),n.dim.noFormat("\u2502"))},Rt=R=>{let P=Oo[R]??"",U=a[R],Y=U&&U.priority&&U.priority>0?"* ":" ";f===R+1&&!Ke&&qe?n.brightWhite.bgBlue.noFormat(`${Y}${P}`):n.noFormat(`${Y}${P}`)},Vt=()=>{let R=p,P=Math.max(0,a.length-p-je),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Y=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Y})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),R>0&&U.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&U.push({kind:"plain",text:`\u2193 ${P} below`}),U},Hn=()=>{let R=Vt();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},Re=R=>ft(R),ed=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,X?`${X.text}${X.cursor}`:"",Z??"",h?`1|${m}|${a.length}`:"0",Hn(),vi?"h1":"h0",qs?"ho1":"ho0"].join("")},$e=()=>{Oe(()=>{Se.paintRow(jn(),ed(),()=>{let R=()=>{zn=null,Zt=null};if(S==="confirm-kill"&&x)R(),n.brightYellow.noFormat(` kill ${Re(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="warm"?n.brightRed.noFormat(` kill + delete ${Re(x.sessionId)}? [y/N]`):n.brightRed.noFormat(` delete ${Re(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),n.dim.noFormat(` working on ${Re(x.sessionId)}\u2026`);else if(S==="rename"&&x&&X){R();let P=X.text,U=X.cursor;n.brightYellow.noFormat(" title: "),n.brightYellow.noFormat(P.slice(0,U)),U<P.length?(n.bgBrightYellow.noFormat(P[U]??" "),n.brightYellow.noFormat(P.slice(U+1))):n.bgBrightYellow(" "),n.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(Z!==null)R(),n.dim.noFormat(` ${Z}`);else{let P=Vt(),U=Hn(),Y="Esc \xB7 Go Back",re=Y.length,ie=5,we=U.length,Ce=Math.max(1,Ie-we-re-ie);if(Zt=null,P.length>0){n.dim.noFormat(" ");let Ze=3;for(let ht=0;ht<P.length;ht++){let Ve=P[ht];ht>0&&(n.dim.noFormat(" \xB7 "),Ze+=3),Ve.kind==="host"?(Zt={start:Ze,end:Ze+Ve.text.length-1},qs?n.noFormat(Ve.text):n.dim.noFormat(Ve.text)):n.dim.noFormat(Ve.text),Ze+=Ve.text.length}}n.dim(" ".repeat(Ce)),vi?n.noFormat(Y):n.dim.noFormat(Y),zn={start:Ie-ie-re+1,end:Ie-ie}}})})},Tt=R=>xn+1+R,Un=()=>xn+wt+1,Qt=()=>xn+wt+3,I=R=>Qt()+1+(R-p),jn=()=>Qt()+1+je,fn=()=>{let R=Os-Fs;if(R<0||R>=wt)return;let P=3+ls;n.moveTo(P,Tt(R))},Hs=()=>qe?f===0?"f":Ke?"h":"u":"x",fi=()=>`ct|${Hs()}|${he()}|${Yt}|${ci()}|${Lt??""}`,No=()=>`cb|${Hs()}|${he()}`,gr=()=>fe!==null?`cs|i|${fe}`:h?`cs|s|${m}|${a.length}`:Q!==null?`cs|h|${Q}`:"blank",qn=R=>`cbb|${Hs()}|${he()}|${Ds(R)}`,Do=()=>`h|${ii}`,pi=R=>{let P=a[R],U=P&&P.priority&&P.priority>0?"* ":" ",Y=Oo[R]??"";return`sr|${f===R+1&&!Ke&&qe?"1":"0"}|${U}${Y}`},Xe=()=>{Oe(()=>{n.hideCursor(),ai(),An(),xn=1,Se.ensureSize(Ie,G),Se.paintRow(xn,fi(),()=>{li()});for(let R=0;R<wt;R++){let P=Fs+R;Se.paintRow(Tt(R),qn(P),()=>{ui(P)})}Se.paintRow(Un(),No(),()=>{Dn()}),Se.paintRow(Un()+1,gr(),()=>Bo()),Se.paintRow(Qt(),Do(),()=>{n.dim.noFormat(` ${ii}`)});for(let R=0;R<je;R++){let P=p+R,U=Qt()+1+R;P<a.length?Se.paintRow(U,pi(P),()=>{Rt(P)}):Se.paintRow(U,"blank",()=>{})}$e();for(let R=jn()+1;R<=G;R++)Se.paintRow(R,"blank",()=>{});f===0&&(fn(),n.hideCursor(!1))})},Ho=()=>{Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Xe()},ms=()=>{Oe(()=>{n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(" Picker hotkeys")(`
213
+ `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:t.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(t.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(t)){this.handleCsiUStdin(t);return}this.handleRawStdinSegment(t)}}handleCsi27Stdin(e){let t=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=t.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=Wb(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 t=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=t.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=Wb(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 t=Ao,s=Ma;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,`
214
+ `);this.pasteBuffer="";let a=Ib(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(t);if(r===-1){let i=gT(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+t.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 t=this.term.width;return this.wrapCacheWidth!==t&&(this.wrapCache.clear(),this.wrapCacheWidth=t),this.wrapOne(e,t).length}wrappedRowsOfMany(e){let t=0;for(let s of e)t+=this.wrappedRowsOf(s);return t}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let t of e)this.trackLine(t)}forgetLine(e){let t=this.lineIds.get(e);t!==void 0&&this.wrapCache.delete(t)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let t=this.lines.splice(0,e);for(let s of t)this.forgetLine(s);this.invalidateSelectionIfTouches(t);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,t){this.upsertLines(e,[t])}upsertLines(e,t){if(t.length===0)return;for(let o of t)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=t.length-s.count,d=this.lines.slice(s.start,o),l=new Array(t.length),u=[];for(let f=0;f<t.length;f++){let p=d[f],h=t[f];p!==void 0&&bT(p,h)?l[f]=p:(p!==void 0&&u.push(p),l[f]=h)}for(let f=t.length;f<d.length;f++)u.push(d[f]);this.lines.splice(s.start,s.count,...l);for(let f of u)this.forgetLine(f);for(let f of l)this.lineIds.has(f)||this.trackLine(f);if(this.invalidateSelectionIfTouches(u),s.count=t.length,c!==0)for(let[f,p]of this.keyedBlocks)f!==e&&p.start>s.start&&(p.start+=c);i=this.wrappedRowsOfMany(t)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:t.length}),this.lines.push(...t),this.trackLines(t),i=this.wrappedRowsOfMany(t);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,t,s,r){if(e.length===0)return;let i=e.split(`
215
+ `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),c+=this.wrappedRowsOf(p)}}let l={prefix:t,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(t.length);for(let l of a){let u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),t=ul(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:t,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Oe(()=>{this.term.hideCursor(),e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,t=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},t),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setSynthesisIndicator(e){this.synthesisIndicator!==e&&(this.synthesisIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),oe({src:"grab",site:"setMouseEnabled",on:!0,mouse:e}),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,t){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.sourceLineId),i=s<r||s===r&&e.offset<=t.offset,o=i?e:t,a=i?t:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}farEndpointFrom(e){if(this.selection===null)return null;let t=this.selection,s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(t.startLineId),i=this.lineIndexById(t.endLineId);if(s<0||r<0||i<0)return null;let o=(u,f,p,h)=>u!==p?u-p:f-h,a=o(s,e.offset,r,t.startOffset),c=o(s,e.offset,i,t.endOffset);if(a<=0)return{sourceLineId:t.endLineId,offset:t.endOffset};if(c>=0)return{sourceLineId:t.startLineId,offset:t.startOffset};let d=Math.abs(s-r)*1e6+Math.abs(e.offset-t.startOffset);return Math.abs(s-i)*1e6+Math.abs(e.offset-t.endOffset)>=d?{sourceLineId:t.endLineId,offset:t.endOffset}:{sourceLineId:t.startLineId,offset:t.startOffset}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let t=[];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 c=(r.body??"").slice(o.start,o.end);(Ka(r.bodyStyle)||r.ansi)&&(c=Db(c)),t.push(c)}return t.join(`
216
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let t=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(t===-1||s===-1)return null;let r=t,i=s,o=e.startOffset,a=e.endOffset;t>s&&(r=s,i=t,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,h=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{start:p,end:h,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null)return null;let t=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(t===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=t.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=s.sourceColEnd??i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);if(c<=a)return null;let d,l;if(s.sourceColEnd!==void 0){let u=this.sourceBodyForId(s.sourceLineId);if(u===null)return null;let f=mp(u,i,a),p=mp(u,a,c);d=gp(e.body,0,f),l=gp(e.body,d,p)}else d=a-i,l=c-i;return{start:d,end:l,toEndOfLine:r.toEnd||r.end>o}}sourceBodyForId(e){let t=this.lineIndexById(e);return t===-1?null:this.lines[t]?.body??null}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,t=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${t}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.synthesisIndicator!==null?{text:this.synthesisIndicator,kind:"synthesis"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let t of e){let s=this.lineIds.get(t);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 t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(t.start,s)),o=this.lines.splice(t.start,t.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>t.start&&(c.start-=t.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 t=e.start+e.count;if(t>=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>=t&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let t=this.keyedBlocks.get(e);if(!t)return;let s=t.start+t.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(t.start,t.start+t.count)),i=this.lines.splice(t.start,t.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>t.start&&(o.start-=t.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,t){if(!this.keyedBlocks.has(e))return[];let s=[...t].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,u]of this.keyedBlocks)if(!t.has(l)&&u.start>=c&&u.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,t,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=t)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(Df),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(t=>({...t}))}: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 t=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=t,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let t=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,t=!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},t=!0)}t&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let t=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){t=!1;break}if(t)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let t=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;t&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.focusedPane="main",this.scheduleRepaint())}reopenBtwOverlay(){return this.btwOverlayOpen?!0:this.btwOverlayLines.length===0?!1:(this.btwOverlayOpen=!0,this.focusedPane="btw",this.scheduleRepaint(),!0)}hasBtwOverlayHistory(){return this.btwOverlayLines.length>0}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let t=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=t!==void 0&&t.start+t.count===this.lines.length,r=s?t.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(t.start,0,o),t.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,t){if(process.env.HYDRA_TUI_KEY_TRACE&&oe({tag:"key",name:e,isChar:!!t.isCharacter}),t.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=hl(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,t){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let r=this.terminalFocused&&Date.now()-this.lastFocusInAt<200;if((this.terminalFocused===!1||r)&&(e.endsWith("_PRESSED")||e.endsWith("_RELEASED")||e==="MOUSE_MOTION"||e==="MOUSE_DRAG"))return;let o=this.mouseCell(t),a=wT(e),c=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?c="move":e.endsWith("_PRESSED")?c="press":e.endsWith("_RELEASED")&&(c="release"),c!==null&&o!==null&&this.onMouse&&this.onMouse({kind:c,button:a,x:o.x,y:o.y,name:e}),c==="move"){let d=o!==null?this.bannerHitAt(o.x,o.y):null;d!==this.hoveredBannerHit&&(this.hoveredBannerHit=d,this.syncedPartialRepaint(()=>this.drawBanner()))}if(o!==null&&c!=="release"){let d=this.keyAndSubAtRow(o.y),l=d!==null&&d.key.startsWith("agent:")?null:d;if(l===null&&c==="move"&&this.hoveredRunKeys!==null&&this.hoveredBlockKey!==null){let u=this.nearestKeyAboveRow(o.y),f=this.nearestKeyBelowRow(o.y);u!==null&&f!==null&&this.hoveredRunKeys.has(u)&&this.hoveredRunKeys.has(f)&&(l={key:this.hoveredBlockKey,sub:null})}if(this.setPointerShape(l!==null?"pointer":"default"),c==="move"){let u=l?.key??null,f=l?.sub??null;(u!==this.hoveredBlockKey||f!==this.hoveredSubKey)&&(this.hoveredBlockKey=u,this.hoveredSubKey=f,this.hoveredRunKeys=u!==null&&this.onHoverRun?this.onHoverRun(u)??null:null,this.syncedPartialRepaint(()=>this.drawScrollback()))}}else o===null&&c==="move"&&(this.hoveredBlockKey!==null||this.hoveredSubKey!==null||this.hoveredRunKeys!==null)&&(this.hoveredBlockKey=null,this.hoveredSubKey=null,this.hoveredRunKeys=null,this.syncedPartialRepaint(()=>this.drawScrollback()));if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let d=this.lastLeftClick;d!==null&&o!==null&&Math.abs(o.x-d.x)<=cl&&Math.abs(o.y-d.y)<=cl&&Date.now()-d.t<=op||this.flushPendingBlockClick(),this.pressCell=o,this.handleSelectionPress(o,yT(t,"shift"));return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),!(e==="MOUSE_RIGHT_BUTTON_PRESSED"&&o!==null&&this.extendSelectionByClick(o))){if(e==="MOUSE_DRAG"&&o!==null){this.handleSelectionDrag(o);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_RIGHT_BUTTON_RELEASED"||e==="MOUSE_MIDDLE_BUTTON_RELEASED"||e==="MOUSE_OTHER_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let d=this.pressCell;this.pressCell=null;let l=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(d!==null&&o!==null&&o.x===d.x&&o.y===d.y&&!l){let u=this.btwHeaderSidRegion();if(u!==null&&this.onHydraLinkClick&&o.y===u.row&&o.x>=u.colStart&&o.x<=u.colEnd)this.onHydraLinkClick(u.sessionId);else if(this.onBlockClick){let f=this.keyAtRow(o.y);if(f!==null){let p=o.y;for(;p>1&&this.keyAtRow(p-1)===f;)p-=1;this.schedulePendingBlockClick(f,o.y-p)}}}this.handleSelectionRelease(o)}}}handleSelectionPress(e,t=!1){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,this.pendingClickCount=1,!this.inAppSelectionEnabled||e===null)return;let s=this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);if(s===null){this.lastLeftClick=null;return}if(t&&this.selection!==null&&this.extendSelectionByClickResolved(s)){this.lastLeftClick=null;return}this.selectionAnchor=s;let r=Date.now(),i=this.lastLeftClick,o=i!==null&&r-i.t<=op&&Math.abs(e.x-i.x)<=cl&&Math.abs(e.y-i.y)<=cl&&i.sourceLineId!==null&&i.sourceLineId===s.sourceLineId;if(o&&i.count===2&&e.x===i.x&&e.y===i.y){this.pendingClickCount=3,this.cancelPendingBlockClick(),this.selectWholeSourceLine(s.sourceLineId),this.doubleClickPending=!0;return}if(o&&i.count===1){if(this.pendingClickCount=2,this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let l=this.keyAtRow(e.y);if(l!==null){let u=e.y;for(;u>1&&this.keyAtRow(u-1)===l;)u-=1;let f=e.y-u;if(this.onBlockDoubleClick(l,f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.onHydraLinkClick&&e!==null){let l=this.findLinkUrlAt(s);if(l!==null&&Lb.test(l)){let f=l.match(Lb)?.[1]??null;if(f&&this.onHydraLinkClick(f)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}if(this.tryOpenSessionAt(s)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let d=this.wordBoundsAt(s);d!==null&&(this.setSelection({sourceLineId:s.sourceLineId,offset:d.start},{sourceLineId:s.sourceLineId,offset:d.end}),this.doubleClickPending=!0)}}selectWholeSourceLine(e){let t=this.lineById(e);if(t===null)return;let s=(t.body??"").length;this.setSelection({sourceLineId:e,offset:0},{sourceLineId:e,offset:s})}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;this.extendSelectionToCell(e);let t=this.scrollbackVisibleRows();e.y<=1&&this.scrollOffset<this.maxScrollOffset()?this.startAutoscroll(e,1):e.y>=t&&this.scrollOffset>0?this.startAutoscroll(e,-1):this.stopAutoscroll()}extendSelectionByClick(e){if(!this.inAppSelectionEnabled||this.selection===null)return!1;let s=this.resolveEdgeSource(e.y)??this.resolveCellToSource(e.x,e.y)??this.resolveNearestSource(e.x,e.y);return s===null?!1:this.extendSelectionByClickResolved(s)}resolveEdgeSource(e){let t=this.scrollbackVisibleRows();if(t<=0||this.lines.length===0)return null;let s=this.term.width,{rows:r}=this.wrapTail(s,t+this.scrollOffset),i=r.length-this.scrollOffset,o=Math.max(0,i-t),a=r.slice(o,i),c=Math.max(0,t-a.length),d=e-1,l=this.scrollOffset<this.maxScrollOffset(),u=this.scrollOffset>0,f=d<c;if(d===0&&l||f){let p=this.lines[0];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:0}}}if(d>=t-1&&u){let p=this.lines[this.lines.length-1];if(p){let h=this.lineIds.get(p);if(h!==void 0)return{sourceLineId:h,offset:(p.body??"").length}}}return null}resolveNearestSource(e,t){let s=this.scrollbackVisibleRows();if(s<=0)return null;let r=this.term.width,i=Math.max(1,Math.min(r,e));for(let o=1;o<s;o++){let a=t-o;if(a>=1){let d=this.resolveCellToSource(i,a);if(d!==null){let l=this.lineById(d.sourceLineId);return l?{sourceLineId:d.sourceLineId,offset:(l.body??"").length}:d}}let c=t+o;if(c<=s){let d=this.resolveCellToSource(i,c);if(d!==null)return{sourceLineId:d.sourceLineId,offset:0}}}return null}extendSelectionByClickResolved(e){let t=this.farEndpointFrom(e);return t===null?!1:(this.selectionAnchor=t,this.selectionDragStarted=!0,this.setSelection(t,e),!0)}extendSelectionToCell(e){if(this.selectionAnchor===null)return;let t=this.resolveCellToSource(e.x,e.y);t!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,t))}static AUTOSCROLL_TICK_MS=60;startAutoscroll(e,t){if(this.autoscrollTimer!==null&&this.autoscrollDir===t){this.autoscrollCell={x:e.x,y:e.y};return}this.stopAutoscroll(),this.autoscrollCell={x:e.x,y:e.y},this.autoscrollDir=t,this.autoscrollTimer=setInterval(()=>{if(this.selectionAnchor===null||this.autoscrollCell===null){this.stopAutoscroll();return}let s=this.scrollOffset;if(this.scrollBy(this.autoscrollDir),this.scrollOffset===s){this.stopAutoscroll();return}this.extendSelectionToCell(this.autoscrollCell)},n.AUTOSCROLL_TICK_MS)}stopAutoscroll(){this.autoscrollTimer!==null&&(clearInterval(this.autoscrollTimer),this.autoscrollTimer=null),this.autoscrollCell=null}handleSelectionRelease(e){this.stopAutoscroll();let t=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null){let r=this.resolveCellToSource(e.x,e.y);this.lastLeftClick={x:e.x,y:e.y,t:Date.now(),count:this.pendingClickCount,sourceLineId:r?.sourceLineId??null}}if(this.pendingClickCount=1,!!this.inAppSelectionEnabled){if(t||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let t=this.lineById(e.sourceLineId);if(t===null)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=hp(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),!ll.test(r[a])&&!dp.test(r[a]))return null;let c=a;for(;c>0&&dp.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&dp.test(r[d]);)d++;for(;d>c+1&&aT.test(r[d-1]);)d--;if(r.slice(c,d).includes("://")){let p=c,h=d;return this.projectCleanRangeToRaw(i,s.length,p,h)}if(!ll.test(r[a]))return null;let u=a;for(;u>0&&ll.test(r[u-1]);)u--;let f=a+1;for(;f<r.length&&ll.test(r[f]);)f++;return this.projectCleanRangeToRaw(i,s.length,u,f)}projectCleanRangeToRaw(e,t,s,r){let i=t,o=t;for(let a=0;a<e.length;a++)if(e[a]===s&&i===t&&(i=a),e[a]===r&&o===t){o=a;break}return{start:i,end:o}}pathTokenAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=hp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(t.links){for(let p of t.links)if(o>=p.start&&o<p.end){let h=p.url,m=h.startsWith("file://")?h.slice(7):h,y=null,w=m.match(/^(.*?)#L(\d+)(?:-L?\d+)?$/);return w&&(m=w[1],y=Number.parseInt(w[2],10)),{raw:m,line:y}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!ap.test(r[a]))return null;let c=a;for(;c>0&&ap.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&ap.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0||l.startsWith("//"))return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}findLinkUrlAt(e){let t=this.lineById(e.sourceLineId);if(t===null||t.ansi||!t.links)return null;let s=t.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=hp(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;for(let a of t.links)if(o>=a.start&&o<a.end)return a.url;return null}resolvePathToken(e){let t=e;(t==="~"||t.startsWith("~/"))&&(t=t==="~"?Fb():`${Fb()}/${t.slice(2)}`);let s=Ob(t)||e.startsWith("~"),r=Ob(t)?t:iT(this.sessionbar.cwd,t);if(s)return r;try{if($b(r).isFile())return r}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.line===null?"":`:${t.line}`;return this.tryOpenPathString(t.raw+s)}tryOpenSessionAt(e){if(!this.onHydraLinkClick)return!1;let t=this.pathTokenAt(e);if(t===null)return!1;let s=t.raw;if(!dT.test(s))return!1;let r=s.startsWith(Ut)?[s]:[Ut+s,s],i=null;for(let o of r)try{if($b(L.sessionFile(o)).isFile()){i=o;break}}catch{}return i===null?!1:this.onHydraLinkClick(i)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let t=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(t=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(t);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=rT(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.message}`)}return!0}schedulePendingBlockClick(e,t){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,t);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,t)},op);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:t}}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 t of this.lines)if(this.lineIds.get(t)===e)return t;return null}lineIndexById(e){for(let t=0;t<this.lines.length;t++){let s=this.lines[t];if(s&&this.lineIds.get(s)===e)return t}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Rb(e,{target:this.selectionClipboard}).then(t=>{if(t.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${t.reason}`)},t=>{this.notify(`clipboard copy failed: ${t.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let t=e,s=Number(t.x),r=Number(t.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"?Ew:Jc))}keyAtRow(e){let t=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(t,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;return u<0||u>=d.length?null:d[u]?.blockKey??null}nearestKeyAboveRow(e){for(let t=e-1;t>=1;t--){let s=this.keyAtRow(t);if(s!==null)return s}return null}nearestKeyBelowRow(e){let s=this.scrollbackVisibleRows();for(let r=e+1;r<=s;r++){let i=this.keyAtRow(r);if(i!==null)return i}return null}keyAndSubAtRow(e){let t=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(t,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;if(u<0||u>=d.length)return null;let f=d[u];return f?.blockKey?{key:f.blockKey,sub:f.hoverSubKey??null}:null}resolveCellToSource(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=t-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let h=this.wrapOrigin.get(p);if(!h)return null;let m=gr(p.prefix??""),y=e-1-m;if(y<0)return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset};let v=Ka(p.bodyStyle)||p.ansi===!0?Mb(wp(p.body),y):Pb(p.body,y);if(h.sourceColEnd!==void 0){let S=this.sourceBodyForId(h.sourceLineId);if(S!==null){let x=mp(p.body,0,v),T=gp(S,h.sourceColOffset,x);return{sourceLineId:h.sourceLineId,offset:T}}}return{sourceLineId:h.sourceLineId,offset:h.sourceColOffset+v}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let t=this.maxScrollOffset(),s=Math.min(t,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 t=e.toLowerCase(),s=[];if(t.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(t,c);if(d===-1)break;a.push(d),c=d+t.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=t.length>0?t: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 t=this.lines[e.lineIdx];if(!t)return null;let s=this.lineIds.get(t);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,t){if(!e||t===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==t.lineId)return null;let r=t.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let t=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,t).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,t),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let h=p.body.length;if(e.col<u+h){o=l.length-1-f;break}u+=h}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let t=this.term.height-this.promptRows()-Je-nt-tt-cT-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,t-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,t,s){this.started&&this.painter.paintRow(e,t,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,t=this.term.height;e<20||t<8||(this.painter.ensureSize(e,t),Oe(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=t-s-tt-nt-Je;this.drawSeparator(r),this.drawPrompt(),this.drawBottomSeparator(t-Je),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=Math.max(1,this.term.width-1),t=this.term.height,s=this.sessionbar.title?.trim(),r=Cy(this.sessionbar.agent,this.sessionbar.model),i=at(this.sessionbar.cwd),o=`sbar|${e}|${r}|${i}|${s??""}`;this.paintRow(t,o,()=>{let a=Ye(r),c=1,d=Math.max(0,e-a-c),l=s?" \xB7 ":"",u=Ye(l),f,p;if(s){let v=Math.min(s.length,8);f=Math.min(i.length,Math.max(8,d-u-v)),p=Math.max(0,d-f-u)}else p=0,f=d;let h=At(i,f),m=s?At(s,p):"",y=Ye(h)+(s?u+Ye(m):0),w=Math.max(c,e-y-a);this.term.bold.noFormat(h),s&&this.term(l).bold.noFormat(m),this.term(" ".repeat(w)),this.term.noFormat(r)})}drawSeparator(e){let t=this.term.width,s=ul(this.sessionbar.sessionId),r=this.banner.status,i=r==="busy"&&this.banner.stalled===!0,o;i?o="Stalled":r==="busy"?o="Busy":o=r.charAt(0).toUpperCase()+r.slice(1);let a=r==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?as(this.banner.elapsedMs):"",c=[];if(this.banner.queued>0){let T=`${this.banner.queued} queued`;c.push({text:T,paint:()=>{this.term.brightYellow(T)}})}if(this.scrollOffset>0){let T=`\u2191 ${this.scrollOffset}`;c.push({text:T,paint:()=>{this.term.brightCyan(T)}})}let d=qb(this.sessionbar.usage)??"",l="\u2500\u2500 ",u=a?` ${a}`:"",f=s?" \xB7 ":"",p=" ",h=d?" ":"",m=d?" \u2500\u2500":"\u2500\u2500",y=l.length+Ye(o)+Ye(u)+f.length+Ye(s);for(let T of c)y+=Ye(" \xB7 ")+Ye(T.text);y+=Ye(p);let w=Ye(h)+Ye(d)+Ye(m),v=Math.max(0,t-y-w),S="\u2500".repeat(v),x=`sep|${t}|${r}|${i?1:0}|${s}|${a}|${this.banner.queued}|${this.scrollOffset}|${d}`;this.paintRow(e,x,()=>{this.term.bold(l),i||r==="disconnected"?this.term.brightRed(o):r==="busy"?this.term.brightYellow(o):r==="cold"?this.term.brightMagenta(o):this.term(o),u&&(i?this.term.brightRed.noFormat(u):r==="busy"?this.term.brightYellow.noFormat(u):this.term.dim.noFormat(u)),s&&(this.term.dim(f),this.term.dim(s));for(let T of c)this.term.dim(" \xB7 "),T.paint();this.term.dim(p),this.term.bold(S),d&&(this.term.dim(h),this.term.noFormat(d)),this.term.bold(m)})}drawBottomSeparator(e){let t=this.term.width,s=this.bannerRightContent(),r=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint,i=" ",o=" \u2500\u2500",a=s?s.text:r,c=Ye(i)+Ye(a)+Ye(o),d=Math.max(0,t-c),l="\u2500".repeat(d),u=s?`${s.kind}|${s.text}`:"",f=s||!this.terminalFocused?"":this.hoveredBannerHit??"",p=`bsep|${t}|${this.banner.currentMode??""}|${this.banner.hint}|${u}|${f}`;this.paintRow(e,p,()=>{if(this.term.bold(l),this.term.dim(i),s)s.kind==="search"?this.term.brightCyan.noFormat(s.text):this.term.brightYellow.noFormat(s.text);else{let m=r.split(" \xB7 "),y=this.terminalFocused?this.hoveredBannerHit:null;for(let w=0;w<m.length;w++){w>0&&this.term.dim(" \xB7 ");let v=m[w];if(v===void 0)continue;let S=null;v.includes("mode")?S="mode":v.includes("pick")?S="pick":v.includes("guide")?S="guide":v.includes("detach")&&(S="detach"),S!==null&&S===y?this.term.noFormat(v):this.term.dim(v)}}this.term.bold(o);let h={mode:null,pick:null,guide:null,detach:null};if(!s){let m=d+Ye(i)+1,y=r.split(" \xB7 ");for(let w of y){let v=Ye(w),S=[m,m+v-1];w.includes("mode")&&h.mode===null?h.mode=S:w.includes("pick")&&h.pick===null?h.pick=S:w.includes("guide")&&h.guide===null?h.guide=S:w.includes("detach")&&h.detach===null&&(h.detach=S),m+=v+Ye(" \xB7 ")}}this.bannerHits={row:e,...h}})}buildBtwHeaderSegments(){let e=this.term.width,t="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?ul(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=r?" ":"",a=qb(this.btwOverlayUsage),c=a?` ${a} `:"",d=a?"\u2500\u2500":"",l=s.length+Ye(t)+i.length+Ye(r)+o.length+Ye(c)+d.length,u="\u2500".repeat(Math.max(0,e-l)),f=`${e}|${r}|${this.btwOverlayStatus}|${a??""}`;return{left:s,label:t,sidSep:i,sid:r,sidTrail:o,middle:u,usage:c,right:d,signature:f}}btwHeaderSidRegion(){if(!this.btwOverlayOpen||!this.btwOverlaySessionId)return null;let e=this.btwOverlayRows();if(e===0)return null;let s=this.term.height-this.promptRows()-tt-nt-Je,r=this.chipRows()+this.queuedRows()+this.completionRows(),o=s-1-r-e+1,a="By the way",c="\u2500\u2500 ",d=ul(this.btwOverlaySessionId),u=1+c.length+Ye(a)+" \xB7 ".length,f=u+Ye(d)-1;return{row:o,colStart:u,colEnd:f,sessionId:this.btwOverlaySessionId}}paintBtwHeader(e){switch(this.term.bold(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&(this.term.dim(e.sid),this.term.dim(e.sidTrail)),this.term.bold(e.middle),e.usage&&this.term.noFormat(e.usage),this.term.bold(e.right)}drawScrollback(){let e=this.term.width,t=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let h=Math.max(0,r.length-s);this.scrollOffset>h&&(this.scrollOffset=h)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;let f=-1,p=-1;if(this.hoveredBlockKey!==null||this.hoveredRunKeys!==null)for(let h=0;h<c.length;h++){let m=c[h]?.blockKey;m===void 0||!(m===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(m))||(f===-1&&(f=h),p=h)}for(let h=0;h<s;h++){let m=t+h,y=h-d,w=y>=0?c[y]:void 0,v=this.activeMatchCol(w,l),S=w?this.selectionRangeForChunk(w):null,x=w!==void 0&&w.blockKey!==void 0&&(w.blockKey===this.hoveredBlockKey||this.hoveredRunKeys!==null&&this.hoveredRunKeys.has(w.blockKey)),T=w!==void 0&&w.blockKey===void 0&&f!==-1&&y>=f&&y<=p,E=x||T,$=this.terminalFocused&&E&&(this.hoveredSubKey===null||(w.hoverSubKey??null)===this.hoveredSubKey),N=Bb("sb",e,w,this.scrollbackHighlight,v,S)+($?"|H":"");this.paintRow(m,N,()=>{w&&this.writeFormattedLine(w,e,v,u,S,$)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let h=new Set;for(let y of c)y.blockKey!==void 0&&h.add(y.blockKey);let m=[];for(let y of this.pendingVisibleKeys)h.has(y)&&m.push(y);for(let y of m)this.pendingVisibleKeys.delete(y),this.onBlockVisible(y)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(lp,this.queuedTexts.length)}chipRows(){return Math.min(fp,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((t,s)=>t===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(up,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Je-nt-tt,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let u=c+l,f=this.completions[l],p=l===e-1&&this.completions.length>up,h=this.completions.length-up+1,m=f?p?`comp|${t}|overflow|${h}`:`comp|${t}|${d}|${f.name}|${f.description??""}`:`comp|${t}|empty`;this.paintRow(u,m,()=>{if(!f)return;if(p){this.term.dim(` + ${h} more match(es)`);return}let y=f.name.padEnd(d),w=f.description??"",v=t-y.length-4,S=v>0?At(w,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),o=this.term.height-s-Je-nt-tt-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>fp,u=this.attachments.length-fp,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${kn(f.sizeBytes)}`:"",h=l?`chip|${t}|overflow|${u}`:f?`chip|${t}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${t}|empty`;this.paintRow(d,h,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,t){process.stdout.write(AT(e,t,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let t=this.term.width,s=this.promptRows(),r=this.term.height-s-Je-nt-tt,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,u=this.queuedTexts[d],f=d===e-1&&this.queuedTexts.length>lp,p=this.queuedTexts.length-lp,h=u===void 0?"":f?`+ ${p+1} more queued`:At(PT(u),t-4),m=!f&&d===c,y=u===void 0?`queued|${t}|empty`:`queued|${t}|${m?"edit":f?"ovf":"row"}|${h}`;this.paintRow(l,y,()=>{if(u===void 0)return;let w=`\u23F3 ${h}`,v=w+" ".repeat(Math.max(0,t-1-w.length));m?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ls(s.buffer,t),i=Fs(r,s,cp),o=this.term.height-i.rendered-tt-nt-Je+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let t=this.term.width,s=this.term.height-pp-tt-nt-Je+1;this.paintRow(s,`confirm|q|${t}|${e.question}`,()=>{this.term.brightYellow(` ? ${At(e.question,t-4)}`)}),this.paintRow(s+1,`confirm|h|${t}|${e.hint}`,()=>{this.term.dim(` ${At(e.hint,t-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let t=this.term.width,s=this.compactionRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${t}|${e.message}`,()=>{this.term.brightYellow(` ${At(e.message,t-2)}`)}),o(`cpct|q|${t}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,u=` ${d?"\u276F":" "} ${a+1}. ${At(c.label,t-8)}`;o(`cpct|o|${t}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${t}`,()=>{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 t=this.term.width,s=this.helpRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${At(e.title,t-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|${t}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${t}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${At(l,t-2-a-1)}`)})}o(`help|hint|${t}|${e.hint}`,()=>{this.term.dim(` ${At(e.hint,t-2)}`)})}helpRows(){return this.helpPrompt?Math.min(fT,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let t=this.term.width,s=this.permissionRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${At(e.title,t-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${t}|${a}`,()=>{this.term.dim(` ${At(a,t-2)}`)}),o(`perm|q|${t}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,f=` ${l?"\u276F":" "} ${c+1}. ${At(d.label,t-8)}`;o(`perm|o|${t}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${t}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}computeBannerPrefixText(){let e=[];return this.banner.queued>0&&e.push(`${this.banner.queued} queued`),this.scrollOffset>0&&e.push(`\u2191 ${this.scrollOffset}`),e.length>0?e.join(" \xB7 ")+" \xB7 ":""}bannerHitAt(e,t){let s=this.bannerHits;if(!s||t!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height,t=this.promptRows(),s=e-t-tt-nt-Je;this.drawSeparator(s),this.drawBottomSeparator(e-Je)}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-tt-nt-Je+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-tt-nt-Je+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-pp-tt-nt-Je+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-tt-nt-Je+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-tt-nt-Je;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-tt-nt-Je+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ls(s.buffer,t),i=Fs(r,s,cp),a=this.term.height-i.rendered-tt-nt-Je+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-tt-nt-Je;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 pp;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,t=Math.max(1,e-2),s=this.dispatcher.state(),r=ls(s.buffer,t);return Math.min(cp,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(lT,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(uT,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let t=this.term.width,s=this.optionsRows(),r=this.term.height-s-tt-nt-Je+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${t}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${At(e.title,t-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let l=e.options[d];if(!l)continue;let u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,h=l.label.padEnd(a),m=t-p.length-3,y=`${p}${At(`${h} ${l.value}`,m)}`;o(`opts|o|${t}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${t}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),t=this.term.width,s=this.wrapBtwTail(t,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,t){if(e<=4){let o=Math.min(t,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(t<=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>=t)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>t?i.slice(i.length-t):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let t=this.term.width,r=this.term.height-this.promptRows()-tt-nt-Je,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(t,c);for(let f=0;f<c;f++){let p=d+1+f,h=u.length-c+f,m=h>=0?u[h]:void 0,y=Bb(`btw|c${f}`,t,m);this.paintRow(p,y,()=>{m?this.writeFormattedLine(m,t):this.term.noFormat(" ".repeat(t))})}}wrapTail(e,t){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let u of this.lines)s(u)||d.push(u);let l=Math.min(t,d.length);return{rows:d.slice(d.length-l),exhausted:t>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),t<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=d,i>=t)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,t){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=gr(r),o=Math.max(1,t-i-1),a=Ka(e.bodyStyle),c=e.ansi?vT(e.body,o):CT(e.body,o,{stripMarkup:a}),d=[],l=0,u=0;for(let f=0;f<c.length;f++){let p=c[f]??"",h={prefix:f===0?e.prefix:" ".repeat(i),body:p};if(e.prefixStyle!==void 0&&(h.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(h.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(h.blockKey=e.blockKey),e.hoverSubKey!==void 0&&(h.hoverSubKey=e.hoverSubKey),e.fillRow&&(h.fillRow=!0),e.ansi&&(h.ansi=!0),f===0&&e.iterm2Image&&(h.iterm2Image=e.iterm2Image),s!==void 0&&p.length>0)if(e.ansi){let m=l,y=0;for(let S=0;S<p.length;){let x=Nn(p,S);if(x){S+=x.text.length,x.width>0&&(y+=1);continue}y+=1,S+=1}let w=y;for(;w>0&&l<e.body.length;){let S=Nn(e.body,l);if(S){l+=S.text.length,S.width>0&&(w-=1);continue}l+=1,w-=1}let v=l;if(f===c.length-1){for(;v<e.body.length;){let S=Nn(e.body,v);if(!S)break;v+=S.text.length}l=v}this.wrapOrigin.set(h,{sourceLineId:s,sourceColOffset:m,sourceColEnd:v})}else{let m=e.body.indexOf(p,u),y=m===-1?u:m;this.wrapOrigin.set(h,{sourceLineId:s,sourceColOffset:y}),u=y+p.length}d.push(h)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,t,s=null,r=0,i=null,o=!1){e.prefix&&$s(this.term,e.prefix,e.prefixStyle??e.bodyStyle,o);let a=Math.max(0,t-gr(e.prefix??"")),c=Ka(e.bodyStyle),d=e.ansi?e.body:At(e.body,a,{stripMarkup:c}),l=(u,f)=>{if(u.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let p=s!==null&&s>=f?s-f:null;Nb(this.term,u,e.bodyStyle,this.scrollbackHighlight,p,r,o)}else $s(this.term,u,e.bodyStyle,o)};if(i!==null){let u=Math.max(0,Math.min(d.length,i.start)),f=Math.max(u,Math.min(d.length,i.end)),p=Ka(e.bodyStyle)||e.ansi===!0;if(l(d.slice(0,u),0),f>u){let m=d.slice(u,f);p&&(m=Db(m)),$s(this.term,m,"selection-highlight",o)}let h=d.slice(f);if(p&&f>u){let m=xT(d.slice(0,f));m.length>0&&(h=m+h)}l(h,f)}else this.scrollbackHighlight!==null&&!e.ansi?Nb(this.term,d,e.bodyStyle,this.scrollbackHighlight,s,r,o):$s(this.term,d,e.bodyStyle,o);if(e.fillRow||o){let u=e.ansi?Ye(d):gr(d),f=a-u;if(f>0){let p=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;$s(this.term," ".repeat(f),p,o)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};zb=/[^\x20-\x7e]/,yp=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Kb=!1;ST=/[a-zA-Z+\-:_!#/]/;ul=ft});function MT(n,e,t=ml){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=t[n];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,n-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(t.length-1,n+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,n-1)};let r=t.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=t[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:n}}async function Gb(n,e){Ln();let t=ft(e.sessionId),s=e.importedFromMachine??"another machine",r=at(e.cwd),i=ml.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+ml.length*2+2,d=Bn(n,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:t},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)n.moveTo(d.contentX,d.contentY+f),n.dim.noFormat(` ${p.label}`),n.noFormat(Ge(p.value,l-p.label.length-2)),f++;return f++,Xb(n,d,f,{intro:"What do you want to do?",choices:ml,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return ds({term:n,render:o,onKey:(a,c,d,l)=>{let u=_T(a,d);if(!u)return;let f=MT(i,u);if(f.kind==="cancel"){l("cancel");return}if(f.kind==="back"){l("back");return}if(f.kind==="resolve"){l(f.action);return}f.selected!==i&&(i=f.selected,o())}})}function Xb(n,e,t,s){let r=e.contentW,i=t;n.moveTo(e.contentX,e.contentY+i),n.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}`;n.moveTo(e.contentX,e.contentY+i),o===s.selected?n.brightWhite.bgBlue.noFormat(Oa(d,r)):n.noFormat(d),i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${a.description}`),i++}i++,n.moveTo(e.contentX,e.contentY+i),n.dim.noFormat(` ${s.footer}`)}function _T(n,e){return n==="UP"?{kind:"up"}:n==="DOWN"?{kind:"down"}:n==="ENTER"||n==="KP_ENTER"?{kind:"enter"}:n==="ESCAPE"?{kind:"back"}:n==="CTRL_C"||n==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:n}:null}async function Zb(n,e,t){let s=ft(e.sessionId),r=e.title??at(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=Bn(n,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;n.moveTo(c.contentX,c.contentY+l),n.dim.noFormat(" session: "),n.noFormat(Ge(s,d-10)),l++,n.moveTo(c.contentX,c.contentY+l),n.noFormat(" "+Ge(r,d-2)),l++,l++,Xb(n,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(),n.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),t.pop(),c(p)},f=(p,h,m)=>{if(p==="CTRL_C"||p==="CTRL_D"){u("cancel");return}if(p==="ESCAPE"){u("back");return}if(p==="ENTER"||p==="KP_ENTER"){u(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(m?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};t.push({onKey:(p,h,m)=>{d||f(p,h,m)},onResize:()=>{d||a()}})})}var ml,vp=V(()=>{"use strict";ve();Zn();ti();ml=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Ya(n){if(n.length===0)return"";let e=n[0]??"";for(let t=1;t<n.length;t++){let s=n[t]??"",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 ev(n){let{matches:e,firstLine:t}=n;if(e.length===0)return null;let s=t.indexOf(" "),r=s===-1?t:t.slice(0,s),i=s===-1?"":t.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Ya(e);return o.length<=r.length?null:o+i}var gl=V(()=>{"use strict"});var Oo,Sp=V(()=>{"use strict";Oo=class{buffer;cur;killBuf="";undoStack=[];redoStack=[];constructor(e=""){this.buffer=e,this.cur=e.length}get text(){return this.buffer}get cursor(){return this.cur}setText(e,t={}){t.recordUndo&&this.recordEdit(),this.buffer=e,this.cur=e.length}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}snap(){return{text:this.buffer,cursor:this.cur}}restore(e){this.buffer=e.text,this.cur=e.cursor}recordEdit(){this.undoStack.push(this.snap()),this.undoStack.length>500&&this.undoStack.shift(),this.redoStack=[]}undo(){let e=this.undoStack.pop();return e===void 0?!1:(this.redoStack.push(this.snap()),this.restore(e),!0)}redo(){let e=this.redoStack.pop();return e===void 0?!1:(this.undoStack.push(this.snap()),this.restore(e),!0)}moveLeft(){this.cur>0&&(this.cur-=1)}moveRight(){this.cur<this.buffer.length&&(this.cur+=1)}moveHome(){this.cur=0}moveEnd(){this.cur=this.buffer.length}moveWordBackward(){let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;this.cur=e}moveWordForward(){let e=this.buffer.length,t=this.cur;for(;t<e&&/\s/.test(this.buffer[t]??"");)t+=1;for(;t<e&&!/\s/.test(this.buffer[t]??"");)t+=1;this.cur=t}insertText(e){e.length!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+e+this.buffer.slice(this.cur),this.cur+=e.length)}backspace(){this.cur!==0&&(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur-1)+this.buffer.slice(this.cur),this.cur-=1)}deleteForward(){this.cur>=this.buffer.length||(this.recordEdit(),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(this.cur+1))}killLine(){this.cur!==0&&(this.recordEdit(),this.killBuf=this.buffer.slice(0,this.cur),this.buffer=this.buffer.slice(this.cur),this.cur=0)}killToEnd(){this.cur>=this.buffer.length||(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur),this.buffer=this.buffer.slice(0,this.cur))}killWord(){if(this.cur===0)return;let e=this.cur;for(;e>0&&/\s/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&!/\s/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordBackward(){if(this.cur===0)return;let e=this.cur;for(;e>0&&!/\w/.test(this.buffer[e-1]??"");)e-=1;for(;e>0&&/\w/.test(this.buffer[e-1]??"");)e-=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(e,this.cur),this.buffer=this.buffer.slice(0,e)+this.buffer.slice(this.cur),this.cur=e)}killWordForward(){if(this.cur>=this.buffer.length)return;let e=this.cur;for(;e<this.buffer.length&&!/\w/.test(this.buffer[e]??"");)e+=1;for(;e<this.buffer.length&&/\w/.test(this.buffer[e]??"");)e+=1;e!==this.cur&&(this.recordEdit(),this.killBuf=this.buffer.slice(this.cur,e),this.buffer=this.buffer.slice(0,this.cur)+this.buffer.slice(e))}yank(){this.killBuf.length!==0&&this.insertText(this.killBuf)}handleKey(e,t){if(t)return this.insertText(e),!0;switch(e){case"LEFT":case"CTRL_B":return this.moveLeft(),!0;case"RIGHT":case"CTRL_F":return this.moveRight(),!0;case"HOME":case"CTRL_A":return this.moveHome(),!0;case"END":case"CTRL_E":return this.moveEnd(),!0;case"ALT_B":case"META_B":return this.moveWordBackward(),!0;case"ALT_F":case"META_F":return this.moveWordForward(),!0;case"BACKSPACE":return this.backspace(),!0;case"DELETE":return this.deleteForward(),!0;case"CTRL_U":return this.killLine(),!0;case"CTRL_K":return this.killToEnd(),!0;case"CTRL_W":return this.killWord(),!0;case"ALT_BACKSPACE":case"META_BACKSPACE":return this.killWordBackward(),!0;case"ALT_D":case"META_D":return this.killWordForward(),!0;case"CTRL_Y":return this.yank(),!0;case"":return this.undo(),!0;case"\x1B_":case"\x1B":return this.redo(),!0}return!1}}});import*as tv from"os";async function ii(n,e,t={}){let s=t.defaultCwd??(e?await pb(e.cwd):void 0)??tv.homedir();Ln();let r=t.title??"Fork locally \u2014 choose cwd",i=t.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:ft(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:at(e.cwd)}]:[],a=new Oo(s),c=null,d=!1,l=null,u=null,f=null,p=null,h=" Enter accept \xB7 Esc back",m="Enter accept",y="Esc back",w=h.indexOf(m),v=h.indexOf(y),S=()=>{let M=o.length+6;l=Bn(n,{contentHeight:M,title:r,overlay:t.overlay===!0});let D=l.contentW,B=0;for(let K of o)n.moveTo(l.contentX,l.contentY+B),n.dim.noFormat(` ${K.label}`),n.noFormat(Ge(K.value,D-K.label.length-2)),B++;B++,n.moveTo(l.contentX,l.contentY+B),n.noFormat(` ${i}`),B+=2,E(B),B+=2;let O=l.contentY+B;c!==null?(n.moveTo(l.contentX,O),n.red.noFormat(` ${Ge(c,D-2)}`),u=null,f=null,p=null):(n.moveTo(l.contentX,O),n.dim.noFormat(h),u=O,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+v,end:l.contentX+v+y.length-1})},x=()=>o.length+3,T=0,E=M=>{if(!l)return;let D=M??x();n.moveTo(l.contentX,l.contentY+D).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+D),n.dim.noFormat("\u2502"),n.moveTo(l.contentX,l.contentY+D),n.noFormat(" ");let O=Math.max(1,l.contentW-1-2),K=a.text,X=a.cursor;X<T&&(T=X),X-T>=O&&(T=X-O+1),T<0&&(T=0);let Z=K.slice(T,T+O);T>0&&Z.length>0&&(Z="\u2026"+Z.slice(1));let Q=X-T;if(d){n.noFormat(Z);return}Q>=Z.length?(n.noFormat(Z),n.bgWhite(" ")):(n.noFormat(Z.slice(0,Q)),n.bgWhite.noFormat(Z[Q]??" "),n.noFormat(Z.slice(Q+1)))},$=()=>{if(E(),!l)return;let M=x()+2;n.moveTo(l.contentX,l.contentY+M).eraseLineAfter(),n.moveTo(l.x+l.w-1,l.contentY+M),n.dim.noFormat("\u2502");let D=l.contentY+M;n.moveTo(l.contentX,D),c!==null?(n.red.noFormat(` ${Ge(c,l.contentW-2)}`),u=null,f=null,p=null):(n.dim.noFormat(h),u=D,f={start:l.contentX+w,end:l.contentX+w+m.length-1},p={start:l.contentX+v,end:l.contentX+v+y.length-1})},N=M=>{if(d)return;let D=a.text;d=!0,c=null,$(),Ha(D).then(B=>{if(d=!1,B.ok){M({kind:"ok",path:B.path});return}c=B.reason,$()})};return ds({term:n,render:S,overlay:t.overlay===!0,onKey:(M,D,B,O)=>{if(!d){if(M==="ENTER"||M==="KP_ENTER"){N(O);return}if(M==="ESCAPE"){O({kind:"back"});return}if(M==="CTRL_C"||M==="CTRL_D"){O({kind:"cancel"});return}if(M==="TAB"){d=!0,hb(a.text).then(K=>{if(d=!1,K.matches.length===0)return;let X;if(K.matches.length===1)X=K.prefix+K.matches[0];else{let Z=Ya(K.matches);if(Z.length<=K.basePrefix.length)return;X=K.prefix+Z}X!==a.text&&(a.setText(X,{recordUndo:!0}),c=null,$())});return}if(a.handleKey(M,B?.isCharacter===!0)){c=null,$();return}}},onMouse:(M,D,B)=>{if(d||M!=="MOUSE_LEFT_BUTTON_PRESSED")return;let O=D?.x,K=D?.y;if(!(typeof O!="number"||typeof K!="number")){if(l!==null&&(O<l.x||O>=l.x+l.w||K<l.y||K>=l.y+l.h)){B({kind:"back"});return}if(u!==null&&K===u){if(f!==null&&O>=f.start&&O<=f.end){N(B);return}if(p!==null&&O>=p.start&&O<=p.end){B({kind:"back"});return}}}}})}var kp=V(()=>{"use strict";ve();Zn();Yf();gl();ti();Sp()});import*as sv from"fs";import*as rv from"os";import*as yl from"path";function wl(n,e){let t=e;for(;t>0;){let s=n[t-1]??"";if(/\s/.test(s)){if(s===" "&&n[t-2]==="\\"){t-=2;continue}break}t-=1}return t===e?null:{token:n.slice(t,e),start:t}}function $T(n){return n.length===0?!1:n.includes("/")?!0:n==="~"||n==="."||n===".."}function FT(n){return n.replace(/\\ /g," ")}function nv(n){return n.replace(/ /g,"\\ ")}function OT(n){let e=n.lastIndexOf("/");return e===-1?{dirPrefix:"",base:n}:{dirPrefix:n.slice(0,e+1),base:n.slice(e+1)}}function LT(n,e){let t=n.length===0?".":n;return(t==="~"||t.startsWith("~/"))&&(t=rv.homedir()+t.slice(1)),yl.isAbsolute(t)?t:yl.resolve(e,t)}function BT(n){let e;try{e=sv.readdirSync(n,{withFileTypes:!0})}catch{return null}return e.map(t=>({name:t.name,isDir:t.isDirectory()}))}function bl(n,e,t=BT){let s=FT(n),{dirPrefix:r,base:i}=OT(s);if(r.length===0&&!$T(n)&&i.length===0)return null;let o=LT(r,e),a=t(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:nv(r+p),candidates:l}}let u=Ya(d.map(f=>f.name));return{replacement:nv(r+u),candidates:l}}var Ip=V(()=>{"use strict";gl()});function NT(n){process.stdout.write(`\x1B]9;4;${n}\x1B\\`)}function DT(n,e,t){let s=`${t.agentId}@${t.version}`;if(t.source==="npm")return t.phase==="install_start"||t.phase==="download_start"?`${n} installing ${s} via npm\u2026`:t.phase==="installed"?`${n} ${s} installed`:`${n} installing ${s} via npm\u2026`;if(t.phase==="download_start"||t.phase==="download_progress"){let r=t.receivedBytes??0,i=t.totalBytes??0,o=(r/1e6).toFixed(1);if(i>0){let a=(i/1e6).toFixed(1),c=Math.min(100,Math.floor(r/i*100));return`${n} downloading ${s} ${o}/${a} MB (${c}%)`}return`${n} downloading ${s} ${o} MB`}return t.phase==="download_done"?`${n} downloaded ${s}, verifying\u2026`:t.phase==="extract"?`${n} extracting ${s}\u2026`:t.phase==="installed"?`${n} ${s} installed`:e||n}function vl(n,e){let t=!1,s="",r=!1,i=n,o=a=>{t||a===3&&r||a===0&&!r||(r=a===3,NT(a))};return{write(a){t||(i=a,s=a,e.write(a))},applyProgress(a){if(t)return;a.phase==="download_start"||a.phase==="download_progress"||a.phase==="install_start"||a.phase==="extract"||a.phase==="download_done"?o(3):a.phase==="installed"&&o(0);let d=DT(i,s,a);s=d,e.write(d)},finalize(){t||(t=!0,o(0),e.finalize())}}}function iv(n){let e=!1;return{write(t){e||(process.stdout.write("\r"),n.eraseLineAfter(),n.brightYellow(t))},finalize(){e||(e=!0,process.stdout.write(`
217
+ `))}}}var xp=V(()=>{"use strict"});function Cp(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Rp(n,e){let t=()=>{process.stdout.write(Xr),process.stdout.write(Ps),process.stdout.write(Zr),process.stdout.write(ei),process.stdout.write(Co),process.stdout.write(Ro),process.stdout.write(To),process.stdout.write(Gr),process.stdout.write("\x1B>")};t();let s=e.prefs??Cp();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=Sl(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(U=>U.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(U=>U.interactive===!0)),P=WT(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??yo,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>bo(R,Date.now())),l=vo(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let h=!1,m="",y=120,w=!1,v=0,S="normal",x=null,T=!1,E="input",$=new _s({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,O=null,K=!1,X=null,Z=null,Q=null,fe=null,Me=()=>{if(fe!==null){let R=fe;return{plain:R,render:()=>{n.brightYellow.noFormat(` ${R}`)}}}if(h){let R=a.length===0?"no matches":`${a.length} match${a.length===1?"":"es"}`;return{plain:`/${m}\u2589 ${R} \xB7 ^c clears`,render:()=>{n.brightYellow.noFormat(` /${m}`),n.bgBrightYellow(" "),n.dim.noFormat(` ${R} \xB7 ^c clears`)}}}return Q!==null?{plain:Q,render:()=>{n.dim.noFormat(` ${Q}`)}}:null},In=!1,De=new _s({history:[]});if(e.initialPrompt&&De.setBuffer(e.initialPrompt),e.initialAttachments)for(let R of e.initialAttachments)De.addAttachment(R);let us=e.config.tui.promptHistoryMaxEntries;ca(L.globalTuiHistoryFile()).then(R=>{let P=R.length>us?R.slice(R.length-us):R;De.setHistory(P)}).catch(()=>{});let Se=new Fo(n),G=Ms(n),Ie=Jt(n),je=0,Yt="",Os=0,un=[],wt=1,Ls=0,Bs=0,fs=0,ai="",Lo=[],xn=1,Za=0,Bo=[],me=1,Ns=0,ed=0,di=0,ci=()=>{G=Ms(n),Ie=Jt(n);let R=Math.max(10,Ie-Ap-1);Os=Math.max(10,Ie-ov);let P=Math.max(10,Ie-8),U=De.state().attachments.length,Y=U>0?` \xB7 \u{1F4CE}\xD7${U}`:"",re=Math.max(10,P-Y.length);Yt=qT(r,re)+Y;let ie=De.state();un=ls(ie.buffer,Os);let we=Fs(un,ie,Va);wt=we.rendered,Ls=we.windowStart,Bs=we.cursorVisualRow,fs=we.cursorVisualCol;let Ce=6+wt,Ze=Math.max(3,G-Ce);je=Math.min(a.length,Ze),ai=ur(wo,l,R,c).padEnd(R),Lo=d.map(ht=>ur(ht,l,R,c).padEnd(R))},li=()=>{d=a.map(R=>bo(R,Date.now())),l=vo(d,c),u=1+a.length,ci()},Ct=()=>{let R=o(i);h&&m.length>0?a=R.filter(P=>zT(P,m)):a=R,li(),h?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An()},ps=R=>{if(R!==void 0){let P=a.findIndex(U=>U.sessionId===R);if(P>=0){f=P+1,An();return}}f=a.length>0?1:0,p=0,An()},An=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+je?p=R-je+1:p+je>a.length&&(p=Math.max(0,a.length-je))},he=()=>Math.max(2,Ie-3),Ke=!1,qe=!0,gt=!1,Ds=[],hs=e.composerAgentId,ms=e.composerModel,ui=()=>{let R=hs;if(!R)return"";let P=ms;return P?`${R}\u2022${P}`:R},Hs=null,gs=null,Lt=null,fi=()=>{let R=he(),P=`\u2500 ${Yt} `,U=ui(),Y="";if(U.length>0){let Ve=`\u2500 ${U} `;Ve.length+P.length+1<=R&&(Y=Ve)}let re=Math.max(1,R-P.length-Y.length),ie="\u2500".repeat(re),we=(f===0||Ke)&&qe;if(Hs=P.length>0?{start:2,end:1+P.length}:null,Y.length>0){let Ve=1+P.length+re+1;gs={start:Ve,end:Ve+Y.length-1}}else gs=null;let Ce=we?n.brightBlue:n.dim,Ze=we?n.brightBlue.bold:n.dim.bold,ht=(Ve,Ks)=>{(Ks?Ze:Ce).noFormat(Ve)};Ce.noFormat("\u256D"),ht(P,Lt==="cwd"),Ce.noFormat(ie),Y&&ht(Y,Lt==="agent"),Ce.noFormat("\u256E")},Hn=()=>{let R=he(),P="\u2500".repeat(R);(f===0||Ke)&&qe?n.brightBlue.noFormat(`\u2570${P}\u256F`):n.dim.noFormat(`\u2570${P}\u256F`)},No=()=>{let R=Me();if(R===null)return;let P=Math.max(0,Jt(n)-2);if(R.plain.length>P){let U=R.plain.slice(0,Math.max(0,P-1))+"\u2026";n.dim.noFormat(` ${U}`);return}R.render()},Us=R=>{let P=un[R];return P?(De.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},pi=R=>{let P=he(),U=Us(R),Y=Math.max(0,P-1-U.length),re=" ".repeat(Y);(f===0||Ke)&&qe?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${U}${re}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${U}${re}`),n.dim.noFormat("\u2502"))},Rt=R=>{let P=Lo[R]??"",U=a[R],Y=U&&U.priority&&U.priority>0?"* ":" ";f===R+1&&!Ke&&qe?n.brightWhite.bgBlue.noFormat(`${Y}${P}`):n.noFormat(`${Y}${P}`)},Vt=()=>{let R=p,P=Math.max(0,a.length-p-je),U=[];if(s.filters.cwdOnly&&U.push({kind:"plain",text:"cwd-only"}),s.filters.hostFilter!=="__all"){let Y=s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`;U.push({kind:"host",text:Y})}return s.filters.includeNonInteractive&&U.push({kind:"plain",text:"+non-interactive"}),R>0&&U.push({kind:"plain",text:`\u2191 ${R} above`}),P>0&&U.push({kind:"plain",text:`\u2193 ${P} below`}),U},Un=()=>{let R=Vt();return R.length===0?"":` ${R.map(P=>P.text).join(" \xB7 ")}`},Re=R=>ft(R),td=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,X?`${X.text}${X.cursor}`:"",Z??"",h?`1|${m}|${a.length}`:"0",Un(),ki?"h1":"h0",zs?"ho1":"ho0"].join("")},$e=()=>{Oe(()=>{Se.paintRow(qn(),td(),()=>{let R=()=>{Kn=null,Zt=null};if(S==="confirm-kill"&&x)R(),n.brightYellow.noFormat(` kill ${Re(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)R(),x.status==="warm"?n.brightRed.noFormat(` kill + delete ${Re(x.sessionId)}? [y/N]`):n.brightRed.noFormat(` delete ${Re(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)R(),n.dim.noFormat(` working on ${Re(x.sessionId)}\u2026`);else if(S==="rename"&&x&&X){R();let P=X.text,U=X.cursor;n.brightYellow.noFormat(" title: "),n.brightYellow.noFormat(P.slice(0,U)),U<P.length?(n.bgBrightYellow.noFormat(P[U]??" "),n.brightYellow.noFormat(P.slice(U+1))):n.bgBrightYellow(" "),n.dim.noFormat(" Enter saves \xB7 Esc cancels")}else if(Z!==null)R(),n.dim.noFormat(` ${Z}`);else{let P=Vt(),U=Un(),Y="Esc \xB7 Go Back",re=Y.length,ie=5,we=U.length,Ce=Math.max(1,Ie-we-re-ie);if(Zt=null,P.length>0){n.dim.noFormat(" ");let Ze=3;for(let ht=0;ht<P.length;ht++){let Ve=P[ht];ht>0&&(n.dim.noFormat(" \xB7 "),Ze+=3),Ve.kind==="host"?(Zt={start:Ze,end:Ze+Ve.text.length-1},zs?n.noFormat(Ve.text):n.dim.noFormat(Ve.text)):n.dim.noFormat(Ve.text),Ze+=Ve.text.length}}n.dim(" ".repeat(Ce)),ki?n.noFormat(Y):n.dim.noFormat(Y),Kn={start:Ie-ie-re+1,end:Ie-ie}}})})},Tt=R=>xn+1+R,jn=()=>xn+wt+1,Qt=()=>xn+wt+3,I=R=>Qt()+1+(R-p),qn=()=>Qt()+1+je,fn=()=>{let R=Bs-Ls;if(R<0||R>=wt)return;let P=3+fs;n.moveTo(P,Tt(R))},js=()=>qe?f===0?"f":Ke?"h":"u":"x",hi=()=>`ct|${js()}|${he()}|${Yt}|${ui()}|${Lt??""}`,Do=()=>`cb|${js()}|${he()}`,br=()=>fe!==null?`cs|i|${fe}`:h?`cs|s|${m}|${a.length}`:Q!==null?`cs|h|${Q}`:"blank",Wn=R=>`cbb|${js()}|${he()}|${Us(R)}`,Ho=()=>`h|${ai}`,mi=R=>{let P=a[R],U=P&&P.priority&&P.priority>0?"* ":" ",Y=Lo[R]??"";return`sr|${f===R+1&&!Ke&&qe?"1":"0"}|${U}${Y}`},Xe=()=>{Oe(()=>{n.hideCursor(),ci(),An(),xn=1,Se.ensureSize(Ie,G),Se.paintRow(xn,hi(),()=>{fi()});for(let R=0;R<wt;R++){let P=Ls+R;Se.paintRow(Tt(R),Wn(P),()=>{pi(P)})}Se.paintRow(jn(),Do(),()=>{Hn()}),Se.paintRow(jn()+1,br(),()=>No()),Se.paintRow(Qt(),Ho(),()=>{n.dim.noFormat(` ${ai}`)});for(let R=0;R<je;R++){let P=p+R,U=Qt()+1+R;P<a.length?Se.paintRow(U,mi(P),()=>{Rt(P)}):Se.paintRow(U,"blank",()=>{})}$e();for(let R=qn()+1;R<=G;R++)Se.paintRow(R,"blank",()=>{});f===0&&(fn(),n.hideCursor(!1))})},Uo=()=>{Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),Xe()},ys=()=>{Oe(()=>{n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(" Picker hotkeys")(`
218
218
 
219
- `);for(let R of BT){if(R===null){n(`
220
- `);continue}let[P,U]=R;n.brightCyan.noFormat(` ${P.padEnd(LT)}`),n.noFormat(U)(`
219
+ `);for(let R of jT){if(R===null){n(`
220
+ `);continue}let[P,U]=R;n.brightCyan.noFormat(` ${P.padEnd(UT)}`),n.noFormat(U)(`
221
221
  `)}n(`
222
222
  `),n.dim.noFormat(" press any key to dismiss")(`
223
- `)})},qt=()=>me+4,xl=2,bt=0,gs=()=>{G=Es(n);let R=Math.max(2,G-(me+3)-xl);return Math.max(1,Math.floor(R/2))},td=()=>{let R=gs();D<bt?bt=D:D>=bt+R&&(bt=D-R+1),bt+R>N.length&&(bt=Math.max(0,N.length-R)),bt<0&&(bt=0)},nd=R=>{Ie=Jt(n);let P=Math.max(2,Ie-3),U="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,P-U.length));R?n.brightBlue.noFormat(`\u256D${U}${Y}\u256E`):n.dim.noFormat(`\u256D${U}${Y}\u256E`),n.styleReset()},yr=()=>{Ie=Jt(n),Xa=Math.max(10,Ie-nv);let R=$.state();Lo=ds(R.buffer,Xa);let P=_s(Lo,R,OT);me=P.rendered,Ls=P.windowStart,Za=P.cursorVisualRow,oi=P.cursorVisualCol},Uo=(R,P)=>{Ie=Jt(n);let U=Math.max(2,Ie-3),Y=Lo[R],re="";Y&&(re=($.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let ie=Math.max(0,U-1-re.length),we=" ".repeat(ie);P?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${re}${we}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${re}${we}`),n.dim.noFormat("\u2502")),n.styleReset()},Gt=R=>{Ie=Jt(n);let P=Math.max(2,Ie-3),U="\u2500".repeat(P);R?n.brightBlue.noFormat(`\u2570${U}\u256F`):n.dim.noFormat(`\u2570${U}\u256F`),n.styleReset()},lt=()=>3+oi,wr=()=>2+(Za-Ls),hi=()=>{let R=E==="input";Oe(()=>{R&&n.hideCursor(),n.moveTo(1,1),nd(R);for(let P=0;P<me;P++)n.moveTo(1,2+P),Uo(Ls+P,R);n.moveTo(1,2+me),Gt(R),R&&(n.moveTo(lt(),wr()),n.hideCursor(!1))})},mi=()=>{Oe(()=>{n.hideCursor();for(let R=0;R<me;R++)n.moveTo(1,2+R),Uo(Ls+R,!0);n.moveTo(lt(),wr()),n.hideCursor(!1)})},br={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},gi=(R,P)=>{let U=N[R];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Jt(n),re=Math.max(20,Y-kp),ie=ft(U.sessionId),we=U.title??at(U.cwd),Ce=P&&U.snippets.length>1?` [${B+1}/${U.snippets.length}]`:P&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",Ze=`${ie} ${U.status==="warm"?"warm":"cold"}`,ht=Math.max(5,re-Ze.length-Ce.length-2),Ve=Ca(we,ht),Ws=`${Ze} ${Ve}${Ce}`.padEnd(re),Bt=U.snippets[P?B:0],bs=Bt?br[Bt.kind]??Bt.kind:"",vs=Bt?.toolName?`${bs} \xB7 ${Bt.toolName}`:bs,ut=Math.max(10,re-vs.length-6),vt=Bt?Ca(Bt.text,ut):"",mn=Bt?` ${vs} ${vt}`:" (no snippet)";return{rowBudget:re,line1:Ws,line2:mn.padEnd(re+kp),focusedRow:P}},jo=(R,P)=>{let{line1:U,focusedRow:Y}=gi(R,P);Y?n.brightWhite.bgBlue.noFormat(`\u276F ${U}`):n.noFormat(` ${U}`),n.styleReset()},qo=(R,P)=>{let{line2:U}=gi(R,P);n.dim.noFormat(U),n.styleReset()},vr=()=>{if(K)n.dim.noFormat(" searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(O!==null)n.brightRed.noFormat(` ${O}`),n.styleReset(),n.eraseLineAfter();else if(E==="input")N.length>0?n.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):n.dim.noFormat(" Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let R=N.length,P=M?" \xB7 truncated":"",U=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";n.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Cn=()=>{yr();let R=E==="input",P=$.state().buffer.join(`
224
- `);Oe(()=>{n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),nd(R);for(let Y=0;Y<me;Y++)n.moveTo(1,2+Y),Uo(Ls+Y,R);n.moveTo(1,2+me),Gt(R);let U=N.length;if(U===0)n.moveTo(1,qt()),K||(O===null&&P.trim().length===0?(n.dim.noFormat(" type a query in the box above, then press Enter"),n.eraseLineAfter()):O===null&&(n.dim.noFormat(" no matches"),n.eraseLineAfter())),n.moveTo(1,qt()+1),vr();else{td();let Y=gs(),re=E!=="input";for(let ie=0;ie<Y;ie++){let we=bt+ie;n.moveTo(1,qt()+ie*2),we<U?jo(we,re&&we===D):n.eraseLineAfter(),n.moveTo(1,qt()+ie*2+1),we<U?qo(we,re&&we===D):n.eraseLineAfter()}n.moveTo(1,qt()+Y*2),vr()}R&&(n.moveTo(lt(),wr()),n.hideCursor(!1))})},ys=(R,P)=>{let U=R-bt;U<0||U>=gs()||Oe(()=>{n.moveTo(1,qt()+U*2),jo(R,P),n.moveTo(1,qt()+U*2+1),qo(R,P)})},yi=()=>{Oe(()=>{n.moveTo(1,qt()+gs()*2),vr()})},sd=()=>{Oe(()=>{let R=gs(),P=N.length,U=E!=="input";for(let Y=0;Y<R;Y++){let re=bt+Y;n.moveTo(1,qt()+Y*2),re<P?jo(re,U&&re===D):n.eraseLineAfter(),n.moveTo(1,qt()+Y*2+1),re<P?qo(re,U&&re===D):n.eraseLineAfter()}n.moveTo(1,qt()+R*2),vr()})},Us=()=>$.state().buffer.join(`
225
- `),Rn=R=>{let P=me;$.feed({type:"paste",text:R}),yr(),me!==P?Cn():mi()},Tn=async()=>{let R=Us().trim();if(R.length!==0){if(a.length===0){O="no sessions in view to search",Cn();return}K=!0,O=null,Cn();try{let P=await vy(e.target,R,{sessionIds:a.map(U=>U.sessionId)});N=P.results,M=P.truncated,D=0,B=0,bt=0,E=P.results.length>0?"results":"input",yr()}catch(P){O=`search failed: ${P.message}`}finally{K=!1,Cn()}}},ws=()=>{},Wt=()=>{Oe(()=>{let R=f===0;R&&n.hideCursor(),Se.paintRow(xn,fi(),()=>{li()}),Se.paintRow(Un(),No(),()=>{Dn()});for(let P=0;P<wt;P++){let U=Fs+P;Se.paintRow(Tt(P),qn(U),()=>{ui(U)})}R&&(fn(),n.hideCursor(!1))})},pn=()=>{Oe(()=>{Se.paintRow(Un()+1,gr(),()=>Bo())})},js=()=>{Q!==null&&(Q=null,pn())},Sr=()=>{Oe(()=>{let R=De.state();un=ds(R.buffer,$s);let P=_s(un,R,Ya);Fs=P.windowStart,Os=P.cursorVisualRow,ls=P.cursorVisualCol;let U=f===0;U&&n.hideCursor();for(let Y=0;Y<wt;Y++){let re=Fs+Y;Se.paintRow(Tt(Y),qn(re),()=>{ui(re)})}U&&(fn(),n.hideCursor(!1))})},wi=async()=>{let R=await il();if(!R.ok){Z=R.reason,$e();return}if(R.kind!=="image"){let P=De.state(),U=[...P.buffer],Y=P.row,re=P.col;De.feed({type:"paste",text:R.text});let ie=De.state();if(U.length!==ie.buffer.length||Y!==ie.row||re!==ie.col||!U.every((Ce,Ze)=>Ce===ie.buffer[Ze])){let Ce=ds(ie.buffer,$s);_s(Ce,ie,Ya).rendered!==wt?Xe():Sr()}return}De.addAttachment(R.attachment),Z=`attached ${R.attachment.name??"image"}`,Xe()},Al=R=>{R<p||R>=p+je||Oe(()=>{Se.paintRow(I(R),pi(R),()=>{Rt(R)})})},Xt=()=>{Oe(()=>{for(let R=0;R<je;R++){let P=Qt()+1+R,U=p+R;U<a.length?Se.paintRow(P,pi(U),()=>{Rt(U)}):Se.paintRow(P,"blank",()=>{})}$e()})},Cl=()=>{Oe(()=>{Se.paintRow(Qt(),Do(),()=>{n.dim.noFormat(` ${ii}`)});for(let R=0;R<je;R++){let P=Qt()+1+R,U=p+R;U<a.length?Se.paintRow(P,pi(U),()=>{Rt(U)}):Se.paintRow(P,"blank",()=>{})}$e(),f===0&&(fn(),n.hideCursor(!1))})},hn=!1,Wn="",rd=0,id=200,kr=null,bi=!1,zn=null,vi=!1,Zt=null,qs=!1,zt=null,Si=null,Ir=null,ki=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let Y=P.indexOf("\x1B[I"),re=P.indexOf("\x1B[O"),ie=Y===-1?re:re===-1?Y:Math.min(Y,re);if(ie===-1)break;let we=qe;qe=ie===Y,qe&&(rd=Date.now()),we!==qe&&!gt&&Bs.length<=1&&Oe(()=>{Wt(),Xt()}),P=P.slice(0,ie)+P.slice(ie+"\x1B[I".length)}if(P.length===0)return}if(!hn&&P===""&&Si){Si();return}if(!hn&&(P===""||P==="\x1B_"||P==="\x1B")){Ir?.(P);return}if(hn){let Y=P.indexOf(Pa);if(Y===-1){Wn+=P;return}Wn+=P.slice(0,Y),hn=!1;let re=Buffer.from(Wn,"binary").toString("utf-8").replace(/\r\n?/g,`
226
- `);Wn="";let ie=P.slice(Y+Pa.length);if(T)E==="input"&&!K&&Rn(re);else if(f===0&&!h){let we=De.feed({type:"paste",text:re});for(let Ve of we)Ve.type==="attachment-request"&&wi();let Ce=De.state(),Ze=ds(Ce.buffer,$s);_s(Ze,Ce,Ya).rendered!==wt?Xe():Sr()}ie.length>0&&zt&&zt(Buffer.from(ie,"binary"));return}let U=P.indexOf(Io);if(U===-1){zt?.(R);return}U>0&&zt?.(Buffer.from(P.slice(0,U),"binary")),P=P.slice(U+Io.length),hn=!0,P.length>0&&ki(Buffer.from(P,"binary"))};return Xe(),await new Promise(R=>{let P=null,U=!1,Y=null,re=!1,ie=Bs,we=F=>{ie.push(F)},Ce=()=>{ie.pop(),gt||ie[ie.length-1]?.onResize()},Ze={push:we,pop:Ce},ht=()=>{let F={kind:"new",cwd:r},z=De.state().attachments;return z.length>0&&(F.attachments=[...z]),fs&&(F.agentId=fs),ps&&(F.model=ps),F},Ve=async()=>{Ys(),Se.clearCache(),we({onKey:()=>{},onResize:()=>{}});let z;try{z=await si(n,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{Ce(),Tr()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=vl(i,r),Ct()),gt||Xe()},Ws=async()=>{let F=e.availableAgents;if(!F||F.length===0)return;Ys(),Se.clearCache(),we({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await Ha(n,F,fs,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{Ce(),Tr()}if(ue.kind==="select"){fs=ue.agentId;let J=e.config.defaultModels;if(ps=J?J[ue.agentId]:void 0,ue.persist)try{await Mi(ue.agentId)}catch{}}gt||Xe()};ws=()=>{$=new Ps({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,bt=0,O=null,K=!1,E="input",T=!1,Ce()};let Bt=(F,z,ue)=>{zs(),ie[ie.length-1]?.onKey(F,z,ue)},bs=()=>{gt||ie[ie.length-1]?.onResize()};Ir=F=>{gt||ie[ie.length-1]?.onKey(F,null,{})};let vs=!1,ut=()=>{if(vs)return;vs=!0,ie.length=0,P&&(clearInterval(P),P=null),Y&&(Y.abort(),Y=null,U=!1),n.off("key",Bt),n.off("mouse",Rr),n.off("resize",bs),process.stdout.write(Ts),process.stdout.write(_a);let F=n;F.stdin&&zt&&(F.stdin.removeListener("data",ki),F.stdin.on("data",zt),zt=null),hn=!1,Wn="",n.grabInput(!1),oe({src:"grab",site:"picker.detachInput",on:!1})},vt=()=>{gt||(gt=!0,ut(),n.hideCursor(!1),n.moveTo(1,jn()+1),n(`
227
- `))},mn=()=>{if(gt||ie.length>1||S!=="normal"||h||re)return;U&&Y&&(Y.abort(),Y=null,U=!1);let F=f>0?a[f-1]?.sessionId:void 0;U=!0;let z=new AbortController;Y=z,en(F,{silent:!0,signal:z.signal}).finally(()=>{Y===z&&(Y=null),U=!1})},zs=()=>{gt||(P&&clearInterval(P),P=setInterval(mn,3e3))},Nt=()=>(ut(),bl("",{write(z){fe=z,pn()},finalize(){fe=null,vt()}})),En=()=>(vt(),R({kind:In?"exit":"abort"}),!0),gn=()=>{let F=d.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
223
+ `)})},qt=()=>me+4,Al=2,bt=0,ws=()=>{G=Ms(n);let R=Math.max(2,G-(me+3)-Al);return Math.max(1,Math.floor(R/2))},nd=()=>{let R=ws();D<bt?bt=D:D>=bt+R&&(bt=D-R+1),bt+R>N.length&&(bt=Math.max(0,N.length-R)),bt<0&&(bt=0)},sd=R=>{Ie=Jt(n);let P=Math.max(2,Ie-3),U="\u2500 Find sessions ",Y="\u2500".repeat(Math.max(1,P-U.length));R?n.brightBlue.noFormat(`\u256D${U}${Y}\u256E`):n.dim.noFormat(`\u256D${U}${Y}\u256E`),n.styleReset()},vr=()=>{Ie=Jt(n),Za=Math.max(10,Ie-ov);let R=$.state();Bo=ls(R.buffer,Za);let P=Fs(Bo,R,HT);me=P.rendered,Ns=P.windowStart,ed=P.cursorVisualRow,di=P.cursorVisualCol},jo=(R,P)=>{Ie=Jt(n);let U=Math.max(2,Ie-3),Y=Bo[R],re="";Y&&(re=($.state().buffer[Y.bufferIdx]??"").slice(Y.startCol,Y.endCol));let ie=Math.max(0,U-1-re.length),we=" ".repeat(ie);P?(n.brightBlue.noFormat("\u2502"),n.noFormat(` ${re}${we}`),n.brightBlue.noFormat("\u2502")):(n.dim.noFormat("\u2502"),n.noFormat(` ${re}${we}`),n.dim.noFormat("\u2502")),n.styleReset()},Gt=R=>{Ie=Jt(n);let P=Math.max(2,Ie-3),U="\u2500".repeat(P);R?n.brightBlue.noFormat(`\u2570${U}\u256F`):n.dim.noFormat(`\u2570${U}\u256F`),n.styleReset()},lt=()=>3+di,Sr=()=>2+(ed-Ns),gi=()=>{let R=E==="input";Oe(()=>{R&&n.hideCursor(),n.moveTo(1,1),sd(R);for(let P=0;P<me;P++)n.moveTo(1,2+P),jo(Ns+P,R);n.moveTo(1,2+me),Gt(R),R&&(n.moveTo(lt(),Sr()),n.hideCursor(!1))})},yi=()=>{Oe(()=>{n.hideCursor();for(let R=0;R<me;R++)n.moveTo(1,2+R),jo(Ns+R,!0);n.moveTo(lt(),Sr()),n.hideCursor(!1)})},kr={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},wi=(R,P)=>{let U=N[R];if(!U)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Y=Jt(n),re=Math.max(20,Y-Ap),ie=ft(U.sessionId),we=U.title??at(U.cwd),Ce=P&&U.snippets.length>1?` [${B+1}/${U.snippets.length}]`:P&&U.totalMatches>U.snippets.length?` [${U.snippets.length} of ${U.totalMatches}]`:"",Ze=`${ie} ${U.status==="warm"?"warm":"cold"}`,ht=Math.max(5,re-Ze.length-Ce.length-2),Ve=Ra(we,ht),Ks=`${Ze} ${Ve}${Ce}`.padEnd(re),Bt=U.snippets[P?B:0],Ss=Bt?kr[Bt.kind]??Bt.kind:"",ks=Bt?.toolName?`${Ss} \xB7 ${Bt.toolName}`:Ss,ut=Math.max(10,re-ks.length-6),vt=Bt?Ra(Bt.text,ut):"",mn=Bt?` ${ks} ${vt}`:" (no snippet)";return{rowBudget:re,line1:Ks,line2:mn.padEnd(re+Ap),focusedRow:P}},qo=(R,P)=>{let{line1:U,focusedRow:Y}=wi(R,P);Y?n.brightWhite.bgBlue.noFormat(`\u276F ${U}`):n.noFormat(` ${U}`),n.styleReset()},Wo=(R,P)=>{let{line2:U}=wi(R,P);n.dim.noFormat(U),n.styleReset()},Ir=()=>{if(K)n.dim.noFormat(" searching\u2026"),n.styleReset(),n.eraseLineAfter();else if(O!==null)n.brightRed.noFormat(` ${O}`),n.styleReset(),n.eraseLineAfter();else if(E==="input")N.length>0?n.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):n.dim.noFormat(" Enter to search \xB7 Esc cancel"),n.styleReset(),n.eraseLineAfter();else{let R=N.length,P=M?" \xB7 truncated":"",U=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";n.dim.noFormat(`${U}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),n.styleReset(),n.eraseLineAfter()}},Cn=()=>{vr();let R=E==="input",P=$.state().buffer.join(`
224
+ `);Oe(()=>{n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),sd(R);for(let Y=0;Y<me;Y++)n.moveTo(1,2+Y),jo(Ns+Y,R);n.moveTo(1,2+me),Gt(R);let U=N.length;if(U===0)n.moveTo(1,qt()),K||(O===null&&P.trim().length===0?(n.dim.noFormat(" type a query in the box above, then press Enter"),n.eraseLineAfter()):O===null&&(n.dim.noFormat(" no matches"),n.eraseLineAfter())),n.moveTo(1,qt()+1),Ir();else{nd();let Y=ws(),re=E!=="input";for(let ie=0;ie<Y;ie++){let we=bt+ie;n.moveTo(1,qt()+ie*2),we<U?qo(we,re&&we===D):n.eraseLineAfter(),n.moveTo(1,qt()+ie*2+1),we<U?Wo(we,re&&we===D):n.eraseLineAfter()}n.moveTo(1,qt()+Y*2),Ir()}R&&(n.moveTo(lt(),Sr()),n.hideCursor(!1))})},bs=(R,P)=>{let U=R-bt;U<0||U>=ws()||Oe(()=>{n.moveTo(1,qt()+U*2),qo(R,P),n.moveTo(1,qt()+U*2+1),Wo(R,P)})},bi=()=>{Oe(()=>{n.moveTo(1,qt()+ws()*2),Ir()})},rd=()=>{Oe(()=>{let R=ws(),P=N.length,U=E!=="input";for(let Y=0;Y<R;Y++){let re=bt+Y;n.moveTo(1,qt()+Y*2),re<P?qo(re,U&&re===D):n.eraseLineAfter(),n.moveTo(1,qt()+Y*2+1),re<P?Wo(re,U&&re===D):n.eraseLineAfter()}n.moveTo(1,qt()+R*2),Ir()})},qs=()=>$.state().buffer.join(`
225
+ `),Rn=R=>{let P=me;$.feed({type:"paste",text:R}),vr(),me!==P?Cn():yi()},Tn=async()=>{let R=qs().trim();if(R.length!==0){if(a.length===0){O="no sessions in view to search",Cn();return}K=!0,O=null,Cn();try{let P=await xy(e.target,R,{sessionIds:a.map(U=>U.sessionId)});N=P.results,M=P.truncated,D=0,B=0,bt=0,E=P.results.length>0?"results":"input",vr()}catch(P){O=`search failed: ${P.message}`}finally{K=!1,Cn()}}},vs=()=>{},Wt=()=>{Oe(()=>{let R=f===0;R&&n.hideCursor(),Se.paintRow(xn,hi(),()=>{fi()}),Se.paintRow(jn(),Do(),()=>{Hn()});for(let P=0;P<wt;P++){let U=Ls+P;Se.paintRow(Tt(P),Wn(U),()=>{pi(U)})}R&&(fn(),n.hideCursor(!1))})},pn=()=>{Oe(()=>{Se.paintRow(jn()+1,br(),()=>No())})},Ws=()=>{Q!==null&&(Q=null,pn())},xr=()=>{Oe(()=>{let R=De.state();un=ls(R.buffer,Os);let P=Fs(un,R,Va);Ls=P.windowStart,Bs=P.cursorVisualRow,fs=P.cursorVisualCol;let U=f===0;U&&n.hideCursor();for(let Y=0;Y<wt;Y++){let re=Ls+Y;Se.paintRow(Tt(Y),Wn(re),()=>{pi(re)})}U&&(fn(),n.hideCursor(!1))})},vi=async()=>{let R=await ol();if(!R.ok){Z=R.reason,$e();return}if(R.kind!=="image"){let P=De.state(),U=[...P.buffer],Y=P.row,re=P.col;De.feed({type:"paste",text:R.text});let ie=De.state();if(U.length!==ie.buffer.length||Y!==ie.row||re!==ie.col||!U.every((Ce,Ze)=>Ce===ie.buffer[Ze])){let Ce=ls(ie.buffer,Os);Fs(Ce,ie,Va).rendered!==wt?Xe():xr()}return}De.addAttachment(R.attachment),Z=`attached ${R.attachment.name??"image"}`,Xe()},Cl=R=>{R<p||R>=p+je||Oe(()=>{Se.paintRow(I(R),mi(R),()=>{Rt(R)})})},Xt=()=>{Oe(()=>{for(let R=0;R<je;R++){let P=Qt()+1+R,U=p+R;U<a.length?Se.paintRow(P,mi(U),()=>{Rt(U)}):Se.paintRow(P,"blank",()=>{})}$e()})},Rl=()=>{Oe(()=>{Se.paintRow(Qt(),Ho(),()=>{n.dim.noFormat(` ${ai}`)});for(let R=0;R<je;R++){let P=Qt()+1+R,U=p+R;U<a.length?Se.paintRow(P,mi(U),()=>{Rt(U)}):Se.paintRow(P,"blank",()=>{})}$e(),f===0&&(fn(),n.hideCursor(!1))})},hn=!1,zn="",id=0,od=200,Ar=null,Si=!1,Kn=null,ki=!1,Zt=null,zs=!1,zt=null,Ii=null,Cr=null,xi=R=>{let P=R.toString("binary");if(P.includes("\x1B[I")||P.includes("\x1B[O")){for(;;){let Y=P.indexOf("\x1B[I"),re=P.indexOf("\x1B[O"),ie=Y===-1?re:re===-1?Y:Math.min(Y,re);if(ie===-1)break;let we=qe;qe=ie===Y,qe&&(id=Date.now()),we!==qe&&!gt&&Ds.length<=1&&Oe(()=>{Wt(),Xt()}),P=P.slice(0,ie)+P.slice(ie+"\x1B[I".length)}if(P.length===0)return}if(!hn&&P===""&&Ii){Ii();return}if(!hn&&(P===""||P==="\x1B_"||P==="\x1B")){Cr?.(P);return}if(hn){let Y=P.indexOf(Ma);if(Y===-1){zn+=P;return}zn+=P.slice(0,Y),hn=!1;let re=Buffer.from(zn,"binary").toString("utf-8").replace(/\r\n?/g,`
226
+ `);zn="";let ie=P.slice(Y+Ma.length);if(T)E==="input"&&!K&&Rn(re);else if(f===0&&!h){let we=De.feed({type:"paste",text:re});for(let Ve of we)Ve.type==="attachment-request"&&vi();let Ce=De.state(),Ze=ls(Ce.buffer,Os);Fs(Ze,Ce,Va).rendered!==wt?Xe():xr()}ie.length>0&&zt&&zt(Buffer.from(ie,"binary"));return}let U=P.indexOf(Ao);if(U===-1){zt?.(R);return}U>0&&zt?.(Buffer.from(P.slice(0,U),"binary")),P=P.slice(U+Ao.length),hn=!0,P.length>0&&xi(Buffer.from(P,"binary"))};return Xe(),await new Promise(R=>{let P=null,U=!1,Y=null,re=!1,ie=Ds,we=F=>{ie.push(F)},Ce=()=>{ie.pop(),gt||ie[ie.length-1]?.onResize()},Ze={push:we,pop:Ce},ht=()=>{let F={kind:"new",cwd:r},z=De.state().attachments;return z.length>0&&(F.attachments=[...z]),hs&&(F.agentId=hs),ms&&(F.model=ms),F},Ve=async()=>{Qs(),Se.clearCache(),we({onKey:()=>{},onResize:()=>{}});let z;try{z=await ii(n,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:",overlay:!0})}finally{Ce(),Mr()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=Sl(i,r),Ct()),gt||Xe()},Ks=async()=>{let F=e.availableAgents;if(!F||F.length===0)return;Qs(),Se.clearCache(),we({onKey:()=>{},onResize:()=>{}});let ue;try{ue=await Ua(n,F,hs,{title:"Switch agent",intro:"Agent used when the composer creates a new session:",overlay:!0})}finally{Ce(),Mr()}if(ue.kind==="select"){hs=ue.agentId;let J=e.config.defaultModels;if(ms=J?J[ue.agentId]:void 0,ue.persist)try{await $i(ue.agentId)}catch{}}gt||Xe()};vs=()=>{$=new _s({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,bt=0,O=null,K=!1,E="input",T=!1,Ce()};let Bt=(F,z,ue)=>{Js(),ie[ie.length-1]?.onKey(F,z,ue)},Ss=()=>{gt||ie[ie.length-1]?.onResize()};Cr=F=>{gt||ie[ie.length-1]?.onKey(F,null,{})};let ks=!1,ut=()=>{if(ks)return;ks=!0,ie.length=0,P&&(clearInterval(P),P=null),Y&&(Y.abort(),Y=null,U=!1),n.off("key",Bt),n.off("mouse",Pr),n.off("resize",Ss),process.stdout.write(Ps),process.stdout.write($a);let F=n;F.stdin&&zt&&(F.stdin.removeListener("data",xi),F.stdin.on("data",zt),zt=null),hn=!1,zn="",n.grabInput(!1),oe({src:"grab",site:"picker.detachInput",on:!1})},vt=()=>{gt||(gt=!0,ut(),n.hideCursor(!1),n.moveTo(1,qn()+1),n(`
227
+ `))},mn=()=>{if(gt||ie.length>1||S!=="normal"||h||re)return;U&&Y&&(Y.abort(),Y=null,U=!1);let F=f>0?a[f-1]?.sessionId:void 0;U=!0;let z=new AbortController;Y=z,en(F,{silent:!0,signal:z.signal}).finally(()=>{Y===z&&(Y=null),U=!1})},Js=()=>{gt||(P&&clearInterval(P),P=setInterval(mn,3e3))},Nt=()=>(ut(),vl("",{write(z){fe=z,pn()},finalize(){fe=null,vt()}})),En=()=>(vt(),R({kind:In?"exit":"abort"}),!0),gn=()=>{let F=d.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
228
228
  `);return`${f}:${p}:${Z??""}
229
- ${F}`},en=async(F,z={})=>{try{let ue=z.silent?gn():"",J=u,de=await ss(e.target,{includeNonInteractive:!0,signal:z.signal}),ce=F??(f>0?a[f-1]?.sessionId:void 0);if(i=vl(de,r),Ct(),ce!==void 0){let Te=a.findIndex(He=>He.sessionId===ce);Te>=0?f=Te+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An(),z.silent&&gn()===ue)return;u===J?Cl():Xe()}catch(ue){if(z.silent)return;Z=`refresh failed: ${ue.message}`,Xe()}},xr=async F=>{if(!x)return;let z=x;S="busy",$e();try{await yy(e.target,z.sessionId,F),S="normal",x=null,X=null,await en(z.sessionId)}catch(ue){S="normal",x=null,X=null,Z=`rename failed: ${ue.message}`,$e()}},Ii=async F=>{try{await by(e.target,F.sessionId),Z="title regen queued (press r to refresh)",$e()}catch(z){Z=`regen failed: ${z.message}`,$e()}},Ar=async F=>{let ue=(F.priority&&F.priority>0?F.priority:0)>0?null:1,J=ue??0;for(let ce of i)ce.sessionId===F.sessionId&&(ce.priority=J>0?J:void 0);let de=F.sessionId;i=vl(i,r),Ct(),us(de),Xe(),Z=J>0?"priority: high":"priority: normal",$e();try{await wy(e.target,F.sessionId,ue)}catch(ce){Z=`priority failed: ${ce.message}`,$e()}},Ks=async()=>{if(re)return;re=!0;let F=f>0?a[f-1]?.sessionId:void 0;Z="syncing agents\u2026",$e();try{let{synced:z,skipped:ue,agents:J}=await gy(e.target);await en(F),Z=`synced ${z} new (${ue} known) from ${J} agent${J===1?"":"s"}`,$e()}catch(z){Z=`sync failed: ${z.message}`,$e()}finally{re=!1}},Cr=async F=>{if(!x)return;let z=x;S="busy",$e();try{F==="kill"?await rs(e.target,z.sessionId):await Sy(e.target,z.sessionId),S="normal",x=null,z.sessionId===e.currentSessionId&&(In=!0);let ue;if(F==="kill")ue=z.sessionId;else{let J=a.findIndex(de=>de.sessionId===z.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await en(ue)}catch(ue){S="normal",x=null,Z=`${F} failed: ${ue.message}`,$e()}},it=(F,z)=>{F===0!=(z===0)&&(Wt(),z===0?(n.hideCursor(!1),fn()):n.hideCursor())},st=F=>{let z=Math.min(u-1,Math.max(0,f+F));if(z===f)return;let ue=f;f=z,An(),Oe(()=>{Xt(),it(ue,f)})},Pn=()=>Z===null?!1:(Z=null,$e(),!0),Kn=()=>{ms(),we({onKey:F=>{if(F==="CTRL_C"){vt(),R({kind:"abort"});return}Ce()},onResize:()=>ms()})},Js=F=>{let z=null,ue=null,J=!0,de=()=>{Oe(()=>{if(n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(` Session info \u2014 ${ft(F.sessionId)}`)(`
229
+ ${F}`},en=async(F,z={})=>{try{let ue=z.silent?gn():"",J=u,de=await is(e.target,{includeNonInteractive:!0,signal:z.signal}),ce=F??(f>0?a[f-1]?.sessionId:void 0);if(i=Sl(de,r),Ct(),ce!==void 0){let Te=a.findIndex(He=>He.sessionId===ce);Te>=0?f=Te+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+je>a.length&&(p=Math.max(0,a.length-je)),An(),z.silent&&gn()===ue)return;u===J?Rl():Xe()}catch(ue){if(z.silent)return;Z=`refresh failed: ${ue.message}`,Xe()}},Rr=async F=>{if(!x)return;let z=x;S="busy",$e();try{await Sy(e.target,z.sessionId,F),S="normal",x=null,X=null,await en(z.sessionId)}catch(ue){S="normal",x=null,X=null,Z=`rename failed: ${ue.message}`,$e()}},Ai=async F=>{try{await Iy(e.target,F.sessionId),Z="title regen queued (press r to refresh)",$e()}catch(z){Z=`regen failed: ${z.message}`,$e()}},Tr=async F=>{let ue=(F.priority&&F.priority>0?F.priority:0)>0?null:1,J=ue??0;for(let ce of i)ce.sessionId===F.sessionId&&(ce.priority=J>0?J:void 0);let de=F.sessionId;i=Sl(i,r),Ct(),ps(de),Xe(),Z=J>0?"priority: high":"priority: normal",$e();try{await ky(e.target,F.sessionId,ue)}catch(ce){Z=`priority failed: ${ce.message}`,$e()}},Ys=async()=>{if(re)return;re=!0;let F=f>0?a[f-1]?.sessionId:void 0;Z="syncing agents\u2026",$e();try{let{synced:z,skipped:ue,agents:J}=await vy(e.target);await en(F),Z=`synced ${z} new (${ue} known) from ${J} agent${J===1?"":"s"}`,$e()}catch(z){Z=`sync failed: ${z.message}`,$e()}finally{re=!1}},Er=async F=>{if(!x)return;let z=x;S="busy",$e();try{F==="kill"?await os(e.target,z.sessionId):await Ay(e.target,z.sessionId),S="normal",x=null,z.sessionId===e.currentSessionId&&(In=!0);let ue;if(F==="kill")ue=z.sessionId;else{let J=a.findIndex(de=>de.sessionId===z.sessionId);J>=0&&(ue=a[J+1]?.sessionId??a[J-1]?.sessionId)}await en(ue)}catch(ue){S="normal",x=null,Z=`${F} failed: ${ue.message}`,$e()}},it=(F,z)=>{F===0!=(z===0)&&(Wt(),z===0?(n.hideCursor(!1),fn()):n.hideCursor())},st=F=>{let z=Math.min(u-1,Math.max(0,f+F));if(z===f)return;let ue=f;f=z,An(),Oe(()=>{Xt(),it(ue,f)})},Pn=()=>Z===null?!1:(Z=null,$e(),!0),Jn=()=>{ys(),we({onKey:F=>{if(F==="CTRL_C"){vt(),R({kind:"abort"});return}Ce()},onResize:()=>ys()})},Vs=F=>{let z=null,ue=null,J=!0,de=()=>{Oe(()=>{if(n.hideCursor(),Se.clearCache(),n.moveTo(1,1).eraseDisplayBelow(),n.brightWhite.bold.noFormat(` Session info \u2014 ${ft(F.sessionId)}`)(`
230
230
 
231
231
  `),J)n.dim.noFormat(" loading\u2026")(`
232
232
  `);else if(ue!==null)n.brightRed.noFormat(` ${ue}`)(`
233
233
  `);else if(z!==null)for(let He of z)n.noFormat(` ${He}`)(`
234
234
  `);n(`
235
235
  `),n.dim.noFormat(" Esc / ^C to return")(`
236
- `)})};de();let ce=new AbortController,Te={onKey:He=>{if(He==="ESCAPE"||He==="CTRL_C"){ce.abort(),Ce();return}},onResize:()=>de()};we(Te),(async()=>{try{let He=await ln(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(F.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!He.ok)throw new Error(`daemon returned HTTP ${He.status}`);let We=await He.json(),ot=On(We),tn=Cf(ot,F.status);z=Oc(tn,!1).replace(/\n$/,"").split(`
237
- `)}catch(He){if(ce.signal.aborted)return;ue=`failed to load info: ${He.message}`}finally{J=!1,!gt&&ie[ie.length-1]===Te&&de()}})()},Rl=()=>{if(a.length===0){Z="no sessions to search",$e();return}$=new Ps({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,bt=0,O=null,K=!1,E="input",T=!0,yr(),Cn(),we({onKey:(z,ue,J)=>{if(E==="input"){if(K)return;if(z==="ESCAPE"||z==="CTRL_C"){ws();return}if(z==="ENTER"||z==="KP_ENTER"){if(Us().trim().length===0)return;Tn();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&N.length>0){E="results",D=0,B=0,Oe(()=>{hi(),ys(0,!0),yi(),n.hideCursor()});return}let de=$.state(),ce=[...de.buffer],Te=de.row,He=de.col,We=null;if(z==="")We={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")We={type:"key",name:"alt-underscore"};else if(J?.isCharacter)We={type:"char",ch:z};else{let ze=pl(z);ze!==null&&(We={type:"key",name:ze})}if(We===null){n.moveTo(lt(),wr());return}$.feed(We);let ot=$.state();if(ce.length===ot.buffer.length&&ce.every((ze,Ue)=>ze===ot.buffer[Ue])&&Te===ot.row&&He===ot.col){n.moveTo(lt(),wr());return}let Jn=me;yr(),me!==Jn?Cn():mi();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){ws();return}if(z==="CTRL_F"){E="input",sd(),yi(),hi();return}if(z==="ENTER"||z==="KP_ENTER"){let ce=N[D];if(!ce)return;let Te=a.find(We=>We.sessionId===ce.sessionId);if(!!Te?.importedFromMachine&&!Te.upstreamSessionId){vt();let We={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(We.agentId=Te.agentId),R(We);return}(async()=>{let We=await Vb(n,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},Ze);if(We==="cancel"){vt(),R({kind:"abort"});return}if(We==="back")return;vt();let ot={kind:"attach",sessionId:ce.sessionId,readonly:We==="view"};Te?.agentId!==void 0&&(ot.agentId=Te.agentId),R(ot)})();return}if(J?.isCharacter&&(z==="n"||z==="N")){let ce=N[D];if(!ce||ce.snippets.length<=1)return;B=(B+1)%ce.snippets.length,ys(D,!0);return}if(J?.isCharacter&&(z==="p"||z==="P")){let ce=N[D];if(!ce||ce.snippets.length<=1)return;B=(B-1+ce.snippets.length)%ce.snippets.length,ys(D,!0);return}let de=ce=>{if(ce<0&&D===0){E="input",Oe(()=>{ys(0,!1),yi(),hi()});return}let Te=Math.min(N.length-1,Math.max(0,D+ce));if(Te===D)return;let He=D,We=bt;D=Te,B=0,td(),bt!==We?sd():(Oe(()=>{ys(He,!1),ys(D,!0)}),yi())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":de(-1);return;case"DOWN":case"TAB":case"CTRL_N":de(1);return;case"PAGE_UP":de(-gs());return;case"PAGE_DOWN":de(gs());return;case"HOME":de(-D);return;case"END":de(N.length);return}return}},onResize:()=>Cn()})},Tl=(F,z,ue)=>{if(S!=="busy"){if(F==="CTRL_O"){Ve();return}if(F==="CTRL_L"){Ho();return}if(S==="rename"&&X){if(F==="ENTER"||F==="KP_ENTER"){let J=X.text.trim();if(J.length===0){S="normal",x=null,X=null,$e();return}xr(J);return}if(F==="ESCAPE"||F==="CTRL_C"){S="normal",x=null,X=null,$e();return}if(X.handleKey(F,ue?.isCharacter===!0)){$e();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(F==="y"||F==="Y")){Cr(S==="confirm-kill"?"kill":"delete");return}if(F==="ESCAPE"||F==="CTRL_C"||F==="ENTER"||F==="KP_ENTER"||ue?.isCharacter&&(F==="n"||F==="N")){S="normal",x=null,$e();return}return}if(Pn(),Ke&&(Ke=!1,f=0,Oe(()=>{Wt(),Xt()})),F==="CTRL_F"&&f!==0){Rl();return}if(f===0&&!h){if(F==="ESCAPE"){En();return}if(F==="ENTER"||F==="KP_ENTER"){let Ue=De.expandedText(),St=ht();Ue.trim().length>0&&(St.prompt=Ue),St.installStatus=Nt(),R(St);return}if(F==="UP"&&b){let Ue=Date.now(),St=Ue-v;if(v=Ue,St<y){fn();return}b=!1}if(F==="DOWN"){let Ue=De.state(),St=Ue.historyIndex!==-1||Ue.queueIndex!==-1,mt=un.length===0||Os===un.length-1;if(!St&&mt&&a.length>0){st(1);return}}if(F==="PAGE_DOWN"&&(un.length===0||Os===un.length-1)&&a.length>0){st(1);return}if(F==="CTRL_P"){a.length>0&&st(1);return}if(b=!1,F==="TAB"){let Ue=De.state(),St=Ue.buffer[Ue.row]??"",mt=yl(St,Ue.col);if(mt!==null){let Et=wl(mt.token,r);if(Et!==null){if(Et.replacement!==mt.token&&(De.replaceRangeOnCurrentLine(mt.start,Ue.col,Et.replacement),Sr()),Et.candidates.length>1){let Vs=Et.candidates.join(" ");Q=`${Et.candidates.length} matches: ${Vs}`,pn()}else js();fn();return}}}js();let J=De.state(),de=[...J.buffer],ce=J.row,Te=J.col,He=null;if(F==="")He={type:"key",name:"ctrl-underscore"};else if(F==="\x1B_"||F==="\x1B")He={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)He={type:"char",ch:F};else{let Ue=pl(F);Ue!==null&&(He={type:"key",name:Ue})}if(He===null){fn();return}let We=De.feed(He),ot=De.state(),tn=de.length===ot.buffer.length&&de.every((Ue,St)=>Ue===ot.buffer[St])&&ce===ot.row&&Te===ot.col;if(We.some(Ue=>Ue.type==="exit")){En();return}for(let Ue of We)Ue.type==="attachment-request"&&wi();if(tn){fn();return}let Jn=ds(ot.buffer,$s);if(_s(Jn,ot,Ya).rendered!==wt){Xe();return}Sr();return}if(!h&&ue?.isCharacter&&F==="?"){Kn();return}if(h){if(ue?.isCharacter){m+=F,Ct(),Xe();return}if(F==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Ct(),Xe()):(h=!1,Ct(),Xe());return}if(F==="ESCAPE"||F==="CTRL_C"){h=!1,m="",Ct(),Xe();return}}if(ue?.isCharacter){if(F==="/"){h=!0,m="",Ct(),Xe();return}if(F==="n"||F==="N"){st(1);return}if(F==="p"||F==="P"){st(-1);return}if(F==="c"||F==="C"){let J=f>0?a[f-1]:void 0,de=ht();J?.cwd&&(de.cwd=J.cwd),de.installStatus=Nt(),R(de);return}if(F==="q"||F==="Q"){En();return}if(F==="o"||F==="O"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Ct(),us(J),Xe();return}if(F==="h"||F==="H"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=sv(s.filters.hostFilter,i),Ct(),us(J),Xe();return}if(F==="i"&&f>0){let J=a[f-1];if(!J)return;Js(J);return}if(F==="I"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Ct(),us(J),Xe();return}if(F==="r"||F==="R"){let J=f>0?a[f-1]?.sessionId:void 0;en(J);return}if(F==="s"||F==="S"){Ks();return}if((F==="v"||F==="V")&&f>0){let J=a[f-1];if(!J)return;let de={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Nt(),R(de);return}if((F==="f"||F==="F")&&f>0){let J=a[f-1];if(!J)return;vt();let de={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(de.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(de.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(de.sourceUpstreamSessionId=J.upstreamSessionId),R(de);return}if((F==="k"||F==="K")&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",$e();return}if(F==="t"&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},X=new Fo(J.title??""),S="rename",$e();return}if(F==="T"&&f>0){let J=a[f-1];if(!J)return;Ii({sessionId:J.sessionId});return}if(F==="*"&&f>0){let J=a[f-1];if(!J)return;Ar(J);return}if((F==="d"||F==="D")&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",$e();return}Ke=!1,f=0,De.feed({type:"char",ch:F}),Xe();return}switch(F){case"UP":case"SHIFT_TAB":case"CTRL_P":F==="UP"&&(f===1&&(b=!0),v=Date.now()),st(-1);return;case"DOWN":case"TAB":case"CTRL_N":st(1);return;case"PAGE_UP":st(-je);return;case"PAGE_DOWN":st(je);return;case"HOME":st(1-f);return;case"END":st(u);return;case"RIGHT":if(Ke||f===0)break;case"ENTER":case"KP_ENTER":{if(Ke){let ce=De.expandedText(),Te=ht();ce.trim().length>0&&(Te.prompt=ce),Te.installStatus=Nt(),R(Te);return}if(f===0){let ce=ht();ce.installStatus=Nt(),R(ce);return}let J=a[f-1];if(!J){vt(),R({kind:"abort"});return}let de={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Nt(),R(de);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":En();return}}};we({onKey:(F,z,ue)=>Tl(F,z,ue),onResize:()=>{gt||Xe()}});let Rr=(F,z)=>{if(gt||ie.length!==1||S!=="normal")return;let ue=F==="MOUSE_MOTION",J=F==="MOUSE_LEFT_BUTTON_PRESSED",de=F==="MOUSE_LEFT_BUTTON_RELEASED",ce=F==="MOUSE_WHEEL_UP",Te=F==="MOUSE_WHEEL_DOWN",He=qe&&Date.now()-rd<id,We=!qe||He;if(J){kr={x:z?.x??-1,y:z?.y??-1},bi=We;return}if(ue&&We)return;let ot=de&&kr!==null&&z?.x===kr.x&&z?.y===kr.y,tn=ot&&!bi,Jn=ot&&bi;if(de&&(kr=null,bi=!1,!ot))return;if(ce||Te){if(a.length===0)return;let Le=ce?-3:3,Pt=Math.max(0,a.length-je),Qs=Math.min(Pt,Math.max(0,p+Le));if(Qs===p)return;if(p=Qs,f>0){let Ai=f-1;Ai<p?f=p+1:Ai>=p+je&&(f=p+je)}Xt();return}if(!ue&&!tn)return;let ze=z?.y;if(typeof ze!="number")return;{let Le=z?.x,Pt=zn!==null&&ze===jn()&&typeof Le=="number"&&Le>=zn.start&&Le<=zn.end,Qs=Zt!==null&&ze===jn()&&typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end;(Pt!==vi||Qs!==qs)&&(vi=Pt,qs=Qs,$e(),f===0?(fn(),n.hideCursor(!1)):n.hideCursor(!0))}if(tn&&zn!==null&&ze===jn()){let Le=z?.x;if(typeof Le=="number"&&Le>=zn.start&&Le<=zn.end){En();return}}if(tn&&Zt!==null&&ze===jn()){let Le=z?.x;if(typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end){let Pt=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=sv(s.filters.hostFilter,i),Ct(),us(Pt),Xe();return}}if(ze>=xn&&ze<=Un()){let Le=null;if(ze===xn){let Pt=z?.x;typeof Pt=="number"&&(hs!==null&&Pt>=hs.start&&Pt<=hs.end?Le="agent":Ns!==null&&Pt>=Ns.start&&Pt<=Ns.end&&(Le="cwd"))}if(Le!==Lt&&(Lt=Le,Wt()),tn&&ze===xn){if(Lt==="agent"){Ws();return}if(Lt==="cwd"){Ve();return}}if((tn||Jn)&&f!==0){Ke=!1;let Pt=f;f=0,Oe(()=>{Xt(),it(Pt,f)});return}ue&&!Ke&&f!==0&&(Ke=!0,Oe(()=>{Wt(),Xt()}));return}Lt!==null&&(Lt=null,Wt()),Ke&&(Ke=!1,Oe(()=>{Wt(),Xt()}));let St=Qt()+1,mt=St+je-1;if(ze<St||ze>mt)return;let Et=p+(ze-St);if(Et<0||Et>=a.length)return;let Vs=a[Et];if(!Vs)return;let Ss=Et+1;if(ue&&f===0)return;let od=f===0,El=f===Ss;if(Jn&&f!==Ss){let Le=f;f=Ss,An(),Oe(()=>{Xt(),it(Le,f)});return}if(Jn)return;if(f!==Ss){let Le=f;f=Ss,An(),Oe(()=>{Xt(),it(Le,f)})}if(!tn||od||!El)return;let xi={kind:"attach",sessionId:Vs.sessionId};Vs.agentId!==void 0&&(xi.agentId=Vs.agentId),xi.installStatus=Nt(),R(xi)},Tr=()=>{n.grabInput({mouse:"motion"}),oe({src:"grab",site:"picker.installGrab",on:!0});let F=n;F.stdin&&typeof F.onStdin=="function"&&(zt=F.onStdin,F.stdin.removeListener("data",F.onStdin),F.stdin.on("data",ki),process.stdout.write(Wc),process.stdout.write(Jc)),n.on("key",Bt),n.on("mouse",Rr),n.on("resize",bs)},Ys=()=>{process.stdout.write(Ts),process.stdout.write(_a);let F=n;F.stdin&&zt&&(F.stdin.removeListener("data",ki),F.stdin.on("data",zt),zt=null),hn=!1,Wn="",n.off("key",Bt),n.off("mouse",Rr),n.off("resize",bs),n.grabInput(!1),oe({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Tr(),process.platform!=="win32"){let F=!1,z=()=>{F&&(F=!1,n.fullscreen(!0),t(),n.hideCursor(),Tr(),gt||Ho())};Si=()=>{F||gt||(F=!0,Ys(),n.fullscreen(!1),process.stdout.write(`${Ma}${zc}
238
- `),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(mn,3e3)})}function NT(n,e){let t="Create new session in ",s=Math.max(1,e-t.length);return t+Ca(at(n),s)}function vl(n,e){let t=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=t(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...n].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=t(i)-t(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function DT(n,e){return e==="__all"?n:e==="__local"?n.filter(t=>!t.importedFromMachine||!!t.upstreamSessionId):n.filter(t=>t.importedFromMachine===e&&!t.upstreamSessionId)}function sv(n,e){let t=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&t.add(i.importedFromMachine);let s=["__local",...[...t].sort(),"__all"],r=s.indexOf(n);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function HT(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),s=[ft(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,at(n.cwd)];for(let r of s)if(r.toLowerCase().includes(t))return!0;return!1}var kp,Ya,OT,nv,LT,BT,rv=V(()=>{"use strict";Pc();ve();Xn();Qe();Aa();Qf();Hd();ol();np();gp();yp();bp();wp();vp();Xr();sp();rp();$a();Hr();Rf();Or();Sp();kp=2,Ya=4,OT=4,nv=4,LT=20,BT=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import UT from"wrap-ansi";async function iv(n,e,t,s){Ln();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=t.split(`
239
- `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(n),l=Es(n),u=Math.min(jT,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>UT(T,f,{hard:!0,trim:!1}).split(`
240
- `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,b=y.length+(m?1:0)+4,v=Bn(n,{contentHeight:b,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,x=0;n.moveTo(v.contentX,v.contentY+x),n.brightWhite.bold.noFormat(Ge(` ${i}`,S)),x+=2;for(let T of y)n.moveTo(v.contentX,v.contentY+x),n.brightRed.noFormat(Ge(` ${T}`,S)),x++;return m&&(n.moveTo(v.contentX,v.contentY+x),n.dim.noFormat(Ge(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),x++),x++,n.moveTo(v.contentX,v.contentY+x),n.dim.noFormat(Ge(` ${a}`,S)),v};return os({term:n,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var jT,ov=V(()=>{"use strict";Xr();jT=100});import{spawn as qT}from"child_process";function WT(n,e){let t="";for(let s=0;s<n.length;s++){let r=n[s];if(r!=="%"||s===n.length-1){t+=r;continue}switch(n[s+1]){case"%":t+="%",s++;break;case"s":t+=e.sessionId,s++;break;case"c":t+=e.cwd,s++;break;case"a":t+=e.agentId,s++;break;case"u":t+=e.baseUrl,s++;break;case"t":t+=e.tokenFile,s++;break;default:t+=r;break}}return t}function zT(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function KT(n,e){let t=zT(n.command);if(t.length===0)return null;let s=t.map(a=>et(WT(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function JT(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(s,r)=>{if(e.truncated)return;let i=n-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>t(s,"stdout"),onStderr:s=>t(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function av(n,e,t){let s=KT(n,e);if(s===null){t.notify("hotkey: empty command");return}let r=JT(t.maxOutputBytes??YT),i=t.spawnFn??qT,o;try{o=i(s.program,s.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{t.emitLines(r.onExit(a,c))})}var YT,dv=V(()=>{"use strict";Qe();YT=16*1024});import{spawn as VT}from"child_process";function cv(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${QT}1337;SetUserVar=${n}=${t}${GT}`)}function lv(n){if(process.env.TMUX_PANE)try{let e=VT("tmux",n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function Ap(n,e){cv(n,e);let t=process.env.TMUX_PANE;t&&lv(["set-option","-pt",t,`@${n}`,e])}function uv(n){cv(n,"");let e=process.env.TMUX_PANE;e&&lv(["set-option","-put",e,`@${n}`])}var QT,GT,fv=V(()=>{"use strict";QT="\x1B]",GT="\x07"});function pv(n){let e={};if(!n||typeof n!="object")return e;let t=n;typeof t.historyPolicy=="string"&&(e.appliedPolicy=t.historyPolicy),typeof t.clientId=="string"&&t.clientId.length>0&&(e.clientId=t.clientId);let s=t._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 hv(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function mv(n){return n.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:n.pendingTurns===0?1:0,banner:"busy",busySince:n.daemonTurnStartedAt}:{pendingTurnsDelta:n.pendingTurns>0?-n.pendingTurns:0,banner:"ready"}}var gv=V(()=>{"use strict"});import{readFileSync as XT}from"fs";import{nanoid as yv}from"nanoid";import ZT from"terminal-kit";import Cp from"fs/promises";import ri from"path";function eE(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function tE(n){let e=Sl(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function nE(n){let e=new Map,t=[];for(let s of n){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),t.push(r))}return t.map(s=>e.get(s))}function Sl(n){if(n.options&&n.options.length>0){let e=n.options.filter(t=>t!==n.defaultAnswer);return n.options.includes(n.defaultAnswer)?[n.defaultAnswer,...e]:[n.defaultAnswer,...n.options]}return[n.defaultAnswer]}function sE(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function rE(n,e,t,s,r=60){let i=n.map((o,a)=>{let c=Sl(o.representative),d=e[a]??0,l=t[a]?Tp:c[d]??c[0]??"";return{label:sE(o.representative.question,r),value:l}});return{title:`Open questions (${n.length})`,options:i,selectedIndex:Math.max(0,Math.min(n.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function iE(n,e,t){return n===Tp?{type:"dismiss",method:pb,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:fb,params:{sessionId:t,questionId:e.id,answer:n}}}function oE(n,e,t,s,r){let i=[];for(let o=0;o<n.length;o++){let a=n[o];if(!a||!t[o])continue;let c=s[o]?Tp:Sl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=iE(c,l,r);u!==null&&i.push(u)}}return i}function aE(n,e,t,s,r,i,o,a){if(!e||t===null||t.length===0)return{type:"noop"};if(n.type==="char"){if(n.ch==="d"||n.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(n.ch)){let d=parseInt(n.ch,10)-1;if(d<t.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(n.type!=="key")return{type:"noop"};let c=d=>{let l=t[o];if(!l)return{type:"noop"};let u=Sl(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(n.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(t.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:oE(t,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function wv(n){if(!Array.isArray(n))return;let e=ts({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function Rp(n){switch(n.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function lE(n,e){e.has(n)?e.delete(n):e.add(n)}function uE(){if(bv)return;bv=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{oe({src:"uncaughtException",stack:n(e)}),ti(),process.stderr.write(`
236
+ `)})};de();let ce=new AbortController,Te={onKey:He=>{if(He==="ESCAPE"||He==="CTRL_C"){ce.abort(),Ce();return}},onResize:()=>de()};we(Te),(async()=>{try{let He=await ln(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(F.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ce.signal});if(!He.ok)throw new Error(`daemon returned HTTP ${He.status}`);let We=await He.json(),ot=On(We),tn=Rf(ot,F.status);z=Lc(tn,!1).replace(/\n$/,"").split(`
237
+ `)}catch(He){if(ce.signal.aborted)return;ue=`failed to load info: ${He.message}`}finally{J=!1,!gt&&ie[ie.length-1]===Te&&de()}})()},Tl=()=>{if(a.length===0){Z="no sessions to search",$e();return}$=new _s({history:[],collapsePastes:!1}),N=[],M=!1,D=0,B=0,bt=0,O=null,K=!1,E="input",T=!0,vr(),Cn(),we({onKey:(z,ue,J)=>{if(E==="input"){if(K)return;if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="ENTER"||z==="KP_ENTER"){if(qs().trim().length===0)return;Tn();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&N.length>0){E="results",D=0,B=0,Oe(()=>{gi(),bs(0,!0),bi(),n.hideCursor()});return}let de=$.state(),ce=[...de.buffer],Te=de.row,He=de.col,We=null;if(z==="")We={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")We={type:"key",name:"alt-underscore"};else if(J?.isCharacter)We={type:"char",ch:z};else{let ze=hl(z);ze!==null&&(We={type:"key",name:ze})}if(We===null){n.moveTo(lt(),Sr());return}$.feed(We);let ot=$.state();if(ce.length===ot.buffer.length&&ce.every((ze,Ue)=>ze===ot.buffer[Ue])&&Te===ot.row&&He===ot.col){n.moveTo(lt(),Sr());return}let Yn=me;vr(),me!==Yn?Cn():yi();return}if(E==="results"){if(z==="ESCAPE"||z==="CTRL_C"){vs();return}if(z==="CTRL_F"){E="input",rd(),bi(),gi();return}if(z==="ENTER"||z==="KP_ENTER"){let ce=N[D];if(!ce)return;let Te=a.find(We=>We.sessionId===ce.sessionId);if(!!Te?.importedFromMachine&&!Te.upstreamSessionId){vt();let We={kind:"attach",sessionId:ce.sessionId};Te.agentId!==void 0&&(We.agentId=Te.agentId),R(We);return}(async()=>{let We=await Zb(n,{sessionId:ce.sessionId,title:ce.title,cwd:ce.cwd},Ze);if(We==="cancel"){vt(),R({kind:"abort"});return}if(We==="back")return;vt();let ot={kind:"attach",sessionId:ce.sessionId,readonly:We==="view"};Te?.agentId!==void 0&&(ot.agentId=Te.agentId),R(ot)})();return}if(J?.isCharacter&&(z==="n"||z==="N")){let ce=N[D];if(!ce||ce.snippets.length<=1)return;B=(B+1)%ce.snippets.length,bs(D,!0);return}if(J?.isCharacter&&(z==="p"||z==="P")){let ce=N[D];if(!ce||ce.snippets.length<=1)return;B=(B-1+ce.snippets.length)%ce.snippets.length,bs(D,!0);return}let de=ce=>{if(ce<0&&D===0){E="input",Oe(()=>{bs(0,!1),bi(),gi()});return}let Te=Math.min(N.length-1,Math.max(0,D+ce));if(Te===D)return;let He=D,We=bt;D=Te,B=0,nd(),bt!==We?rd():(Oe(()=>{bs(He,!1),bs(D,!0)}),bi())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":de(-1);return;case"DOWN":case"TAB":case"CTRL_N":de(1);return;case"PAGE_UP":de(-ws());return;case"PAGE_DOWN":de(ws());return;case"HOME":de(-D);return;case"END":de(N.length);return}return}},onResize:()=>Cn()})},El=(F,z,ue)=>{if(S!=="busy"){if(F==="CTRL_O"){Ve();return}if(F==="CTRL_L"){Uo();return}if(S==="rename"&&X){if(F==="ENTER"||F==="KP_ENTER"){let J=X.text.trim();if(J.length===0){S="normal",x=null,X=null,$e();return}Rr(J);return}if(F==="ESCAPE"||F==="CTRL_C"){S="normal",x=null,X=null,$e();return}if(X.handleKey(F,ue?.isCharacter===!0)){$e();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ue?.isCharacter&&(F==="y"||F==="Y")){Er(S==="confirm-kill"?"kill":"delete");return}if(F==="ESCAPE"||F==="CTRL_C"||F==="ENTER"||F==="KP_ENTER"||ue?.isCharacter&&(F==="n"||F==="N")){S="normal",x=null,$e();return}return}if(Pn(),Ke&&(Ke=!1,f=0,Oe(()=>{Wt(),Xt()})),F==="CTRL_F"&&f!==0){Tl();return}if(f===0&&!h){if(F==="ESCAPE"){En();return}if(F==="ENTER"||F==="KP_ENTER"){let Ue=De.expandedText(),St=ht();Ue.trim().length>0&&(St.prompt=Ue),St.installStatus=Nt(),R(St);return}if(F==="UP"&&w){let Ue=Date.now(),St=Ue-v;if(v=Ue,St<y){fn();return}w=!1}if(F==="DOWN"){let Ue=De.state(),St=Ue.historyIndex!==-1||Ue.queueIndex!==-1,mt=un.length===0||Bs===un.length-1;if(!St&&mt&&a.length>0){st(1);return}}if(F==="PAGE_DOWN"&&(un.length===0||Bs===un.length-1)&&a.length>0){st(1);return}if(F==="CTRL_P"){a.length>0&&st(1);return}if(w=!1,F==="TAB"){let Ue=De.state(),St=Ue.buffer[Ue.row]??"",mt=wl(St,Ue.col);if(mt!==null){let Et=bl(mt.token,r);if(Et!==null){if(Et.replacement!==mt.token&&(De.replaceRangeOnCurrentLine(mt.start,Ue.col,Et.replacement),xr()),Et.candidates.length>1){let Gs=Et.candidates.join(" ");Q=`${Et.candidates.length} matches: ${Gs}`,pn()}else Ws();fn();return}}}Ws();let J=De.state(),de=[...J.buffer],ce=J.row,Te=J.col,He=null;if(F==="")He={type:"key",name:"ctrl-underscore"};else if(F==="\x1B_"||F==="\x1B")He={type:"key",name:"alt-underscore"};else if(ue?.isCharacter)He={type:"char",ch:F};else{let Ue=hl(F);Ue!==null&&(He={type:"key",name:Ue})}if(He===null){fn();return}let We=De.feed(He),ot=De.state(),tn=de.length===ot.buffer.length&&de.every((Ue,St)=>Ue===ot.buffer[St])&&ce===ot.row&&Te===ot.col;if(We.some(Ue=>Ue.type==="exit")){En();return}for(let Ue of We)Ue.type==="attachment-request"&&vi();if(tn){fn();return}let Yn=ls(ot.buffer,Os);if(Fs(Yn,ot,Va).rendered!==wt){Xe();return}xr();return}if(!h&&ue?.isCharacter&&F==="?"){Jn();return}if(h){if(ue?.isCharacter){m+=F,Ct(),Xe();return}if(F==="BACKSPACE"){m.length>0?(m=m.slice(0,-1),Ct(),Xe()):(h=!1,Ct(),Xe());return}if(F==="ESCAPE"||F==="CTRL_C"){h=!1,m="",Ct(),Xe();return}}if(ue?.isCharacter){if(F==="/"){h=!0,m="",Ct(),Xe();return}if(F==="n"||F==="N"){st(1);return}if(F==="p"||F==="P"){st(-1);return}if(F==="c"||F==="C"){let J=f>0?a[f-1]:void 0,de=ht();J?.cwd&&(de.cwd=J.cwd),de.installStatus=Nt(),R(de);return}if(F==="q"||F==="Q"){En();return}if(F==="o"||F==="O"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,Ct(),ps(J),Xe();return}if(F==="h"||F==="H"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=av(s.filters.hostFilter,i),Ct(),ps(J),Xe();return}if(F==="i"&&f>0){let J=a[f-1];if(!J)return;Vs(J);return}if(F==="I"){let J=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,Ct(),ps(J),Xe();return}if(F==="r"||F==="R"){let J=f>0?a[f-1]?.sessionId:void 0;en(J);return}if(F==="s"||F==="S"){Ys();return}if((F==="v"||F==="V")&&f>0){let J=a[f-1];if(!J)return;let de={kind:"attach",sessionId:J.sessionId,readonly:!0};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Nt(),R(de);return}if((F==="f"||F==="F")&&f>0){let J=a[f-1];if(!J)return;vt();let de={kind:"fork",sourceSessionId:J.sessionId,sourceCwd:J.cwd};J.agentId!==void 0&&(de.sourceAgentId=J.agentId),J.importedFromMachine!==void 0&&(de.sourceImportedFromMachine=J.importedFromMachine),J.upstreamSessionId!==void 0&&(de.sourceUpstreamSessionId=J.upstreamSessionId),R(de);return}if((F==="k"||F==="K")&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-kill",$e();return}if(F==="t"&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},X=new Oo(J.title??""),S="rename",$e();return}if(F==="T"&&f>0){let J=a[f-1];if(!J)return;Ai({sessionId:J.sessionId});return}if(F==="*"&&f>0){let J=a[f-1];if(!J)return;Tr(J);return}if((F==="d"||F==="D")&&f>0){let J=a[f-1];if(!J)return;x={sessionId:J.sessionId,cwd:J.cwd,status:J.status},S="confirm-delete",$e();return}Ke=!1,f=0,De.feed({type:"char",ch:F}),Xe();return}switch(F){case"UP":case"SHIFT_TAB":case"CTRL_P":F==="UP"&&(f===1&&(w=!0),v=Date.now()),st(-1);return;case"DOWN":case"TAB":case"CTRL_N":st(1);return;case"PAGE_UP":st(-je);return;case"PAGE_DOWN":st(je);return;case"HOME":st(1-f);return;case"END":st(u);return;case"RIGHT":if(Ke||f===0)break;case"ENTER":case"KP_ENTER":{if(Ke){let ce=De.expandedText(),Te=ht();ce.trim().length>0&&(Te.prompt=ce),Te.installStatus=Nt(),R(Te);return}if(f===0){let ce=ht();ce.installStatus=Nt(),R(ce);return}let J=a[f-1];if(!J){vt(),R({kind:"abort"});return}let de={kind:"attach",sessionId:J.sessionId};J.agentId!==void 0&&(de.agentId=J.agentId),de.installStatus=Nt(),R(de);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":En();return}}};we({onKey:(F,z,ue)=>El(F,z,ue),onResize:()=>{gt||Xe()}});let Pr=(F,z)=>{if(gt||ie.length!==1||S!=="normal")return;let ue=F==="MOUSE_MOTION",J=F==="MOUSE_LEFT_BUTTON_PRESSED",de=F==="MOUSE_LEFT_BUTTON_RELEASED",ce=F==="MOUSE_WHEEL_UP",Te=F==="MOUSE_WHEEL_DOWN",He=qe&&Date.now()-id<od,We=!qe||He;if(J){Ar={x:z?.x??-1,y:z?.y??-1},Si=We;return}if(ue&&We)return;let ot=de&&Ar!==null&&z?.x===Ar.x&&z?.y===Ar.y,tn=ot&&!Si,Yn=ot&&Si;if(de&&(Ar=null,Si=!1,!ot))return;if(ce||Te){if(a.length===0)return;let Le=ce?-3:3,Pt=Math.max(0,a.length-je),Xs=Math.min(Pt,Math.max(0,p+Le));if(Xs===p)return;if(p=Xs,f>0){let Ri=f-1;Ri<p?f=p+1:Ri>=p+je&&(f=p+je)}Xt();return}if(!ue&&!tn)return;let ze=z?.y;if(typeof ze!="number")return;{let Le=z?.x,Pt=Kn!==null&&ze===qn()&&typeof Le=="number"&&Le>=Kn.start&&Le<=Kn.end,Xs=Zt!==null&&ze===qn()&&typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end;(Pt!==ki||Xs!==zs)&&(ki=Pt,zs=Xs,$e(),f===0?(fn(),n.hideCursor(!1)):n.hideCursor(!0))}if(tn&&Kn!==null&&ze===qn()){let Le=z?.x;if(typeof Le=="number"&&Le>=Kn.start&&Le<=Kn.end){En();return}}if(tn&&Zt!==null&&ze===qn()){let Le=z?.x;if(typeof Le=="number"&&Le>=Zt.start&&Le<=Zt.end){let Pt=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=av(s.filters.hostFilter,i),Ct(),ps(Pt),Xe();return}}if(ze>=xn&&ze<=jn()){let Le=null;if(ze===xn){let Pt=z?.x;typeof Pt=="number"&&(gs!==null&&Pt>=gs.start&&Pt<=gs.end?Le="agent":Hs!==null&&Pt>=Hs.start&&Pt<=Hs.end&&(Le="cwd"))}if(Le!==Lt&&(Lt=Le,Wt()),tn&&ze===xn){if(Lt==="agent"){Ks();return}if(Lt==="cwd"){Ve();return}}if((tn||Yn)&&f!==0){Ke=!1;let Pt=f;f=0,Oe(()=>{Xt(),it(Pt,f)});return}ue&&!Ke&&f!==0&&(Ke=!0,Oe(()=>{Wt(),Xt()}));return}Lt!==null&&(Lt=null,Wt()),Ke&&(Ke=!1,Oe(()=>{Wt(),Xt()}));let St=Qt()+1,mt=St+je-1;if(ze<St||ze>mt)return;let Et=p+(ze-St);if(Et<0||Et>=a.length)return;let Gs=a[Et];if(!Gs)return;let Is=Et+1;if(ue&&f===0)return;let ad=f===0,Pl=f===Is;if(Yn&&f!==Is){let Le=f;f=Is,An(),Oe(()=>{Xt(),it(Le,f)});return}if(Yn)return;if(f!==Is){let Le=f;f=Is,An(),Oe(()=>{Xt(),it(Le,f)})}if(!tn||ad||!Pl)return;let Ci={kind:"attach",sessionId:Gs.sessionId};Gs.agentId!==void 0&&(Ci.agentId=Gs.agentId),Ci.installStatus=Nt(),R(Ci)},Mr=()=>{n.grabInput({mouse:"motion"}),oe({src:"grab",site:"picker.installGrab",on:!0});let F=n;F.stdin&&typeof F.onStdin=="function"&&(zt=F.onStdin,F.stdin.removeListener("data",F.onStdin),F.stdin.on("data",xi),process.stdout.write(zc),process.stdout.write(Yc)),n.on("key",Bt),n.on("mouse",Pr),n.on("resize",Ss)},Qs=()=>{process.stdout.write(Ps),process.stdout.write($a);let F=n;F.stdin&&zt&&(F.stdin.removeListener("data",xi),F.stdin.on("data",zt),zt=null),hn=!1,zn="",n.off("key",Bt),n.off("mouse",Pr),n.off("resize",Ss),n.grabInput(!1),oe({src:"grab",site:"picker.uninstallGrab",on:!1}),n.hideCursor(!1)};if(Mr(),process.platform!=="win32"){let F=!1,z=()=>{F&&(F=!1,n.fullscreen(!0),t(),n.hideCursor(),Mr(),gt||Uo())};Ii=()=>{F||gt||(F=!0,Qs(),n.fullscreen(!1),process.stdout.write(`${_a}${Kc}
238
+ `),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}P=setInterval(mn,3e3)})}function qT(n,e){let t="Create new session in ",s=Math.max(1,e-t.length);return t+Ra(at(n),s)}function Sl(n,e){let t=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="warm",o=t(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...n].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=t(i)-t(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function WT(n,e){return e==="__all"?n:e==="__local"?n.filter(t=>!t.importedFromMachine||!!t.upstreamSessionId):n.filter(t=>t.importedFromMachine===e&&!t.upstreamSessionId)}function av(n,e){let t=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&t.add(i.importedFromMachine);let s=["__local",...[...t].sort(),"__all"],r=s.indexOf(n);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function zT(n,e){if(e.length===0)return!0;let t=e.toLowerCase(),s=[ft(n.sessionId),n.upstreamSessionId??"",n.agentId??"",n.title??"",n.cwd,at(n.cwd)];for(let r of s)if(r.toLowerCase().includes(t))return!0;return!1}var Ap,Va,HT,ov,UT,jT,dv=V(()=>{"use strict";Mc();ve();Zn();Qe();Ca();Gf();Ud();al();sp();bp();vp();kp();Sp();Ip();ti();rp();ip();Fa();qr();Tf();Nr();xp();Ap=2,Va=4,HT=4,ov=4,UT=20,jT=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],["typing in list","jumps focus back to composer with that key"],["mouse-hover composer","Enter from anywhere creates a new session"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected warm session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});import KT from"wrap-ansi";async function cv(n,e,t,s){Ln();let r=s?.canGoBack!==!1,i=e?`Couldn't start ${e}`:"Couldn't start session",o=t.split(`
239
+ `).map(d=>d.trimEnd()).filter(d=>d.length>0),a=r?"r retry \xB7 Esc back to picker \xB7 ^C cancel":"r retry \xB7 Esc / ^C exit",c=()=>{let d=Jt(n),l=Ms(n),u=Math.min(JT,Math.max(20,d-4)),f=Math.max(1,u-1),p=o.flatMap(T=>KT(T,f,{hard:!0,trim:!1}).split(`
240
+ `)),h=Math.max(1,l-4-4),m=p.length>h,y=m?p.slice(0,h-1):p,w=y.length+(m?1:0)+4,v=Bn(n,{contentHeight:w,contentWidth:u,title:"Agent failed to start"}),S=v.contentW,x=0;n.moveTo(v.contentX,v.contentY+x),n.brightWhite.bold.noFormat(Ge(` ${i}`,S)),x+=2;for(let T of y)n.moveTo(v.contentX,v.contentY+x),n.brightRed.noFormat(Ge(` ${T}`,S)),x++;return m&&(n.moveTo(v.contentX,v.contentY+x),n.dim.noFormat(Ge(" \u2026 (full details in ~/.hydra-acp/tui.log)",S)),x++),x++,n.moveTo(v.contentX,v.contentY+x),n.dim.noFormat(Ge(` ${a}`,S)),v};return ds({term:n,render:()=>{c()},onKey:(d,l,u,f)=>{if(d==="r"||d==="R"||d==="ENTER"||d==="KP_ENTER"){f("retry");return}if(d==="ESCAPE"){f(r?"back":"cancel");return}d==="CTRL_C"&&f("cancel")}})}var JT,lv=V(()=>{"use strict";ti();JT=100});import{spawn as YT}from"child_process";function VT(n,e){let t="";for(let s=0;s<n.length;s++){let r=n[s];if(r!=="%"||s===n.length-1){t+=r;continue}switch(n[s+1]){case"%":t+="%",s++;break;case"s":t+=e.sessionId,s++;break;case"c":t+=e.cwd,s++;break;case"a":t+=e.agentId,s++;break;case"u":t+=e.baseUrl,s++;break;case"t":t+=e.tokenFile,s++;break;default:t+=r;break}}return t}function QT(n){if(Array.isArray(n))return[...n];let e=n;return e.trim().length===0?[]:e.trim().split(/\s+/)}function GT(n,e){let t=QT(n.command);if(t.length===0)return null;let s=t.map(a=>et(VT(a,e))),[r,...i]=s;if(!r)return null;let o={HYDRA_SESSION_ID:e.sessionId,HYDRA_CWD:e.cwd,HYDRA_AGENT:e.agentId,HYDRA_BASE_URL:e.baseUrl,HYDRA_TOKEN_FILE:e.tokenFile};return{program:r,args:i,env:o}}function XT(n){let e={stdout:"",stderr:"",bytes:0,truncated:!1},t=(s,r)=>{if(e.truncated)return;let i=n-e.bytes;if(i<=0){e.truncated=!0;return}let o=s.length<=i?s.toString("utf8"):s.subarray(0,i).toString("utf8");s.length>i&&(e.truncated=!0),e[r]+=o,e.bytes+=Math.min(s.length,i)};return{onStdout:s=>t(s,"stdout"),onStderr:s=>t(s,"stderr"),onExit:(s,r)=>{let i=[],o=(a,c)=>{let d=a.split(/\r?\n/);for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let l of d)i.push({text:l,style:c})};return e.stdout&&o(e.stdout,"stdout"),e.stderr&&o(e.stderr,"stderr"),e.truncated&&i.push({text:`[output truncated at ${n} bytes]`,style:"meta"}),r?i.push({text:`[killed by ${r}]`,style:"error"}):typeof s=="number"&&s!==0&&i.push({text:`[exit ${s}]`,style:"error"}),i}}}function uv(n,e,t){let s=GT(n,e);if(s===null){t.notify("hotkey: empty command");return}let r=XT(t.maxOutputBytes??ZT),i=t.spawnFn??YT,o;try{o=i(s.program,s.args,{cwd:t.cwd,env:{...t.parentEnv??process.env,...s.env},stdio:["ignore","pipe","pipe"]})}catch(a){t.emitLines([{text:`[hotkey spawn failed: ${a.message}]`,style:"error"}]);return}o.stdout?.on("data",r.onStdout),o.stderr?.on("data",r.onStderr),o.on("error",a=>{t.emitLines([{text:`[hotkey spawn error: ${a.message}]`,style:"error"}])}),o.on("close",(a,c)=>{t.emitLines(r.onExit(a,c))})}var ZT,fv=V(()=>{"use strict";Qe();ZT=16*1024});import{spawn as eE}from"child_process";function pv(n,e){let t=Buffer.from(e,"utf8").toString("base64");process.stdout.write(`${tE}1337;SetUserVar=${n}=${t}${nE}`)}function hv(n){if(process.env.TMUX_PANE)try{let e=eE("tmux",n,{stdio:"ignore",detached:!0});e.on("error",()=>{}),e.unref()}catch{}}function Tp(n,e){pv(n,e);let t=process.env.TMUX_PANE;t&&hv(["set-option","-pt",t,`@${n}`,e])}function mv(n){pv(n,"");let e=process.env.TMUX_PANE;e&&hv(["set-option","-put",e,`@${n}`])}var tE,nE,gv=V(()=>{"use strict";tE="\x1B]",nE="\x07"});function yv(n){let e={};if(!n||typeof n!="object")return e;let t=n;typeof t.historyPolicy=="string"&&(e.appliedPolicy=t.historyPolicy),typeof t.clientId=="string"&&t.clientId.length>0&&(e.clientId=t.clientId);let s=t._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 wv(n){return!n.replayDraining&&!n.amended&&n.pendingTurns>0&&n.queueSize===0&&!n.ownTurnInFlight&&!n.hasInFlightHead}function bv(n){return n.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:n.pendingTurns===0?1:0,banner:"busy",busySince:n.daemonTurnStartedAt}:{pendingTurnsDelta:n.pendingTurns>0?-n.pendingTurns:0,banner:"ready"}}var vv=V(()=>{"use strict"});import{readFileSync as sE}from"fs";import{nanoid as Sv}from"nanoid";import rE from"terminal-kit";import Ep from"fs/promises";import oi from"path";function iE(n){return n.filter(e=>e.status==="open"||e.status==="pending-delivery")}function oE(n){let e=kl(n);if(n.status==="pending-delivery"&&n.userAnswer){let t=e.indexOf(n.userAnswer);if(t!==-1)return t}return 0}function aE(n){let e=new Map,t=[];for(let s of n){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),t.push(r))}return t.map(s=>e.get(s))}function kl(n){if(n.options&&n.options.length>0){let e=n.options.filter(t=>t!==n.defaultAnswer);return n.options.includes(n.defaultAnswer)?[n.defaultAnswer,...e]:[n.defaultAnswer,...n.options]}return[n.defaultAnswer]}function dE(n,e){return n.length<=e?n:e<=1?"\u2026":n.slice(0,e-1)+"\u2026"}function cE(n,e,t,s,r=60){let i=n.map((o,a)=>{let c=kl(o.representative),d=e[a]??0,l=t[a]?Mp:c[d]??c[0]??"";return{label:dE(o.representative.question,r),value:l}});return{title:`Open questions (${n.length})`,options:i,selectedIndex:Math.max(0,Math.min(n.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function lE(n,e,t){return n===Mp?{type:"dismiss",method:yb,params:{sessionId:t,questionId:e.id}}:{type:"answer",method:gb,params:{sessionId:t,questionId:e.id,answer:n}}}function uE(n,e,t,s,r){let i=[];for(let o=0;o<n.length;o++){let a=n[o];if(!a||!t[o])continue;let c=s[o]?Mp:kl(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=lE(c,l,r);u!==null&&i.push(u)}}return i}function fE(n,e,t,s,r,i,o,a){if(!e||t===null||t.length===0)return{type:"noop"};if(n.type==="char"){if(n.ch==="d"||n.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(n.ch)){let d=parseInt(n.ch,10)-1;if(d<t.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(n.type!=="key")return{type:"noop"};let c=d=>{let l=t[o];if(!l)return{type:"noop"};let u=kl(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(n.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(t.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:uE(t,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function kv(n){if(!Array.isArray(n))return;let e=ns({sessionUpdate:"config_option_update",configOptions:n});return e&&e.kind==="config-options"?e.options:void 0}function Pp(n){switch(n.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function mE(n,e){e.has(n)?e.delete(n):e.add(n)}function gE(){if(Iv)return;Iv=!0;let n=e=>e instanceof Error?e.stack??e.message:String(e);process.on("uncaughtException",e=>{oe({src:"uncaughtException",stack:n(e)}),yr(),process.stderr.write(`
241
241
  uncaught: ${n(e)}
242
- `),process.exit(1)}),process.on("unhandledRejection",e=>{oe({src:"unhandledRejection",stack:n(e)}),ti(),process.stderr.write(`
242
+ `),process.exit(1)}),process.on("unhandledRejection",e=>{oe({src:"unhandledRejection",stack:n(e)}),yr(),process.stderr.write(`
243
243
  unhandled rejection: ${n(e)}
244
- `),process.exit(1)}),process.on("exit",e=>{e!==0&&oe({src:"process-exit",code:e})})}async function kv(n){uE();let e=await xe(),t=n.target??await Dt(e);if(ph(e.tui.logMaxBytes),t.isLocal&&!n.target&&await ar(e),n.agentId)try{let p=await zr(t),h=Ea(n.agentId,p.map(m=>m.id));h!==void 0&&h!==n.agentId&&(n.agentId=h)}catch{}let s=ZT.terminal;Kb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:jp(e),defaultEnterAction:e.tui.defaultEnterAction,...n.agentId?{lastChosenAgent:n.agentId}:{}},o=Ip(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
245
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=n;try{for(;u!==null;)u=await pE(s,e,t,u,r,i,o)}finally{uv("hydra_session"),d(),process.off("exit",l)}let f=await La();if(f&&process.stderr.write(`\u2728 ${Ba(f)}
246
- `),process.stdout.isTTY){let p=await jr(e);if(p?.version!==void 0){let h=p.version!==ye,m=sr(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let b=h?`daemon ${p.version} \u2260 cli ${ye}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Vn()} daemon restart\` to apply.`)+`
247
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=ft(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Vn()} --session ${p}${h}
248
- `)}}function fE(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,c=e.length,d=a>0,l;if(!d||n.expanded)l=e;else{let M=Math.max(0,c-a),D=e.slice(M),B=[];for(let O=0;O<M;O++){let K=e[O];if(K===void 0)continue;let X=t.get(K);X&&!Sf(X.status)&&B.push(K)}l=[...B,...D]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",b=y?`amended \xB7 ${is(h)}`:`stopped (${m}) \xB7 ${is(h)}`,v;if(c===0)m!==null?v=b:v=f?`thinking \xB7 ${is(h)}`:`thought \xB7 ${is(h)}`;else{let M=c===1?"tool":"tools",D=m!==null?b:f?is(h):`took ${is(h)}`,B=[`${c} ${M}`,D];f&&d&&u>0&&B.push(`${u} hidden`),v=B.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?x:"dim"}],N=[null];for(let M of l){let D=t.get(M);if(D){let B=Ta(D,p);for(let O of B)O.hoverSubKey=M;if($.push(...B),N.push(...B.map(()=>M)),o?.has(M)){let O=jy(D);for(let K of O)K.hoverSubKey=M;$.push(...O),N.push(...O.map(()=>M))}}}return{lines:$,rowOwners:N}}async function pE(n,e,t,s,r,i,o){let a=await hE(n,e,t,s,o,i);if(!a)return n.grabInput(!1),oe({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=s.installStatus;s.installStatus&&delete s.installStatus;let l=a.installStatus??d??bl(c,tv(n));l.write(c);let u=t.isLocal?async()=>(await Dt(await xe())).wsUrl:t.wsUrl,f=["acp.v1",`hydra-acp-token.${t.token}`],p=null,h=null,m=new To({url:u,subprotocols:f,onConnect:async g=>{g||p&&await p()},onDisconnect:g=>{h&&h(g)},log:g=>oe({src:"resilient-ws",line:g})}),y=new Kt(m);await m.start(),y.onNotification(Ad,g=>{let w=Vh.safeParse(g);w.success&&l.applyProgress(w.data)});let b=[],v=null,S=!1,x=!1,T=(g,w)=>{g&&(v?v(g,w):b.push({event:g,rawUpdate:w}))},E,$=g=>{g!==E&&(E=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},N=null,M=null,D=!1,B=0,O=0,K=!1,X=!1,Z,Q=null,fe=null,Me=null,In=null,De=()=>setInterval(()=>{if(Q===null||G===null)return;let g=In===null?0:Date.now()-In;G.setBanner({elapsedMs:Date.now()-Q,stalled:g>=dE}),mt()},1e3),cs=!1,Se=g=>{let w=O;O=Math.max(0,O+g);let k=typeof G<"u"&&G!==null;w===0&&O>0?(X=!1,Q=Date.now(),In=Date.now(),Ie?.setTurnRunning(!0),k&&G.setBanner({status:"busy",elapsedMs:0,stalled:!1}),fe===null&&k&&(fe=De())):w>0&&O===0?(X=!1,Q=null,In=null,Ie?.setTurnRunning(!1),fe!==null&&(clearInterval(fe),fe=null),k&&G.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):O>0&&X&&(X=!1,k&&G.setBanner({status:"busy",stalled:!1}))},G=null,Ie=null,je,Yt=null,$s=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),un=g=>{let{update:w}=g??{},k=ts(w,{cwd:qe});mE(w,k),In=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!$s.has(C)){let A=w??{};typeof A.messageId=="string"&&(je=A.messageId)}if(C==="prompt_received"?Se(1):k?.kind==="turn-complete"&&(Se(-1),D=!0),C==="permission_resolved"){Lo(w);return}if(C==="hydra_compaction"){Oo(w);return}if(C==="clarifier_question_asked"){let A=w,_=typeof A.question?.question=="string"?A.question.question:"",W=_.length>50?_.slice(0,49)+"\u2026":_;I.notify(W?`new question: ${W} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(T(k,w),Za(w))};y.onNotification("session/update",g=>{if(!S){if(Yt!==null){Yt.push(g);return}un(g)}}),y.onNotification("hydra-acp/session/closed",()=>{if(S)return;O>0&&Se(-O),typeof G<"u"&&G!==null&&G.setBanner({status:"cold",elapsedMs:void 0})});let wt=new Map,Fs=200,Os=0,ls=!1,ii=4e3;y.onNotification("hydra-acp/prompt_queue/added",g=>{if(S)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,_=setTimeout(()=>{S||(wt.delete(C),Y.set(C,U(C,A)),G&&Ie&&Ze())},Fs);wt.set(C,_)}else Y.set(w.messageId,U(w.messageId,w.prompt)),G&&Ie&&Ze();if(Bs!==void 0&&w.originator?.clientId===Bs){let C=re.shift();C&&(C.messageId=w.messageId,ie.set(w.messageId,C))}}),y.onNotification("hydra-acp/prompt_queue/updated",g=>{if(S)return;let w=g??{};if(typeof w.messageId!="string"||!Y.has(w.messageId))return;Y.set(w.messageId,U(w.messageId,w.prompt));let k=ie.get(w.messageId);if(k){let C=Array.isArray(w.prompt)?w.prompt:[],A="",_=[];for(let W of C){if(!W||typeof W!="object")continue;let H=W;H.type==="text"&&typeof H.text=="string"?A+=H.text:H.type==="image"&&typeof H.data=="string"&&typeof H.mimeType=="string"&&_.push({data:H.data,mimeType:H.mimeType,sizeBytes:Math.floor(H.data.length*3/4)})}k.text=A,k.attachments=_}G&&Ie&&Ze()}),y.onNotification("hydra-acp/prompt_queue/removed",g=>{if(S)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(Z=w.messageId);let k=wt.get(w.messageId);k!==void 0&&(clearTimeout(k),wt.delete(w.messageId)),Y.delete(w.messageId)&&G&&Ie&&Ze();let A=ie.get(w.messageId);A&&(ie.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,T({kind:"user-text",text:A.displayText,attachments:A.attachments}),Ce=A))}),y.onNotification("hydra-acp/cancel_failed",g=>{if(S)return;let w=g??{};if(!(typeof G<"u"&&G!==null))return;Os=Date.now(),ls=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";G.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"}])}),y.onNotification("hydra-acp/prompt/amended",g=>{if(S)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let k=w.cancelledMessageId;we.add(k),Ce!==null&&Ce.messageId!==void 0&&Ce.messageId===k&&(T({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Ce=null,we.delete(k))});let Oo=g=>{let w=g??{},k=typeof w.phase=="string"?w.phase:void 0;if(k==="started")I.setCompactionIndicator("compacting...");else if(k==="iteration")I.setCompactionIndicator("compacting...");else if(k==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(k==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(k==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(k==="failed"){I.setCompactionIndicator(null);let C=typeof w.error=="string"?w.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},xn=()=>{Me===null&&(Me=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),Me!==null&&(clearInterval(Me),Me=null)):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),Me!==null&&(clearInterval(Me),Me=null))}catch{}},5e3))},Xa=()=>{Me!==null&&(clearInterval(Me),Me=null)},Lo=g=>{let w=g??{},k=typeof w.toolCallId=="string"?w.toolCallId:void 0,C;w.outcome&&typeof w.outcome=="object"?C=w.outcome:typeof w.chosenOptionId=="string"&&(C={kind:"selected",optionId:w.chosenOptionId}),Ls(k,C?{outcome:C}:void 0)},me=null,Ls=(g,w)=>{if(!me||me.toolCallId&&g&&me.toolCallId!==g)return;let k=me.resolve;me=null,I.setPermissionPrompt(null),k(w??{outcome:{outcome:"cancelled"}})},Za=g=>{if(!me?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===me.toolCallId&&(!w.status||w.status==="pending"||Ls(w.toolCallId,void 0))},oi=()=>{if(!me){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:me.title,detail:me.detail,options:me.options.map(g=>({label:g.name})),selectedIndex:me.selectedIndex})},ai=g=>{if(!me)return;let{options:w,resolve:k}=me;if(me=null,I.setPermissionPrompt(null),g===null){k({outcome:{outcome:"cancelled"}});return}k({outcome:{outcome:"selected",optionId:g}})};y.onRequest("session/request_permission",async g=>{if(S)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Zr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(ee=>({optionId:ee.optionId,name:Pe(ee.name??""),...ee.kind!==void 0?{kind:ee.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",_=Pe(A),W=Pe(jw(Uw(g))),H=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${_} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(ee=>{me={title:_,detail:W,options:C,selectedIndex:0,resolve:ee,toolCallId:H},oi()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let di,Ct,us=!0,An=!1;try{let g=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ye}});Ct=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(us=!1),An=rn(g?._meta??void 0).prompt?.amending===!0}catch{}let he=a.sessionId,Ke=a.agentId,qe=a.cwd,gt,Bs,fs,ps,ci,Ns,hs,Lt,li,Dn,Bo=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let w={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[$t]:g}}:{}},k;try{k=await _w({request:()=>y.request("session/new",w),showBanner:(_,W,H)=>$w(n,_,W,H,{authenticate:ee=>y.request("authenticate",{methodId:ee})}),resolveOnboarding:async _=>{if(_)try{return(await zr(t)).find(ee=>ee.id===_)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(_){n.grabInput(!1),oe({src:"grab",site:"runSession.session-new-failed",on:!1}),m.close().catch(()=>{});let W=_ instanceof Error?_.message:String(_);oe({src:"session-new-failed",agentId:s.agentId??null,message:W});let H=await iv(n,s.agentId,W,{canGoBack:!s.forceNew});if(H==="cancel")return null;let ee={...s};return delete ee.sessionId,delete ee.resume,H==="retry"?ee.forceNew=!0:(delete ee.forceNew,delete ee.agentId),ee}if(k.kind==="cancel")return n.grabInput(!1),oe({src:"grab",site:"runSession.auth-cancel",on:!1}),m.close().catch(()=>{}),null;if(k.kind==="back"){n.grabInput(!1),oe({src:"grab",site:"runSession.auth-back",on:!1}),m.close().catch(()=>{});let _={...s};return delete _.sessionId,delete _.forceNew,delete _.resume,delete _.agentId,_}let C=k.result;l.write(c),he=C.sessionId,Ap("hydra_session",he),r.sessionId=he,r.readonly=!1;let A=rn(C._meta??void 0);A.clientId&&(Bs=A.clientId),di=A.upstreamSessionId,A.agentId&&(Ke=A.agentId),A.cwd&&(qe=A.cwd),A.title&&(gt=A.title),fs=A.currentModel,ps=A.currentMode,li=A.currentUsage,Dn=A.turnStartedAt,A.availableCommands&&(ci=rc(A.availableCommands)),A.availableModes&&(Ns=A.availableModes),hs=wv(C.configOptions),Lt=A.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let w=await y.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:ye},...Object.keys(g).length>0?{_meta:{[$t]:g}}:{}});he=w.sessionId,Ap("hydra_session",he),w.clientId&&(Bs=w.clientId),r.sessionId=he,r.readonly=s.readonly===!0;let k=rn(w._meta??void 0);Bo=k.resurrected===!0,di=k.upstreamSessionId,k.agentId&&(Ke=k.agentId),k.cwd&&(qe=k.cwd),k.title&&(gt=k.title),fs=k.currentModel,ps=k.currentMode,li=k.currentUsage,Dn=k.turnStartedAt,k.availableCommands&&(ci=rc(k.availableCommands)),k.availableModes&&(Ns=k.availableModes),hs=wv(w.configOptions),Lt=k.queue}let Ds=L.tuiHistoryFile(he),ui=L.globalTuiHistoryFile(),Rt=await da(Ds).catch(()=>[]),Vt=await da(ui).catch(()=>[]);Vt.length>e.tui.promptHistoryMaxEntries&&(Vt=Vt.slice(Vt.length-e.tui.promptHistoryMaxEntries));let Hn=[...Rt],Re=new Ps({history:Dd(Vt,Hn)});Ie=Re;let ed=!1,$e=(g,w)=>{let k=g.replace(/\n+$/,"");if(k.length===0)return;let C=(w??g).replace(/\n+$/,""),A=ca(Rt,k),_=A!==Rt;Rt=A,Hn=ca(Hn,C);let W=ca(Vt,k,e.tui.promptHistoryMaxEntries),H=W!==Vt;Vt=W,Re.setHistory(Dd(Vt,Hn)),_&&Dr(Ds,Rt).catch(()=>{}),H&&Jm(ui,k).catch(()=>{})};O>0&&Re.setTurnRunning(!0);let Tt=null,Un=null;qb(Wb(e.tui.ambiguousWidth,process.env)),Wy(e.tui.diffContextLines);let Qt=!1,I,jn=()=>{Qt&&(Qt=!1,I.start())},fn=()=>{Qt||(Qt=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",jn);let Hs=null,fi=null;I=new fl({term:n,dispatcher:Re,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"?fn:void 0,onBlockClick:(g,w)=>{Uv(g,w)},onBlockDoubleClick:(g,w)=>Hv(g,w),onHydraLinkClick:g=>(Si(g),!0),onBlockVisible:g=>{Bv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let w=Cr.get(g);if(w!==void 0&&w.length>0)return new Set(w);let k=I.contiguousRun(g,new Set(Ks.keys()));return k.length>0?new Set(k):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){Hs=I.bannerHitAt(g.x,g.y),fi=Hs?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let k=fi,C=Hs;if(fi=null,Hs=null,C!==null&&k!==null&&k.x===g.x&&k.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){Bt(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Rp(A))return;Ir(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&Rp(w)||Ir(w)},onKey:g=>{for(let w of g){if(K&&yi(w)){w.type==="key"&&oe({src:"key-swallowed",site:"compactionPrompt",name:w.name});continue}if(me&&nd(w)){w.type==="key"&&oe({src:"key-swallowed",site:"permission",name:w.name});continue}if(sd(w)){w.type==="key"&&oe({src:"key-swallowed",site:"help",name:w.name});continue}if(zn(w)){w.type==="key"&&oe({src:"key-swallowed",site:"questions",name:w.name});continue}if(bi(w)){w.type==="key"&&oe({src:"key-swallowed",site:"options",name:w.name});continue}if(td(w)){w.type==="key"&&oe({src:"key-swallowed",site:"scrollbackSearch",name:w.name});continue}if(xl(w)){w.type==="key"&&oe({src:"key-swallowed",site:"completion",name:w.name});continue}if(gs(w)){w.type==="key"&&oe({src:"key-swallowed",site:"btwClose",name:w.name});continue}if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){ki(w.paths);continue}if(w.type==="key"&&yr(w.name)){oe({src:"key-swallowed",site:"userHotkey",name:w.name});continue}let k=Re.feed(w);for(let C of k)s.readonly===!0&&Rp(C)||Ir(C)}qt(),I.setBannerSearchIndicator(Re.state().historySearchQuery),I.setAttachments(Re.state().attachments),I.refreshPrompt()}}),G=I,I.setStickyBottomKey("plan");let No=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],gr=ci??[],qn=Ns??[],Do=hs??[],pi=()=>Do.find(g=>g.id==="agent"),Xe=()=>{let g=new Set,w=[];for(let k of[...No,...gr])g.has(k.name)||(g.add(k.name),w.push(k));return w},Ho=()=>{let g=Re.state().buffer,w=g[0]??"";if(!w.startsWith("/"))return[];if(g.length>1)return[];let k=w.indexOf(" "),C=k===-1?w:w.slice(0,k);if(C.lastIndexOf("/")>0)return[];let A=Xe().filter(_=>_.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},ms=[],qt=()=>{let g=Ho();if(g.length>0){ms=[],I.setCompletions(g);return}I.setCompletions(ms)},xl=g=>{if(g.type!=="key"||g.name!=="tab")return ms.length>0&&(ms=[]),!1;let w=Ho();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){ms=[];let k=Re.state().buffer[0]??"",C=Qb({matches:w.map(A=>A.name),firstLine:k});return C===null||Re.replaceFirstLine(C),!0}return bt()},bt=()=>{let g=Re.state(),w=g.buffer[g.row]??"",k=yl(w,g.col);if(k===null)return!1;let C=wl(k.token,qe);return C===null?!1:(C.replacement!==k.token&&Re.replaceRangeOnCurrentLine(k.start,g.col,C.replacement),ms=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},gs=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay(),!0),td=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let w=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(w),!0}if(g.type==="paste"){let w=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(w),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let w=I.scrollbackSearchTerm();return w.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(w.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},nd=g=>{if(!me)return!1;let w=me.options;if(g.type==="key")switch(g.name){case"up":return me.selectedIndex=Math.max(0,me.selectedIndex-1),oi(),!0;case"down":return me.selectedIndex=Math.min(w.length-1,me.selectedIndex+1),oi(),!0;case"enter":{let k=w[me.selectedIndex];return k&&ai(k.optionId),!0}case"escape":case"ctrl-c":return ai(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let k=parseInt(g.ch,10)-1,C=w[k];return C&&ai(C.optionId),!0}return!0},yr=g=>{let w=e.tui.hotkeys[g];return w?(av(w,{sessionId:he,cwd:qe,agentId:Ke||Ct||"",baseUrl:t.baseUrl,tokenFile:L.authToken()},{notify:k=>I.notify(k),cwd:qe,emitLines:k=>{I.appendLines(k.map(C=>{let A;switch(C.style){case"meta":A="dim";break;case"stderr":case"error":A="tool-status-fail";break;default:A="info"}return{prefix:" ",body:C.text,bodyStyle:A}}))}}),!0):!1},Uo=Ke||Ct||"?",Gt={...li??{}};l.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:Uo,cwd:qe,sessionId:he,title:gt,model:fs,usage:{...Gt}}),ps&&I.setBanner({currentMode:ps}),La().then(g=>{g&&I.notify(`\u2728 ${Ba(g)}`,3e4)}).catch(()=>{});let lt=null,wr=new Promise(g=>{lt=g}),hi=()=>{y.notify("session/cancel",{sessionId:he}).catch(()=>{})},mi=()=>{G!==null&&O===1&&(X=!0,G.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},br=()=>{if(Tt){Tt.cancel(),mi();return}if(O>0){hi(),mi();return}gi()},gi=()=>{Zt(0)},jo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",w="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",w],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",w]],...cE]},qo=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:jo(),hint:"any key dismisses \xB7 /help lists commands"})},vr=()=>{K=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=he;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Cn=()=>{K=!1,I.setCompactionPrompt(null)},ys=g=>{let w=I.compactionPromptSpec();if(!w)return;let k=w.options.length;if(k===0)return;let C=((w.selectedIndex+g)%k+k)%k;C!==w.selectedIndex&&I.setCompactionPrompt({...w,selectedIndex:C})},yi=g=>{if(!K)return!1;if(g.type==="key"){if(g.name==="escape")return Cn(),!0;if(g.name==="up")return ys(-1),!0;if(g.name==="down")return ys(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?vr():Cn(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return vr(),!0;if(w==="n"||w==="2")return Cn(),!0}return!0},sd=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Us=["tools","plan","thoughts","diffs","mouse","enter"],Rn=0,Tn=null,ws=[],Wt=[],pn=[],js=0,Sr=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}},wi=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"}},Al=()=>({title:"Session options",options:Us.map(g=>({label:wi(g),value:Sr(g)})),selectedIndex:Rn}),Xt=()=>{I.isOptionsPromptActive()&&Tn===null&&I.setOptionsPrompt(Al())},Cl=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Rn=0,I.setOptionsPrompt(Al())},hn=()=>{if(Tn===null)return;let g=rE(Tn,ws,pn,js);I.setOptionsPrompt(g)},Wn=()=>{Tn=null,ws=[],Wt=[],pn=[],js=0,I.setOptionsPrompt(null)},rd=async()=>{if(Tn!==null){Wn();return}try{let w=await y.request(ub,{sessionId:he}),k=eE(w.questions??[]);if(k.length===0){I.notify("no open questions");return}let C=nE(k);Tn=C,js=0,ws=C.map(A=>tE(A.representative)),Wt=C.map(()=>!1),pn=C.map(()=>!1),hn()}catch(g){I.notify("clarifier unavailable"),oe({src:"questions",step:"list_failed",error:g.message})}},id=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,xr.clear(),Ii.clear(),Vs();break;case"plan":i.planExpanded=!i.planExpanded,Js=null,Tr();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",mn.clear(),Nv();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Xt()},kr=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${wi(g)} is session-only \u2014 not saved`);return;case"thoughts":await Jo("showThoughts",i.showThoughts);break;case"diffs":await Jo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Jo("mouse",i.mouseEnabled);break;case"enter":await Jo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${wi(g)} ${Sr(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},bi=g=>{if(Tn!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Rn=Math.max(0,Rn-1),Xt(),!0;case"down":return Rn=Math.min(Us.length-1,Rn+1),Xt(),!0;case"enter":{let w=Us[Rn];return w&&id(w),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let w=parseInt(g.ch,10)-1,k=Us[w];return k&&(Rn=w,id(k)),!0}if(g.ch==="s"||g.ch==="S"){let w=Us[Rn];return w&&kr(w),!0}}return!0},zn=g=>{if(Tn===null)return!1;let w=aE(g,!0,Tn,ws,Wt,pn,js,he);switch(w.type){case"noop":return!0;case"row":return js=w.selectedRow,hn(),!0;case"cycle":return ws[w.selectedRow]=w.newValueIndex,Wt[w.selectedRow]=!0,pn[w.selectedRow]=!1,hn(),!0;case"dismiss-toggle":{let k=w.selectedRow;return pn[k]?(pn[k]=!1,Wt[k]=!1):(pn[k]=!0,Wt[k]=!0),hn(),!0}case"discard":return Wn(),!0;case"save":{let k=w.dispatches;return Wn(),k.length===0||(async()=>{let C=0,A=0,_=0;for(let H of k)try{await y.request(H.method,H.params),H.type==="dismiss"?A++:C++}catch(ee){_++,oe({src:"questions",step:"dispatch_failed",method:H.method,error:ee.message})}let W=[];C>0&&W.push(`${C} answered`),A>0&&W.push(`${A} dismissed`),_>0&&W.push(`${_} failed`),W.length>0&&I.notify(`clarifier: ${W.join(", ")}`)})(),!0}}return!1},vi=()=>{S=!0,N?(N.cancel(),N=null,M=null):M!==null&&(rs(t,M).catch(()=>{}),M=null),process.off("SIGINT",br),process.platform!=="win32"&&process.off("SIGCONT",jn),fe!==null&&(clearInterval(fe),fe=null),Me!==null&&(clearInterval(Me),Me=null);for(let g of wt.values())clearTimeout(g);wt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),Dr(Ds,Rt).catch(()=>{}),m.close().catch(()=>{})},Zt=(g=0)=>{vi(),lt&&(lt(null),lt=null),g!==0&&process.exit(g)},qs=async()=>{if(oe({src:"switch-session",step:"entered",finishSessionNull:lt===null}),!lt)return;N?(N.cancel(),N=null,M=null):M!==null&&(rs(t,M).catch(()=>{}),M=null),Xa(),I.setSynthesisIndicator(null);let g=Re.state().buffer.join(`
249
- `);g.replace(/\s+$/,"").length>0&&$e(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),Dr(Ds,Rt).catch(()=>{});let w=!1;try{let k=null,C=null;for(;k===null;){let H=await ss(t,{includeNonInteractive:!0}),ee=s.agentId??i.lastChosenAgent??e.defaultAgent,Ee=ee?e.defaultModels?.[ee]:void 0,be=[];try{be=await zr(t)}catch{}let ae=await xp(n,{cwd:qe,sessions:H,config:e,target:t,currentSessionId:he,prefs:o,...ee?{composerAgentId:ee}:{},...Ee?{composerModel:Ee}:{},...be.length>0?{availableAgents:be}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){w=!0,Zt(0);return}if(ae.kind==="new"){k={choice:ae,sessions:H};break}if(ae.kind==="fork"){let Mn=await Av(n,t,ae,H);if(Mn.kind==="cancel")return;if(Mn.kind==="back")continue;k={choice:{kind:"attach",sessionId:Mn.ctx.sessionId,...Mn.ctx.agentId?{agentId:Mn.ctx.agentId}:{}},sessions:H},C={readonly:!1,cwd:Mn.ctx.cwd},Mn.ctx.resumeHint!==void 0&&(C.resumeHint=Mn.ctx.resumeHint);break}let ge=H.find(Mn=>Mn.sessionId===ae.sessionId);if(!(ge!==void 0&&!!ge.importedFromMachine&&!ge.upstreamSessionId&&ae.readonly!==!0)){if(t.isLocal&&ge&&!ge.importedFromMachine&&ae.readonly!==!0&&!(await Da(ge.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let zo=await si(n,ge,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(zo.kind==="cancel")return;if(zo.kind==="back")continue;k={choice:ae,sessions:H},C={readonly:!1,cwd:zo.path,resumeHint:{agentId:ae.agentId??ge.agentId??"",cwd:zo.path,upstreamSessionId:""}};break}k={choice:ae,sessions:H};break}let Yn={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let Wo=await Iv(n,t,ge,ae,Yn);if(Wo.kind==="cancel")return;Wo.kind!=="back"&&(k={choice:ae,sessions:H},C={readonly:Yn.readonly===!0,cwd:Wo.ctx.cwd},Wo.ctx.resumeHint!==void 0&&(C.resumeHint=Wo.ctx.resumeHint))}let{choice:A}=k,_=lt;if(lt=null,process.off("SIGINT",br),m.close().catch(()=>{}),w=!0,A.kind==="new"){let{sessionId:H,agentId:ee,...Ee}=s,be={...Ee,cwd:A.cwd??qe,forceNew:!0,readonly:!1};A.prompt!==void 0&&(be.initialPrompt=A.prompt),A.attachments&&A.attachments.length>0&&(be.initialAttachments=A.attachments),A.agentId!==void 0&&(be.agentId=A.agentId,i.lastChosenAgent=A.agentId),A.model!==void 0&&(be.model=A.model),A.installStatus!==void 0&&(be.installStatus=A.installStatus),_(be);return}if(A.kind!=="attach")return;let W={...s,sessionId:A.sessionId,cwd:C?.cwd??qe,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(W.agentId=A.agentId),C?.resumeHint!==void 0?W.resumeHint=C.resumeHint:delete W.resumeHint,A.installStatus!==void 0?W.installStatus=A.installStatus:delete W.installStatus,_(W)}finally{!w&&lt&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},zt=async(g="next")=>{if(!lt)return;let k=(await ss(t)).filter(be=>be.status==="warm");if(k.length<=1)return;let C=k.findIndex(be=>be.sessionId===he),W=((C===-1?0:C)+(g==="prev"?-1:1)+k.length)%k.length,H=k[W],ee=lt;lt=null,process.off("SIGINT",br),m.close().catch(()=>{});let Ee={...s,sessionId:H.sessionId,cwd:qe,readonly:!1};H.agentId!==void 0&&(Ee.agentId=H.agentId),ee(Ee)},Si=async g=>{if(!lt)return;let w=await ss(t,{includeNonInteractive:!0}),k=g.trim();if(!k){I.notify("usage: /session <id|next|prev>");return}let C=k.startsWith(Ut)?[k]:[k,Ut+k],A=w.find(H=>C.includes(H.sessionId));if(!A){let H=w.filter(ee=>C.some(Ee=>ee.sessionId.startsWith(Ee)));if(H.length===1)A=H[0];else if(H.length>1){I.notify(`ambiguous session id: ${k} (${H.length} matches)`);return}}if(!A){I.notify(`no session matches: ${k}`);return}if(A.sessionId===he){I.notify("already on that session");return}let _=lt;lt=null,process.off("SIGINT",br),m.close().catch(()=>{});let W={...s,sessionId:A.sessionId,cwd:A.cwd??qe,readonly:!1};A.agentId!==void 0&&(W.agentId=A.agentId),delete W.resumeHint,_(W)},Ir=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ws(g.text,g.attachments,g.displayText):Ve(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ve(g.text,g.attachments,g.displayText):Ws(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=ht(g.index);if(!w)return;let k=[];g.text.length>0&&k.push({type:"text",text:g.text});for(let C of g.attachments)k.push({type:"image",data:C.data,mimeType:C.mimeType});y.request("hydra-acp/prompt/update",{sessionId:he,messageId:w,prompt:k}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let w=ht(g.index);if(!w)return;y.request("hydra-acp/prompt/cancel",{sessionId:he,messageId:w}).then(k=>{let C=k;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(k=>{I.notify(`queue cancel failed: ${k.message}`)});return}case"cancel":{if(I.isOverlayOpen()){N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay();return}if(g.prefill&&Tt){let w=Y.size===0,k=Re.state().buffer.every(C=>C==="");w&&k&&(Un={text:Tt.text,attachments:Tt.attachments})}Tt?Tt.cancel():O>0&&hi(),mi();return}case"exit":gi();return;case"plan-toggle":Bt(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":qs().catch(w=>{oe({src:"switch-session-failed",stack:w instanceof Error?w.stack??w.message:String(w)})});return;case"next-live-session":zt().catch(()=>{});return;case"toggle-options":Cl();return;case"toggle-questions":rd();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w,I.notify(w?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":qo();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":R(g.source);return}},ki=async g=>{if(!us){I.notify("agent does not accept image attachments");return}let w=0;for(let k of g){if(k.startsWith("data:")){let A=Gf(k);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>as){I.notify(`image too large (${kn(A.sizeBytes)}, max ${kn(as)})`);continue}Re.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=Ua(k);if(!C){I.notify(`unsupported image type: ${ri.basename(k)}`);continue}try{let A=await Cp.readFile(k);if(A.length>as){I.notify(`image too large (${kn(A.length)}, max ${kn(as)})`);continue}Re.addAttachment({mimeType:C,data:A.toString("base64"),name:ri.basename(k),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${ri.basename(k)}: ${A.message}`)}}w>0&&(I.setAttachments(Re.state().attachments),I.refreshPrompt())},R=async(g="clipboard")=>{let w=g==="primary"?await kb():await il();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!us){I.notify("agent does not accept image attachments");return}Re.addAttachment(w.attachment),I.setAttachments(Re.state().attachments),I.refreshPrompt();return}let k=Re.feed({type:"paste",text:w.text});for(let C of k)Ir(C);I.refreshPrompt()},P=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,U=(g,w)=>{let k=Array.isArray(w)?w:[],C="",A=0;for(let _ of k){if(!_||typeof _!="object")continue;let W=_;W.type==="text"&&typeof W.text=="string"?C+=W.text:W.type==="image"&&(A+=1)}return{messageId:g,text:Pe(C),attachmentCount:A}},Y=new Map,re=[],ie=new Map,we=new Set,Ce=null,Ze=()=>{let g=[...Y.values()],w=g.map(P);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),Re.setQueue(g.map(k=>k.text))},ht=g=>[...Y.values()][g]?.messageId;if(Lt&&Lt.length>0){for(let g of Lt){if(g.position===0){Z=g.messageId;continue}Y.set(g.messageId,U(g.messageId,g.prompt))}Y.size>0&&Ze()}let Ve=(g,w,k)=>{I.scrollToBottom(),!bs(g)&&($e(g,k),vs(g,w,k))},Ws=(g,w,k)=>{if(I.scrollToBottom(),bs(g))return;if($e(g,k),!An||Z===void 0){vs(g,w,k);return}let C=Z,A=[];g.length>0&&A.push({type:"text",text:g});for(let H of w)A.push({type:"image",data:H.data,mimeType:H.mimeType});let _={text:g,displayText:k??g,attachments:w,flushed:!1};re.push(_);let W=()=>{let H=re.indexOf(_);H>=0&&re.splice(H,1),_.messageId!==void 0&&ie.delete(_.messageId)};y.request("hydra-acp/prompt/amend",{sessionId:he,targetMessageId:C,prompt:A}).then(H=>{let ee=H;if(ee.amended&&ee.reason==="ok"){Se(1);return}if(W(),ee.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),Re.setBuffer(g,w),I.refreshPrompt();return}if(ee.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),Re.setBuffer(g,w),I.refreshPrompt();return}if(ee.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),Re.setBuffer(g,w),I.refreshPrompt();return}}).catch(H=>{W(),I.notify(`amend failed: ${H.message}`),Re.setBuffer(g,w),I.refreshPrompt()})},Bt=async g=>{if(qn.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),k=qn.findIndex(_=>_.id===w),C=k===-1?0:(k+1)%qn.length,A=qn[C]?.id;if(A){I.setBanner({currentMode:A});try{await y.request("session/set_mode",{sessionId:he,modeId:A})}catch(_){I.notify(`set_mode failed: ${_.message}`)}}},bs=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
250
- `))return!1;let k=w.indexOf(" ");switch(k===-1?w:w.slice(0,k)){case"/quit":case"/exit":return gi(),!0;case"/clear":return ut.clear(),zs.clear(),Nt.length=0,it=null,st=null,Pn=null,vt.clear(),mn.clear(),en.clear(),xr.clear(),Ks.clear(),Cr.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let _ of No)A.push({prefix:" ",body:` ${_.name.padEnd(12)} ${_.description??""}`,bodyStyle:"info"});if(gr.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let _ of gr)A.push({prefix:" ",body:` ${_.name.padEnd(12)} ${_.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=k===-1?"":w.slice(k+1).trim(),_=pi();if(!_)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let ee of _.options){let Ee=ee.value===_.currentValue?"* ":" ";H.push({prefix:" ",body:`${Ee}${ee.value.padEnd(16)} ${ee.name}`,bodyStyle:"info"})}return I.appendLines(H),!0}let W=_.options.find(H=>H.value===A)?.value;if(!W){let H=A.toLowerCase(),ee=_.options.filter(Ee=>Ee.value.toLowerCase().startsWith(H));ee.length===1&&(W=ee[0].value)}return W?W===_.currentValue?(I.notify(`already on agent ${W}`),!0):(I.notify(`switching to ${W}\u2026`),y.request("session/set_config_option",{sessionId:he,configId:"agent",value:W}).catch(H=>{I.notify(`set_config_option failed: ${H.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return qs().catch(A=>{oe({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=k===-1?"":w.slice(k+1).trim();return A?A==="next"||A==="prev"?(zt(A).catch(_=>{I.notify(`session ${A} failed: ${_.message}`)}),!0):(Si(A).catch(_=>{I.notify(`session switch failed: ${_.message}`)}),!0):(qs().catch(_=>{oe({src:"switch-session-failed",stack:_ instanceof Error?_.stack??_.message:String(_)})}),!0)}case"/rename":{let A=k===-1?"":w.slice(k+1).trim(),_=A.length>0?`/hydra title ${A}`:"/hydra title";return $e(w,w),vs(_,[],w),!0}case"/btw":{let A=k===-1?"":w.slice(k+1).trim();if(!A)return I.isOverlayOpen()?(N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(he==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;B+=1;let _=B;N&&(N.cancel(),N=null);let W=null;M!==null&&!D?W=M:M!==null&&(rs(t,M).catch(()=>{}),M=null),D=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let H=new nl({getMaxWidth:()=>{let ae=I.width();return ae>0?ae:void 0}});H.on("changed",()=>{I.setBtwOverlayContent(H.getLines())});let ee={};H.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Ee=ae=>{H.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},be={};return W!==null&&(be.reuseSessionId=W),mb(t,he,A,be).then(ae=>{if(_!==B){ae.cancel();return}N=ae,M=ae.sessionId,I.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",ge=>{if(_===B)if(ge.kind==="update"){H.append(ge.update);let rt=ts(ge.update);if(rt&&rt.kind==="usage-update"){let Yn=!1;rt.used!==void 0&&ee.used!==rt.used&&(ee.used=rt.used,Yn=!0),rt.size!==void 0&&ee.size!==rt.size&&(ee.size=rt.size,Yn=!0),rt.costAmount!==void 0&&ee.costAmount!==rt.costAmount&&(ee.costAmount=rt.costAmount,Yn=!0),rt.costCurrency!==void 0&&ee.costCurrency!==rt.costCurrency&&(ee.costCurrency=rt.costCurrency,Yn=!0),Yn&&I.setBtwOverlayMeta({usage:{...ee}})}}else ge.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),N=null):ge.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),N=null,M=null):ge.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw errored: ${ge.error.message}`),M!==null&&rs(t,M).catch(()=>{}),N=null,M=null)})}).catch(ae=>{if(_!==B)return;let ge=ae instanceof Error?ae.message:String(ae);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw startup failed: ${ge}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ge}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(he==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=k===-1?"":w.slice(k+1).trim(),_=he;return(async()=>{try{let W=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(_)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!W.ok){let ge=await W.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${W.status} ${ge}`.trim(),bodyStyle:"info"}]);return}let H=await W.text(),ee=new Date().toISOString().replace(/[:.]/g,"-"),Ee=`hydra-${ft(_)}-${ee}.md`,be=A.length>0?et(A):Ee,ae=ri.resolve(be);await Cp.mkdir(ri.dirname(ae),{recursive:!0}),await Cp.writeFile(ae,H,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(W){I.appendLines([{prefix:" ",body:`/export failed: ${W.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},vs=async(g,w,k)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let be of w)C.push({type:"image",data:be.data,mimeType:be.mimeType});Se(1);let A={text:g,displayText:k??g,attachments:w,flushed:!1};re.push(A),ls=!1;let _=!1,W=null,H=be=>{typeof G<"u"&&G!==null&&G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:be,bodyStyle:"tool-status-fail"}])},ee=!1;Tt={text:g,attachments:w,cancel:()=>{if(ls){ls=!1,ee=!0,H("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),y.request("hydra-acp/session/force_cancel",{sessionId:he}).catch(ae=>{H(`force-stop failed: ${ae.message}`)});return}if(_)return;_=!0,y.notify("session/cancel",{sessionId:he}).catch(()=>{});let be=Date.now();W=setTimeout(()=>{Tt!==null&&(Os>=be||(ls=!0,H("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},ii)}};let Ee;try{let be=await y.request("session/prompt",{sessionId:he,prompt:C});be&&typeof be.stopReason=="string"&&(Ee=be.stopReason)}catch(be){let ae=re.indexOf(A);ae>=0&&re.splice(ae,1),A.messageId!==void 0&&ie.delete(A.messageId),ee?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:be.message,bodyStyle:"tool-status-fail"}])}finally{if(Tt=null,W!==null&&(clearTimeout(W),W=null),Se(-1),A.flushed&&Ce===A){let be=A.messageId!==void 0&&we.has(A.messageId);be&&A.messageId!==void 0&&we.delete(A.messageId);let ae={kind:"turn-complete"};Ee!==void 0&&(ae.stopReason=Ee),be&&(ae.amended=!0),T(ae),Ce=null}if(Un!==null){let{text:be,attachments:ae}=Un;Un=null,Re.state().buffer.every(rt=>rt==="")&&(Re.setBuffer(be,ae),I.refreshPrompt())}}},ut=new Map,vt=new Map,mn=new Map,zs=new Map,Nt=[],En=0,gn=`tools:${En}`,en=new Map,xr=new Map,Ii=new Set,Ar=new Map,Ks=new Map,Cr=new Map,it=null,st=null,Pn=null,Kn=null,Js=null,Rl=e.tui.maxToolItems,Tl=e.tui.maxPlanItems,Rr=()=>({maxPlanItems:Js??i.planExpanded?1/0:Tl}),Tr=()=>{if(Kn===null)return;let g=lr(Kn,Rr());g.length>0&&I.upsertLines("plan",[{body:""},...g])},Ys="",F=null,z=0,ue=()=>{if(F===null)return;let g=I.width(),w=ur(Ys,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(F,w)},J=g=>{g.length!==0&&(F===null&&(I.ensureSeparator(),F=`agent:${z}`,z+=1,Ys=""),Ys+=g,ue())},de=()=>{F=null,Ys=""},ce="",Te=null,He=0,We=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),ot=()=>{if(Te===null||ce.length===0)return;let g=vo(ce);g.length!==0&&I.upsertLines(Te,g)},tn=g=>{let w=Ks.get(g);if(w===void 0)return[];let k=vo(w.text);return w.workerTaskId&&k.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),k},Jn=(g,w)=>{g.length!==0&&(Te===null&&(I.ensureSeparator("thought"),Te=`thought:${He}`,He+=1,ce=""),ce+=g,Ks.set(Te,{text:ce,workerTaskId:w}),ot())},ze=()=>{Te=null,ce=""},Ue=g=>fE({...g,collapsedLimit:Rl}),St=g=>xr.get(g)??i.toolsExpanded,mt=()=>{if(it===null)return;let{lines:g,rowOwners:w}=Ue({order:Nt,states:ut,startedAt:it,endedAt:st,stopReason:Pn,expanded:St(gn),perToolExpanded:Ii});I.upsertLines(gn,g),Ar.set(gn,w)},Et=g=>{let w=en.get(g);if(!w)return;let{lines:k,rowOwners:C}=Ue({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:St(g),perToolExpanded:Ii});I.upsertLines(g,k),Ar.set(g,C)},Vs=()=>{it!==null&&!en.has(gn)&&mt();for(let g of en.keys())Et(g)},Ss=()=>{it!==null&&en.set(gn,{order:[...Nt],states:new Map(ut),startedAt:it,endedAt:st??Date.now(),stopReason:Pn,rowOwners:Ar.get(gn)??[]})},od=()=>{En+=1,gn=`tools:${En}`,it=Date.now(),st=null,Pn=null,mt()};function El(g){if(!g||typeof g!="object")return null;let w=g,k=Array.isArray(w.content)?w.content:void 0;if(!k)return null;let C=[],A=_=>{if(typeof _=="string"){C.push({text:yt(_)});return}if(_&&typeof _=="object"){let W=_;typeof W.__hydraBlob=="string"&&C.push({hash:W.__hydraBlob})}};for(let _ of k){if(!_||typeof _!="object")continue;let W=_;if(W.type==="content"&&W.content&&typeof W.content=="object"){let H=W.content;if(H.text!==void 0){A(H.text);continue}}if(W.type==="text"&&W.text!==void 0){A(W.text);continue}W.text!==void 0&&A(W.text)}return C.length>0?C:null}let xi=(g,w)=>{let k=w.map(_=>"text"in _?_.text:"").join(`
251
- `);if(k.length===0)return;let{text:C,truncated:A}=Uy(k);g.resultText=C,g.resultTruncated=A},Le=new Set,Pt=(g,w)=>{!w.some(C=>"hash"in C)||Le.has(g)||(Le.add(g),(async()=>{let C=await Promise.all(w.map(async _=>"text"in _?_:{text:await Ai(_.hash)??""}));Le.delete(g);let A=ut.get(g);if(!A)for(let _ of en.values()){let W=_.states.get(g);if(W){A=W;break}}if(A){xi(A,C),ut.has(g)&&mt();for(let[_,W]of en)W.states.has(g)&&Et(_);I.repaintNow()}})().catch(()=>{Le.delete(g)}))},Qs=(g,w,k,C,A,_,W,H,ee,Ee)=>{let be=!ut.has(g),ae=ut.get(g),ge=ae??{initialTitle:w??"tool",latestTitle:w??"tool",status:k??"pending",startedAt:Date.now()};if(!ae&&ee!==void 0&&(ge.workerTaskId=ee),ae&&w!==void 0&&(ge.latestTitle=w),_!==void 0&&ge.detail===void 0&&(ge.detail=_),W!==void 0&&ge.detailFull===void 0&&(ge.detailFull=W),H!==void 0&&H.length>0&&(ge.locations=H),ae&&k!==void 0&&(ge.status=k),ae||(ge.status=k??"pending"),ge.endedAt===void 0&&Sf(ge.status)&&(ge.endedAt=Date.now()),C!==void 0&&(ge.errorText=C),A!==void 0&&(ge.editDiff=A),Ee!==void 0){let rt=El(Ee);rt!==null&&(xi(ge,rt),rt.some(Yn=>"hash"in Yn)&&Pt(g,rt))}ut.set(g,ge),be&&(it===null&&(En+=1,gn=`tools:${En}`,it=Date.now(),st=null,Pn=null),Nt.push(g))},Ai=async g=>{try{let w=await y.request("hydra-acp/session/tool_content",{sessionId:he,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},ad=new Set,Lv=(g,w)=>{ad.has(g)||w.oldRef===void 0&&w.newRef===void 0||(ad.add(g),(async()=>{let[k,C]=await Promise.all([w.oldRef?Ai(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?Ai(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&k===null||w.newRef!==void 0&&C===null){ad.delete(g);let Ee=bf(w,"diff",{deferredStatus:"error"});Ee.length>0&&(I.upsertLines(`editdiff:${g}`,Ee),I.repaintNow());return}let _={...w.path!==void 0?{path:w.path}:{},oldText:k??"",newText:C??""};vt.set(g,_);let W=ut.get(g);W?.editDiff&&(W.editDiff=_),ad.delete(g);let H=mn.get(g),ee=H===void 0?i.showFileUpdates:H?"diff":"edit";ee!=="none"&&(dd(g,_,ee==="diff"?"diff":"edit"),I.repaintNow())})())},dd=(g,w,k)=>{let C=`editdiff:${g}`,A=bf(w,k);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),k==="diff"&&(w.oldRef!==void 0||w.newRef!==void 0)&&I.notifyWhenVisible(C)},Bv=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),k=vt.get(w);k&&(k.oldRef!==void 0||k.newRef!==void 0)&&Lv(w,k)},Fp=g=>{let w=`editdiff:${g}`,k=i.showFileUpdates,C=ut.get(g),A;if(k==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let W=mn.get(g);A=W!==void 0?W?"diff":"edit":k==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let _=C.editDiff;vt.set(g,_),dd(g,_,A)},Nv=()=>{let g=i.showFileUpdates;for(let[w,k]of vt){let C=`editdiff:${w}`,A=mn.get(w),_=A===void 0?g:A?"diff":"edit";if(_==="none"){I.removeKey(C);continue}dd(w,k,_==="diff"?"diff":"edit")}},Dv=g=>{if(!g.path)return null;let w=yt(g.oldText).split(`
244
+ `),process.exit(1)}),process.on("exit",e=>{e!==0&&oe({src:"process-exit",code:e})})}async function Cv(n){gE();let e=await xe(),t=n.target??await Dt(e);if(gh(e.tui.logMaxBytes),t.isLocal&&!n.target&&await cr(e),n.agentId)try{let p=await Yr(t),h=Pa(n.agentId,p.map(m=>m.id));h!==void 0&&h!==n.agentId&&(n.agentId=h)}catch{}let s=rE.terminal;Qb(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:zp(e),defaultEnterAction:e.tui.defaultEnterAction,...n.agentId?{lastChosenAgent:n.agentId}:{}},o=Cp(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(yr(),s.fullscreen(!1),a=!1,process.stdout.write(`
245
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=n;try{for(;u!==null;)u=await wE(s,e,t,u,r,i,o)}finally{mv("hydra_session"),d(),process.off("exit",l)}let f=await Ba();if(f&&process.stderr.write(`\u2728 ${Na(f)}
246
+ `),process.stdout.isTTY){let p=await zr(e);if(p?.version!==void 0){let h=p.version!==ye,m=ir(e),y=p.configDigest!==void 0&&p.configDigest!==m;if(h||y){let w=h?`daemon ${p.version} \u2260 cli ${ye}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${w} \u2014 run \`${Qn()} daemon restart\` to apply.`)+`
247
+ `)}}}if(r.sessionId&&process.stdout.isTTY){let p=ft(r.sessionId),h=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Qn()} --session ${p}${h}
248
+ `)}}function yE(n){let{order:e,states:t,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=n,c=e.length,d=a>0,l;if(!d||n.expanded)l=e;else{let M=Math.max(0,c-a),D=e.slice(M),B=[];for(let O=0;O<M;O++){let K=e[O];if(K===void 0)continue;let X=t.get(K);X&&!kf(X.status)&&B.push(K)}l=[...B,...D]}let u=c-l.length,f=r===null,p=r??Date.now(),h=p-s,m=!f&&i!==null&&i!=="end_turn"?i:null,y=m==="amended",w=y?`amended \xB7 ${as(h)}`:`stopped (${m}) \xB7 ${as(h)}`,v;if(c===0)m!==null?v=w:v=f?`thinking \xB7 ${as(h)}`:`thought \xB7 ${as(h)}`;else{let M=c===1?"tool":"tools",D=m!==null?w:f?as(h):`took ${as(h)}`,B=[`${c} ${M}`,D];f&&d&&u>0&&B.push(`${u} hidden`),v=B.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":m!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":m!==null?x:"dim"}],N=[null];for(let M of l){let D=t.get(M);if(D){let B=Ea(D,p);for(let O of B)O.hoverSubKey=M;if($.push(...B),N.push(...B.map(()=>M)),o?.has(M)){let O=Ky(D);for(let K of O)K.hoverSubKey=M;$.push(...O),N.push(...O.map(()=>M))}}}return{lines:$,rowOwners:N}}async function wE(n,e,t,s,r,i,o){let a=await bE(n,e,t,s,o,i);if(!a)return n.grabInput(!1),oe({src:"grab",site:"runSession.picker-aborted",on:!1}),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":a.isFreshFork?"Forking session\u2026":"Resuming session\u2026",d=s.installStatus;s.installStatus&&delete s.installStatus;let l=a.installStatus??d??vl(c,iv(n));l.write(c);let u=t.isLocal?async()=>(await Dt(await xe())).wsUrl:t.wsUrl,f=["acp.v1",`hydra-acp-token.${t.token}`],p=null,h=null,m=new Po({url:u,subprotocols:f,onConnect:async g=>{g||p&&await p()},onDisconnect:g=>{h&&h(g)},log:g=>oe({src:"resilient-ws",line:g})}),y=new Kt(m);await m.start(),y.onNotification(Cd,g=>{let b=Xh.safeParse(g);b.success&&l.applyProgress(b.data)});let w=[],v=null,S=!1,x=!1,T=(g,b)=>{g&&(v?v(g,b):w.push({event:g,rawUpdate:b}))},E,$=g=>{g!==E&&(E=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},N=null,M=null,D=!1,B=0,O=0,K=!1,X=!1,Z,Q=null,fe=null,Me=null,In=null,De=()=>setInterval(()=>{if(Q===null||G===null)return;let g=In===null?0:Date.now()-In;G.setBanner({elapsedMs:Date.now()-Q,stalled:g>=pE}),mt()},1e3),us=!1,Se=g=>{let b=O;O=Math.max(0,O+g);let k=typeof G<"u"&&G!==null;b===0&&O>0?(X=!1,Q=Date.now(),In=Date.now(),Ie?.setTurnRunning(!0),k&&G.setBanner({status:"busy",elapsedMs:0,stalled:!1}),fe===null&&k&&(fe=De())):b>0&&O===0?(X=!1,Q=null,In=null,Ie?.setTurnRunning(!1),fe!==null&&(clearInterval(fe),fe=null),k&&G.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):O>0&&X&&(X=!1,k&&G.setBanner({status:"busy",stalled:!1}))},G=null,Ie=null,je,Yt=null,Os=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction","clarifier_question_asked","clarifier_question_answered","clarifier_question_dismissed"]),un=g=>{let{update:b}=g??{},k=ns(b,{cwd:qe});vE(b,k),In=Date.now();let C=b?.sessionUpdate;if(typeof C=="string"&&!Os.has(C)){let A=b??{};typeof A.messageId=="string"&&(je=A.messageId)}if(C==="prompt_received"?Se(1):k?.kind==="turn-complete"&&(Se(-1),D=!0),C==="permission_resolved"){Bo(b);return}if(C==="hydra_compaction"){Lo(b);return}if(C==="clarifier_question_asked"){let A=b,_=typeof A.question?.question=="string"?A.question.question:"",W=_.length>50?_.slice(0,49)+"\u2026":_;I.notify(W?`new question: ${W} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(T(k,b),ed(b))};y.onNotification("session/update",g=>{if(!S){if(Yt!==null){Yt.push(g);return}un(g)}}),y.onNotification("hydra-acp/session/closed",()=>{if(S)return;O>0&&Se(-O),typeof G<"u"&&G!==null&&G.setBanner({status:"cold",elapsedMs:void 0})});let wt=new Map,Ls=200,Bs=0,fs=!1,ai=4e3;y.onNotification("hydra-acp/prompt_queue/added",g=>{if(S)return;let b=g??{};if(typeof b.messageId!="string")return;if(typeof b._meta?.["hydra-acp"]?.amending=="string"){let C=b.messageId,A=b.prompt,_=setTimeout(()=>{S||(wt.delete(C),Y.set(C,U(C,A)),G&&Ie&&Ze())},Ls);wt.set(C,_)}else Y.set(b.messageId,U(b.messageId,b.prompt)),G&&Ie&&Ze();if(Ds!==void 0&&b.originator?.clientId===Ds){let C=re.shift();C&&(C.messageId=b.messageId,ie.set(b.messageId,C))}}),y.onNotification("hydra-acp/prompt_queue/updated",g=>{if(S)return;let b=g??{};if(typeof b.messageId!="string"||!Y.has(b.messageId))return;Y.set(b.messageId,U(b.messageId,b.prompt));let k=ie.get(b.messageId);if(k){let C=Array.isArray(b.prompt)?b.prompt:[],A="",_=[];for(let W of C){if(!W||typeof W!="object")continue;let H=W;H.type==="text"&&typeof H.text=="string"?A+=H.text:H.type==="image"&&typeof H.data=="string"&&typeof H.mimeType=="string"&&_.push({data:H.data,mimeType:H.mimeType,sizeBytes:Math.floor(H.data.length*3/4)})}k.text=A,k.attachments=_}G&&Ie&&Ze()}),y.onNotification("hydra-acp/prompt_queue/removed",g=>{if(S)return;let b=g??{};if(typeof b.messageId!="string")return;b.reason==="started"&&(Z=b.messageId);let k=wt.get(b.messageId);k!==void 0&&(clearTimeout(k),wt.delete(b.messageId)),Y.delete(b.messageId)&&G&&Ie&&Ze();let A=ie.get(b.messageId);A&&(ie.delete(b.messageId),b.reason==="started"&&(A.flushed=!0,T({kind:"user-text",text:A.displayText,attachments:A.attachments}),Ce=A))}),y.onNotification("hydra-acp/cancel_failed",g=>{if(S)return;let b=g??{};if(!(typeof G<"u"&&G!==null))return;Bs=Date.now(),fs=!0;let C=typeof b.code=="number"?` (${b.code})`:"",A=typeof b.message=="string"&&b.message.length>0?`: ${b.message}`:"";G.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"}])}),y.onNotification("hydra-acp/prompt/amended",g=>{if(S)return;let b=g??{};if(typeof b.cancelledMessageId!="string")return;let k=b.cancelledMessageId;we.add(k),Ce!==null&&Ce.messageId!==void 0&&Ce.messageId===k&&(T({kind:"turn-complete",stopReason:"cancelled",amended:!0}),Ce=null,we.delete(k))});let Lo=g=>{let b=g??{},k=typeof b.phase=="string"?b.phase:void 0;if(k==="started")I.setCompactionIndicator("compacting...");else if(k==="iteration")I.setCompactionIndicator("compacting...");else if(k==="deferred")I.setCompactionIndicator("compaction queued (waiting for idle)");else if(k==="swapped")I.setCompactionIndicator(null),I.notify("compacted",2e3);else if(k==="rolled_back")I.setCompactionIndicator(null),I.notify("rolled back",2e3);else if(k==="failed"){I.setCompactionIndicator(null);let C=typeof b.error=="string"?b.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;I.notify(`compaction failed: ${A}`,5e3)}},xn=()=>{Me===null&&(Me=setInterval(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let b=await g.json();b.forkSynthesisState===void 0?(I.setSynthesisIndicator(null),I.notify("synthesis complete",2e3),Me!==null&&(clearInterval(Me),Me=null)):b.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3),Me!==null&&(clearInterval(Me),Me=null))}catch{}},5e3))},Za=()=>{Me!==null&&(clearInterval(Me),Me=null)},Bo=g=>{let b=g??{},k=typeof b.toolCallId=="string"?b.toolCallId:void 0,C;b.outcome&&typeof b.outcome=="object"?C=b.outcome:typeof b.chosenOptionId=="string"&&(C={kind:"selected",optionId:b.chosenOptionId}),Ns(k,C?{outcome:C}:void 0)},me=null,Ns=(g,b)=>{if(!me||me.toolCallId&&g&&me.toolCallId!==g)return;let k=me.resolve;me=null,I.setPermissionPrompt(null),k(b??{outcome:{outcome:"cancelled"}})},ed=g=>{if(!me?.toolCallId)return;let b=g??{};b.sessionUpdate!=="tool_call"&&b.sessionUpdate!=="tool_call_update"||b.toolCallId===me.toolCallId&&(!b.status||b.status==="pending"||Ns(b.toolCallId,void 0))},di=()=>{if(!me){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:me.title,detail:me.detail,options:me.options.map(g=>({label:g.name})),selectedIndex:me.selectedIndex})},ci=g=>{if(!me)return;let{options:b,resolve:k}=me;if(me=null,I.setPermissionPrompt(null),g===null){k({outcome:{outcome:"cancelled"}});return}k({outcome:{outcome:"selected",optionId:g}})};y.onRequest("session/request_permission",async g=>{if(S)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return ni(g);let b=g??{},C=(Array.isArray(b.options)?b.options:[]).map(ee=>({optionId:ee.optionId,name:Pe(ee.name??""),...ee.kind!==void 0?{kind:ee.kind}:{}})),A=b.toolCall?.title??b.toolCall?.name??"tool",_=Pe(A),W=Pe(Kw(zw(g))),H=b.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${_} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(ee=>{me={title:_,detail:W,options:C,selectedIndex:0,resolve:ee,toolCallId:H},di()})}),y.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let li,Ct,ps=!0,An=!1;try{let g=await y.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ye}});Ct=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ps=!1),An=rn(g?._meta??void 0).prompt?.amending===!0}catch{}let he=a.sessionId,Ke=a.agentId,qe=a.cwd,gt,Ds,hs,ms,ui,Hs,gs,Lt,fi,Hn,No=!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 b={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[$t]:g}}:{}},k;try{k=await Lw({request:()=>y.request("session/new",b),showBanner:(_,W,H)=>Bw(n,_,W,H,{authenticate:ee=>y.request("authenticate",{methodId:ee})}),resolveOnboarding:async _=>{if(_)try{return(await Yr(t)).find(ee=>ee.id===_)?.onboarding}catch{return}},fallbackAgentId:s.agentId})}catch(_){n.grabInput(!1),oe({src:"grab",site:"runSession.session-new-failed",on:!1}),m.close().catch(()=>{});let W=_ instanceof Error?_.message:String(_);oe({src:"session-new-failed",agentId:s.agentId??null,message:W});let H=await cv(n,s.agentId,W,{canGoBack:!s.forceNew});if(H==="cancel")return null;let ee={...s};return delete ee.sessionId,delete ee.resume,H==="retry"?ee.forceNew=!0:(delete ee.forceNew,delete ee.agentId),ee}if(k.kind==="cancel")return n.grabInput(!1),oe({src:"grab",site:"runSession.auth-cancel",on:!1}),m.close().catch(()=>{}),null;if(k.kind==="back"){n.grabInput(!1),oe({src:"grab",site:"runSession.auth-back",on:!1}),m.close().catch(()=>{});let _={...s};return delete _.sessionId,delete _.forceNew,delete _.resume,delete _.agentId,_}let C=k.result;l.write(c),he=C.sessionId,Tp("hydra_session",he),r.sessionId=he,r.readonly=!1;let A=rn(C._meta??void 0);A.clientId&&(Ds=A.clientId),li=A.upstreamSessionId,A.agentId&&(Ke=A.agentId),A.cwd&&(qe=A.cwd),A.title&&(gt=A.title),hs=A.currentModel,ms=A.currentMode,fi=A.currentUsage,Hn=A.turnStartedAt,A.availableCommands&&(ui=ic(A.availableCommands)),A.availableModes&&(Hs=A.availableModes),gs=kv(C.configOptions),Lt=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 b=await y.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:ye},...Object.keys(g).length>0?{_meta:{[$t]:g}}:{}});he=b.sessionId,Tp("hydra_session",he),b.clientId&&(Ds=b.clientId),r.sessionId=he,r.readonly=s.readonly===!0;let k=rn(b._meta??void 0);No=k.resurrected===!0,li=k.upstreamSessionId,k.agentId&&(Ke=k.agentId),k.cwd&&(qe=k.cwd),k.title&&(gt=k.title),hs=k.currentModel,ms=k.currentMode,fi=k.currentUsage,Hn=k.turnStartedAt,k.availableCommands&&(ui=ic(k.availableCommands)),k.availableModes&&(Hs=k.availableModes),gs=kv(b.configOptions),Lt=k.queue}let Us=L.tuiHistoryFile(he),pi=L.globalTuiHistoryFile(),Rt=await ca(Us).catch(()=>[]),Vt=await ca(pi).catch(()=>[]);Vt.length>e.tui.promptHistoryMaxEntries&&(Vt=Vt.slice(Vt.length-e.tui.promptHistoryMaxEntries));let Un=[...Rt],Re=new _s({history:Hd(Vt,Un)});Ie=Re;let td=!1,$e=(g,b)=>{let k=g.replace(/\n+$/,"");if(k.length===0)return;let C=(b??g).replace(/\n+$/,""),A=la(Rt,k),_=A!==Rt;Rt=A,Un=la(Un,C);let W=la(Vt,k,e.tui.promptHistoryMaxEntries),H=W!==Vt;Vt=W,Re.setHistory(Hd(Vt,Un)),_&&jr(Us,Rt).catch(()=>{}),H&&Qm(pi,k).catch(()=>{})};O>0&&Re.setTurnRunning(!0);let Tt=null,jn=null;Jb(Yb(e.tui.ambiguousWidth,process.env)),Yy(e.tui.diffContextLines);let Qt=!1,I,qn=()=>{Qt&&(Qt=!1,I.start())},fn=()=>{Qt||(Qt=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",qn);let js=null,hi=null;I=new pl({term:n,dispatcher:Re,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"?fn:void 0,onBlockClick:(g,b)=>{zv(g,b)},onBlockDoubleClick:(g,b)=>Wv(g,b),onHydraLinkClick:g=>(Ii(g),!0),onBlockVisible:g=>{Uv(g)},onHoverRun:g=>{if(!g.startsWith("thought:"))return null;let b=Er.get(g);if(b!==void 0&&b.length>0)return new Set(b);let k=I.contiguousRun(g,new Set(Ys.keys()));return k.length>0?new Set(k):null},onMouse:g=>{if(g.button==="left"&&g.kind==="press"){js=I.bannerHitAt(g.x,g.y),hi=js?{x:g.x,y:g.y}:null;return}if(g.button==="left"&&g.kind==="release"){let k=hi,C=js;if(hi=null,js=null,C!==null&&k!==null&&k.x===g.x&&k.y===g.y&&I.bannerHitAt(g.x,g.y)===C){if(C==="mode"){Bt(!0);return}let A=C==="pick"?{type:"switch-session"}:C==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&Pp(A))return;Cr(A);return}}if(g.kind!=="press"||g.button!=="middle")return;let b={type:"attachment-request",source:"primary"};s.readonly===!0&&Pp(b)||Cr(b)},onKey:g=>{for(let b of g){if(K&&bi(b)){b.type==="key"&&oe({src:"key-swallowed",site:"compactionPrompt",name:b.name});continue}if(me&&sd(b)){b.type==="key"&&oe({src:"key-swallowed",site:"permission",name:b.name});continue}if(rd(b)){b.type==="key"&&oe({src:"key-swallowed",site:"help",name:b.name});continue}if(Kn(b)){b.type==="key"&&oe({src:"key-swallowed",site:"questions",name:b.name});continue}if(Si(b)){b.type==="key"&&oe({src:"key-swallowed",site:"options",name:b.name});continue}if(nd(b)){b.type==="key"&&oe({src:"key-swallowed",site:"scrollbackSearch",name:b.name});continue}if(Al(b)){b.type==="key"&&oe({src:"key-swallowed",site:"completion",name:b.name});continue}if(ws(b)){b.type==="key"&&oe({src:"key-swallowed",site:"btwClose",name:b.name});continue}if(b.type==="key"&&b.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(b.type==="attachment-paths"){xi(b.paths);continue}if(b.type==="key"&&vr(b.name)){oe({src:"key-swallowed",site:"userHotkey",name:b.name});continue}let k=Re.feed(b);for(let C of k)s.readonly===!0&&Pp(C)||Cr(C)}qt(),I.setBannerSearchIndicator(Re.state().historySearchQuery),I.setAttachments(Re.state().attachments),I.refreshPrompt()}}),G=I,I.setStickyBottomKey("plan");let Do=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt> (no args toggles the last overlay)"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],br=ui??[],Wn=Hs??[],Ho=gs??[],mi=()=>Ho.find(g=>g.id==="agent"),Xe=()=>{let g=new Set,b=[];for(let k of[...Do,...br])g.has(k.name)||(g.add(k.name),b.push(k));return b},Uo=()=>{let g=Re.state().buffer,b=g[0]??"";if(!b.startsWith("/"))return[];if(g.length>1)return[];let k=b.indexOf(" "),C=k===-1?b:b.slice(0,k);if(C.lastIndexOf("/")>0)return[];let A=Xe().filter(_=>_.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},ys=[],qt=()=>{let g=Uo();if(g.length>0){ys=[],I.setCompletions(g);return}I.setCompletions(ys)},Al=g=>{if(g.type!=="key"||g.name!=="tab")return ys.length>0&&(ys=[]),!1;let b=Uo();if(I.isOverlayOpen()&&b.length===0)return I.toggleFocusedPane(),!0;if(b.length>0){ys=[];let k=Re.state().buffer[0]??"",C=ev({matches:b.map(A=>A.name),firstLine:k});return C===null||Re.replaceFirstLine(C),!0}return bt()},bt=()=>{let g=Re.state(),b=g.buffer[g.row]??"",k=wl(b,g.col);if(k===null)return!1;let C=bl(k.token,qe);return C===null?!1:(C.replacement!==k.token&&Re.replaceRangeOnCurrentLine(k.start,g.col,C.replacement),ys=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},ws=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay(),!0),nd=g=>{if(!I.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&I.isScrolledBack()?(I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let b=I.scrollbackSearchTerm()+g.ch;return I.updateScrollbackSearchTerm(b),!0}if(g.type==="paste"){let b=I.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return I.updateScrollbackSearchTerm(b),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return I.advanceScrollbackSearch(),!0;case"ctrl-s":return I.retreatScrollbackSearch(),!0;case"backspace":{let b=I.scrollbackSearchTerm();return b.length===0?I.cancelScrollbackSearch():I.updateScrollbackSearchTerm(b.slice(0,-1)),!0}case"enter":return I.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return I.cancelScrollbackSearch(),!0;default:return!0}return!0},sd=g=>{if(!me)return!1;let b=me.options;if(g.type==="key")switch(g.name){case"up":return me.selectedIndex=Math.max(0,me.selectedIndex-1),di(),!0;case"down":return me.selectedIndex=Math.min(b.length-1,me.selectedIndex+1),di(),!0;case"enter":{let k=b[me.selectedIndex];return k&&ci(k.optionId),!0}case"escape":case"ctrl-c":return ci(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let k=parseInt(g.ch,10)-1,C=b[k];return C&&ci(C.optionId),!0}return!0},vr=g=>{let b=e.tui.hotkeys[g];return b?(uv(b,{sessionId:he,cwd:qe,agentId:Ke||Ct||"",baseUrl:t.baseUrl,tokenFile:L.authToken()},{notify:k=>I.notify(k),cwd:qe,emitLines:k=>{I.appendLines(k.map(C=>{let A;switch(C.style){case"meta":A="dim";break;case"stderr":case"error":A="tool-status-fail";break;default:A="info"}return{prefix:" ",body:C.text,bodyStyle:A}}))}}),!0):!1},jo=Ke||Ct||"?",Gt={...fi??{}};l.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:jo,cwd:qe,sessionId:he,title:gt,model:hs,usage:{...Gt}}),ms&&I.setBanner({currentMode:ms}),Ba().then(g=>{g&&I.notify(`\u2728 ${Na(g)}`,3e4)}).catch(()=>{});let lt=null,Sr=new Promise(g=>{lt=g}),gi=()=>{y.notify("session/cancel",{sessionId:he}).catch(()=>{})},yi=()=>{G!==null&&O===1&&(X=!0,G.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},kr=()=>{if(Tt){Tt.cancel(),yi();return}if(O>0){gi(),yi();return}wi()},wi=()=>{Zt(0)},qo=()=>{let g="enqueue prompt (sends now, or queues during a turn)",b="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",b],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",b]],...hE]},Wo=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:qo(),hint:"any key dismisses \xB7 /help lists commands"})},Ir=()=>{K=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=he;fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}}).catch(()=>{})},Cn=()=>{K=!1,I.setCompactionPrompt(null)},bs=g=>{let b=I.compactionPromptSpec();if(!b)return;let k=b.options.length;if(k===0)return;let C=((b.selectedIndex+g)%k+k)%k;C!==b.selectedIndex&&I.setCompactionPrompt({...b,selectedIndex:C})},bi=g=>{if(!K)return!1;if(g.type==="key"){if(g.name==="escape")return Cn(),!0;if(g.name==="up")return bs(-1),!0;if(g.name==="down")return bs(1),!0;if(g.name==="enter"){let b=I.compactionPromptSpec();return b?.options[b.selectedIndex]?.key==="y"?Ir():Cn(),!0}}if(g.type==="char"){let b=g.ch.toLowerCase();if(b==="y"||b==="1")return Ir(),!0;if(b==="n"||b==="2")return Cn(),!0}return!0},rd=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,qs=["tools","plan","thoughts","diffs","mouse","enter"],Rn=0,Tn=null,vs=[],Wt=[],pn=[],Ws=0,xr=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"}},Cl=()=>({title:"Session options",options:qs.map(g=>({label:vi(g),value:xr(g)})),selectedIndex:Rn}),Xt=()=>{I.isOptionsPromptActive()&&Tn===null&&I.setOptionsPrompt(Cl())},Rl=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Rn=0,I.setOptionsPrompt(Cl())},hn=()=>{if(Tn===null)return;let g=cE(Tn,vs,pn,Ws);I.setOptionsPrompt(g)},zn=()=>{Tn=null,vs=[],Wt=[],pn=[],Ws=0,I.setOptionsPrompt(null)},id=async()=>{if(Tn!==null){zn();return}try{let b=await y.request(mb,{sessionId:he}),k=iE(b.questions??[]);if(k.length===0){I.notify("no open questions");return}let C=aE(k);Tn=C,Ws=0,vs=C.map(A=>oE(A.representative)),Wt=C.map(()=>!1),pn=C.map(()=>!1),hn()}catch(g){I.notify("clarifier unavailable"),oe({src:"questions",step:"list_failed",error:g.message})}},od=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,Rr.clear(),Ai.clear(),Gs();break;case"plan":i.planExpanded=!i.planExpanded,Vs=null,Mr();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",mn.clear(),jv();break;case"mouse":{let b=!I.isMouseEnabled();I.setMouseEnabled(b),i.mouseEnabled=b;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}Xt()},Ar=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${vi(g)} is session-only \u2014 not saved`);return;case"thoughts":await Yo("showThoughts",i.showThoughts);break;case"diffs":await Yo("showFileUpdates",i.showFileUpdates);break;case"mouse":await Yo("mouse",i.mouseEnabled);break;case"enter":await Yo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${vi(g)} ${xr(g)}`)}catch(b){I.notify(`save failed: ${b instanceof Error?b.message:String(b)}`)}})()},Si=g=>{if(Tn!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Rn=Math.max(0,Rn-1),Xt(),!0;case"down":return Rn=Math.min(qs.length-1,Rn+1),Xt(),!0;case"enter":{let b=qs[Rn];return b&&od(b),!0}case"ctrl-o":case"escape":case"ctrl-c":return I.setOptionsPrompt(null),!0;case"ctrl-d":return I.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let b=parseInt(g.ch,10)-1,k=qs[b];return k&&(Rn=b,od(k)),!0}if(g.ch==="s"||g.ch==="S"){let b=qs[Rn];return b&&Ar(b),!0}}return!0},Kn=g=>{if(Tn===null)return!1;let b=fE(g,!0,Tn,vs,Wt,pn,Ws,he);switch(b.type){case"noop":return!0;case"row":return Ws=b.selectedRow,hn(),!0;case"cycle":return vs[b.selectedRow]=b.newValueIndex,Wt[b.selectedRow]=!0,pn[b.selectedRow]=!1,hn(),!0;case"dismiss-toggle":{let k=b.selectedRow;return pn[k]?(pn[k]=!1,Wt[k]=!1):(pn[k]=!0,Wt[k]=!0),hn(),!0}case"discard":return zn(),!0;case"save":{let k=b.dispatches;return zn(),k.length===0||(async()=>{let C=0,A=0,_=0;for(let H of k)try{await y.request(H.method,H.params),H.type==="dismiss"?A++:C++}catch(ee){_++,oe({src:"questions",step:"dispatch_failed",method:H.method,error:ee.message})}let W=[];C>0&&W.push(`${C} answered`),A>0&&W.push(`${A} dismissed`),_>0&&W.push(`${_} failed`),W.length>0&&I.notify(`clarifier: ${W.join(", ")}`)})(),!0}}return!1},ki=()=>{S=!0,N?(N.cancel(),N=null,M=null):M!==null&&(os(t,M).catch(()=>{}),M=null),process.off("SIGINT",kr),process.platform!=="win32"&&process.off("SIGCONT",qn),fe!==null&&(clearInterval(fe),fe=null),Me!==null&&(clearInterval(Me),Me=null);for(let g of wt.values())clearTimeout(g);wt.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),jr(Us,Rt).catch(()=>{}),m.close().catch(()=>{})},Zt=(g=0)=>{ki(),lt&&(lt(null),lt=null),g!==0&&process.exit(g)},zs=async()=>{if(oe({src:"switch-session",step:"entered",finishSessionNull:lt===null}),!lt)return;N?(N.cancel(),N=null,M=null):M!==null&&(os(t,M).catch(()=>{}),M=null),Za(),I.setSynthesisIndicator(null);let g=Re.state().buffer.join(`
249
+ `);g.replace(/\s+$/,"").length>0&&$e(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),jr(Us,Rt).catch(()=>{});let b=!1;try{let k=null,C=null;for(;k===null;){let H=await is(t,{includeNonInteractive:!0}),ee=s.agentId??i.lastChosenAgent??e.defaultAgent,Ee=ee?e.defaultModels?.[ee]:void 0,be=[];try{be=await Yr(t)}catch{}let ae=await Rp(n,{cwd:qe,sessions:H,config:e,target:t,currentSessionId:he,prefs:o,...ee?{composerAgentId:ee}:{},...Ee?{composerModel:Ee}:{},...be.length>0?{availableAgents:be}:{}});if(ae.kind==="abort")return;if(ae.kind==="exit"){b=!0,Zt(0);return}if(ae.kind==="new"){k={choice:ae,sessions:H};break}if(ae.kind==="fork"){let Mn=await Ev(n,t,ae,H);if(Mn.kind==="cancel")return;if(Mn.kind==="back")continue;k={choice:{kind:"attach",sessionId:Mn.ctx.sessionId,...Mn.ctx.agentId?{agentId:Mn.ctx.agentId}:{}},sessions:H},C={readonly:!1,cwd:Mn.ctx.cwd},Mn.ctx.resumeHint!==void 0&&(C.resumeHint=Mn.ctx.resumeHint);break}let ge=H.find(Mn=>Mn.sessionId===ae.sessionId);if(!(ge!==void 0&&!!ge.importedFromMachine&&!ge.upstreamSessionId&&ae.readonly!==!0)){if(t.isLocal&&ge&&!ge.importedFromMachine&&ae.readonly!==!0&&!(await Ha(ge.cwd)).ok){ae.installStatus?.finalize(),delete ae.installStatus;let Ko=await ii(n,ge,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Ko.kind==="cancel")return;if(Ko.kind==="back")continue;k={choice:ae,sessions:H},C={readonly:!1,cwd:Ko.path,resumeHint:{agentId:ae.agentId??ge.agentId??"",cwd:Ko.path,upstreamSessionId:""}};break}k={choice:ae,sessions:H};break}let Vn={...s,readonly:!1};ae.installStatus?.finalize(),delete ae.installStatus;let zo=await Rv(n,t,ge,ae,Vn);if(zo.kind==="cancel")return;zo.kind!=="back"&&(k={choice:ae,sessions:H},C={readonly:Vn.readonly===!0,cwd:zo.ctx.cwd},zo.ctx.resumeHint!==void 0&&(C.resumeHint=zo.ctx.resumeHint))}let{choice:A}=k,_=lt;if(lt=null,process.off("SIGINT",kr),m.close().catch(()=>{}),b=!0,A.kind==="new"){let{sessionId:H,agentId:ee,...Ee}=s,be={...Ee,cwd:A.cwd??qe,forceNew:!0,readonly:!1};A.prompt!==void 0&&(be.initialPrompt=A.prompt),A.attachments&&A.attachments.length>0&&(be.initialAttachments=A.attachments),A.agentId!==void 0&&(be.agentId=A.agentId,i.lastChosenAgent=A.agentId),A.model!==void 0&&(be.model=A.model),A.installStatus!==void 0&&(be.installStatus=A.installStatus),_(be);return}if(A.kind!=="attach")return;let W={...s,sessionId:A.sessionId,cwd:C?.cwd??qe,readonly:C?.readonly??A.readonly===!0};A.agentId!==void 0&&(W.agentId=A.agentId),C?.resumeHint!==void 0?W.resumeHint=C.resumeHint:delete W.resumeHint,A.installStatus!==void 0?W.installStatus=A.installStatus:delete W.installStatus,_(W)}finally{!b&&lt&&(I.start({skipFullscreen:!0}),I.resumeRepaint())}},zt=async(g="next")=>{if(!lt)return;let k=(await is(t)).filter(be=>be.status==="warm");if(k.length<=1)return;let C=k.findIndex(be=>be.sessionId===he),W=((C===-1?0:C)+(g==="prev"?-1:1)+k.length)%k.length,H=k[W],ee=lt;lt=null,process.off("SIGINT",kr),m.close().catch(()=>{});let Ee={...s,sessionId:H.sessionId,cwd:qe,readonly:!1};H.agentId!==void 0&&(Ee.agentId=H.agentId),ee(Ee)},Ii=async g=>{if(!lt)return;let b=await is(t,{includeNonInteractive:!0}),k=g.trim();if(!k){I.notify("usage: /session <id|next|prev>");return}let C=k.startsWith(Ut)?[k]:[k,Ut+k],A=b.find(H=>C.includes(H.sessionId));if(!A){let H=b.filter(ee=>C.some(Ee=>ee.sessionId.startsWith(Ee)));if(H.length===1)A=H[0];else if(H.length>1){I.notify(`ambiguous session id: ${k} (${H.length} matches)`);return}}if(!A){I.notify(`no session matches: ${k}`);return}if(A.sessionId===he){I.notify("already on that session");return}let _=lt;lt=null,process.off("SIGINT",kr),m.close().catch(()=>{});let W={...s,sessionId:A.sessionId,cwd:A.cwd??qe,readonly:!1};A.agentId!==void 0&&(W.agentId=A.agentId),delete W.resumeHint,_(W)},Cr=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Ks(g.text,g.attachments,g.displayText):Ve(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ve(g.text,g.attachments,g.displayText):Ks(g.text,g.attachments,g.displayText);return;case"queue-edit":{let b=ht(g.index);if(!b)return;let k=[];g.text.length>0&&k.push({type:"text",text:g.text});for(let C of g.attachments)k.push({type:"image",data:C.data,mimeType:C.mimeType});y.request("hydra-acp/prompt/update",{sessionId:he,messageId:b,prompt:k}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&I.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{I.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let b=ht(g.index);if(!b)return;y.request("hydra-acp/prompt/cancel",{sessionId:he,messageId:b}).then(k=>{let C=k;!C.cancelled&&C.reason!=="ok"&&I.notify(`queue cancel skipped (${C.reason})`)}).catch(k=>{I.notify(`queue cancel failed: ${k.message}`)});return}case"cancel":{if(I.isOverlayOpen()){N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay();return}if(g.prefill&&Tt){let b=Y.size===0,k=Re.state().buffer.every(C=>C==="");b&&k&&(jn={text:Tt.text,attachments:Tt.attachments})}Tt?Tt.cancel():O>0&&gi(),yi();return}case"exit":wi();return;case"plan-toggle":Bt(g.on);return;case"redraw-banner":I.setBanner({});return;case"redraw":I.fullRedraw();return;case"scroll-to-top":I.scrollToTop();return;case"scroll-to-bottom":I.scrollToBottom();return;case"switch-session":zs().catch(b=>{oe({src:"switch-session-failed",stack:b instanceof Error?b.stack??b.message:String(b)})});return;case"next-live-session":zt().catch(()=>{});return;case"toggle-options":Rl();return;case"toggle-questions":id();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts),I.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let b=!I.isMouseEnabled();I.setMouseEnabled(b),i.mouseEnabled=b,I.notify(b?"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":Wo();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":R(g.source);return}},xi=async g=>{if(!ps){I.notify("agent does not accept image attachments");return}let b=0;for(let k of g){if(k.startsWith("data:")){let A=Xf(k);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>cs){I.notify(`image too large (${kn(A.sizeBytes)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),b++;continue}let C=ja(k);if(!C){I.notify(`unsupported image type: ${oi.basename(k)}`);continue}try{let A=await Ep.readFile(k);if(A.length>cs){I.notify(`image too large (${kn(A.length)}, max ${kn(cs)})`);continue}Re.addAttachment({mimeType:C,data:A.toString("base64"),name:oi.basename(k),sizeBytes:A.length}),b++}catch(A){I.notify(`cannot read ${oi.basename(k)}: ${A.message}`)}}b>0&&(I.setAttachments(Re.state().attachments),I.refreshPrompt())},R=async(g="clipboard")=>{let b=g==="primary"?await Cb():await ol();if(!b.ok){I.notify(b.reason);return}if(b.kind==="image"){if(!ps){I.notify("agent does not accept image attachments");return}Re.addAttachment(b.attachment),I.setAttachments(Re.state().attachments),I.refreshPrompt();return}let k=Re.feed({type:"paste",text:b.text});for(let C of k)Cr(C);I.refreshPrompt()},P=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,U=(g,b)=>{let k=Array.isArray(b)?b:[],C="",A=0;for(let _ of k){if(!_||typeof _!="object")continue;let W=_;W.type==="text"&&typeof W.text=="string"?C+=W.text:W.type==="image"&&(A+=1)}return{messageId:g,text:Pe(C),attachmentCount:A}},Y=new Map,re=[],ie=new Map,we=new Set,Ce=null,Ze=()=>{let g=[...Y.values()],b=g.map(P);I.setQueuedPrompts(b),I.setBanner({queued:g.length}),Re.setQueue(g.map(k=>k.text))},ht=g=>[...Y.values()][g]?.messageId;if(Lt&&Lt.length>0){for(let g of Lt){if(g.position===0){Z=g.messageId;continue}Y.set(g.messageId,U(g.messageId,g.prompt))}Y.size>0&&Ze()}let Ve=(g,b,k)=>{I.scrollToBottom(),!Ss(g)&&($e(g,k),ks(g,b,k))},Ks=(g,b,k)=>{if(I.scrollToBottom(),Ss(g))return;if($e(g,k),!An||Z===void 0){ks(g,b,k);return}let C=Z,A=[];g.length>0&&A.push({type:"text",text:g});for(let H of b)A.push({type:"image",data:H.data,mimeType:H.mimeType});let _={text:g,displayText:k??g,attachments:b,flushed:!1};re.push(_);let W=()=>{let H=re.indexOf(_);H>=0&&re.splice(H,1),_.messageId!==void 0&&ie.delete(_.messageId)};y.request("hydra-acp/prompt/amend",{sessionId:he,targetMessageId:C,prompt:A}).then(H=>{let ee=H;if(ee.amended&&ee.reason==="ok"){Se(1);return}if(W(),ee.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),Re.setBuffer(g,b),I.refreshPrompt();return}if(ee.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),Re.setBuffer(g,b),I.refreshPrompt();return}if(ee.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),Re.setBuffer(g,b),I.refreshPrompt();return}}).catch(H=>{W(),I.notify(`amend failed: ${H.message}`),Re.setBuffer(g,b),I.refreshPrompt()})},Bt=async g=>{if(Wn.length===0){I.notify("no modes advertised by agent");return}let b=I.currentModeId(),k=Wn.findIndex(_=>_.id===b),C=k===-1?0:(k+1)%Wn.length,A=Wn[C]?.id;if(A){I.setBanner({currentMode:A});try{await y.request("session/set_mode",{sessionId:he,modeId:A})}catch(_){I.notify(`set_mode failed: ${_.message}`)}}},Ss=g=>{let b=g.replace(/\s+$/,"");if(!b.startsWith("/")||b.includes(`
250
+ `))return!1;let k=b.indexOf(" ");switch(k===-1?b:b.slice(0,k)){case"/quit":case"/exit":return wi(),!0;case"/clear":return ut.clear(),Js.clear(),Nt.length=0,it=null,st=null,Pn=null,vt.clear(),mn.clear(),en.clear(),Rr.clear(),Ys.clear(),Er.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let _ of Do)A.push({prefix:" ",body:` ${_.name.padEnd(12)} ${_.description??""}`,bodyStyle:"info"});if(br.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let _ of br)A.push({prefix:" ",body:` ${_.name.padEnd(12)} ${_.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=k===-1?"":b.slice(k+1).trim(),_=mi();if(!_)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let H=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let ee of _.options){let Ee=ee.value===_.currentValue?"* ":" ";H.push({prefix:" ",body:`${Ee}${ee.value.padEnd(16)} ${ee.name}`,bodyStyle:"info"})}return I.appendLines(H),!0}let W=_.options.find(H=>H.value===A)?.value;if(!W){let H=A.toLowerCase(),ee=_.options.filter(Ee=>Ee.value.toLowerCase().startsWith(H));ee.length===1&&(W=ee[0].value)}return W?W===_.currentValue?(I.notify(`already on agent ${W}`),!0):(I.notify(`switching to ${W}\u2026`),y.request("session/set_config_option",{sessionId:he,configId:"agent",value:W}).catch(H=>{I.notify(`set_config_option failed: ${H.message}`)}),!0):(I.notify(`unknown agent: ${A}`),!0)}case"/sessions":return I.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return zs().catch(A=>{oe({src:"switch-session-failed",stack:A instanceof Error?A.stack??A.message:String(A)})}),!0;case"/session":{let A=k===-1?"":b.slice(k+1).trim();return A?A==="next"||A==="prev"?(zt(A).catch(_=>{I.notify(`session ${A} failed: ${_.message}`)}),!0):(Ii(A).catch(_=>{I.notify(`session switch failed: ${_.message}`)}),!0):(zs().catch(_=>{oe({src:"switch-session-failed",stack:_ instanceof Error?_.stack??_.message:String(_)})}),!0)}case"/rename":{let A=k===-1?"":b.slice(k+1).trim(),_=A.length>0?`/hydra title ${A}`:"/hydra title";return $e(b,b),ks(_,[],b),!0}case"/btw":{let A=k===-1?"":b.slice(k+1).trim();if(!A)return I.isOverlayOpen()?(N&&(N.cancel(),N=null,M=null),I.closeBtwOverlay(),!0):(I.reopenBtwOverlay()||I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0);if(he==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;B+=1;let _=B;N&&(N.cancel(),N=null);let W=null;M!==null&&!D?W=M:M!==null&&(os(t,M).catch(()=>{}),M=null),D=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let H=new sl({getMaxWidth:()=>{let ae=I.width();return ae>0?ae:void 0}});H.on("changed",()=>{I.setBtwOverlayContent(H.getLines())});let ee={};H.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Ee=ae=>{H.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ae}})},be={};return W!==null&&(be.reuseSessionId=W),bb(t,he,A,be).then(ae=>{if(_!==B){ae.cancel();return}N=ae,M=ae.sessionId,I.setBtwOverlayMeta({sessionId:ae.sessionId}),ae.on("event",ge=>{if(_===B)if(ge.kind==="update"){H.append(ge.update);let rt=ns(ge.update);if(rt&&rt.kind==="usage-update"){let Vn=!1;rt.used!==void 0&&ee.used!==rt.used&&(ee.used=rt.used,Vn=!0),rt.size!==void 0&&ee.size!==rt.size&&(ee.size=rt.size,Vn=!0),rt.costAmount!==void 0&&ee.costAmount!==rt.costAmount&&(ee.costAmount=rt.costAmount,Vn=!0),rt.costCurrency!==void 0&&ee.costCurrency!==rt.costCurrency&&(ee.costCurrency=rt.costCurrency,Vn=!0),Vn&&I.setBtwOverlayMeta({usage:{...ee}})}}else ge.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),N=null):ge.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),N=null,M=null):ge.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw errored: ${ge.error.message}`),M!==null&&os(t,M).catch(()=>{}),N=null,M=null)})}).catch(ae=>{if(_!==B)return;let ge=ae instanceof Error?ae.message:String(ae);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ee(`btw startup failed: ${ge}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ge}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(he==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=k===-1?"":b.slice(k+1).trim(),_=he;return(async()=>{try{let W=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(_)}/transcript`,{headers:{Authorization:`Bearer ${t.token}`}});if(!W.ok){let ge=await W.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${W.status} ${ge}`.trim(),bodyStyle:"info"}]);return}let H=await W.text(),ee=new Date().toISOString().replace(/[:.]/g,"-"),Ee=`hydra-${ft(_)}-${ee}.md`,be=A.length>0?et(A):Ee,ae=oi.resolve(be);await Ep.mkdir(oi.dirname(ae),{recursive:!0}),await Ep.writeFile(ae,H,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${ae}`,bodyStyle:"system"}])}catch(W){I.appendLines([{prefix:" ",body:`/export failed: ${W.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},ks=async(g,b,k)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let be of b)C.push({type:"image",data:be.data,mimeType:be.mimeType});Se(1);let A={text:g,displayText:k??g,attachments:b,flushed:!1};re.push(A),fs=!1;let _=!1,W=null,H=be=>{typeof G<"u"&&G!==null&&G.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:be,bodyStyle:"tool-status-fail"}])},ee=!1;Tt={text:g,attachments:b,cancel:()=>{if(fs){fs=!1,ee=!0,H("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),y.request("hydra-acp/session/force_cancel",{sessionId:he}).catch(ae=>{H(`force-stop failed: ${ae.message}`)});return}if(_)return;_=!0,y.notify("session/cancel",{sessionId:he}).catch(()=>{});let be=Date.now();W=setTimeout(()=>{Tt!==null&&(Bs>=be||(fs=!0,H("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},ai)}};let Ee;try{let be=await y.request("session/prompt",{sessionId:he,prompt:C});be&&typeof be.stopReason=="string"&&(Ee=be.stopReason)}catch(be){let ae=re.indexOf(A);ae>=0&&re.splice(ae,1),A.messageId!==void 0&&ie.delete(A.messageId),ee?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:be.message,bodyStyle:"tool-status-fail"}])}finally{if(Tt=null,W!==null&&(clearTimeout(W),W=null),Se(-1),A.flushed&&Ce===A){let be=A.messageId!==void 0&&we.has(A.messageId);be&&A.messageId!==void 0&&we.delete(A.messageId);let ae={kind:"turn-complete"};Ee!==void 0&&(ae.stopReason=Ee),be&&(ae.amended=!0),T(ae),Ce=null}if(jn!==null){let{text:be,attachments:ae}=jn;jn=null,Re.state().buffer.every(rt=>rt==="")&&(Re.setBuffer(be,ae),I.refreshPrompt())}}},ut=new Map,vt=new Map,mn=new Map,Js=new Map,Nt=[],En=0,gn=`tools:${En}`,en=new Map,Rr=new Map,Ai=new Set,Tr=new Map,Ys=new Map,Er=new Map,it=null,st=null,Pn=null,Jn=null,Vs=null,Tl=e.tui.maxToolItems,El=e.tui.maxPlanItems,Pr=()=>({maxPlanItems:Vs??i.planExpanded?1/0:El}),Mr=()=>{if(Jn===null)return;let g=fr(Jn,Pr());g.length>0&&I.upsertLines("plan",[{body:""},...g])},Qs="",F=null,z=0,ue=()=>{if(F===null)return;let g=I.width(),b=pr(Qs,g>0?{maxWidth:g}:void 0);b.length!==0&&I.upsertLines(F,b)},J=g=>{g.length!==0&&(F===null&&(I.ensureSeparator(),F=`agent:${z}`,z+=1,Qs=""),Qs+=g,ue())},de=()=>{F=null,Qs=""},ce="",Te=null,He=0,We=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),ot=()=>{if(Te===null||ce.length===0)return;let g=ko(ce);g.length!==0&&I.upsertLines(Te,g)},tn=g=>{let b=Ys.get(g);if(b===void 0)return[];let k=ko(b.text);return b.workerTaskId&&k.unshift({prefix:" ",body:`[T${b.workerTaskId}] `,bodyStyle:"dim"}),k},Yn=(g,b)=>{g.length!==0&&(Te===null&&(I.ensureSeparator("thought"),Te=`thought:${He}`,He+=1,ce=""),ce+=g,Ys.set(Te,{text:ce,workerTaskId:b}),ot())},ze=()=>{Te=null,ce=""},Ue=g=>yE({...g,collapsedLimit:Tl}),St=g=>Rr.get(g)??i.toolsExpanded,mt=()=>{if(it===null)return;let{lines:g,rowOwners:b}=Ue({order:Nt,states:ut,startedAt:it,endedAt:st,stopReason:Pn,expanded:St(gn),perToolExpanded:Ai});I.upsertLines(gn,g),Tr.set(gn,b)},Et=g=>{let b=en.get(g);if(!b)return;let{lines:k,rowOwners:C}=Ue({order:b.order,states:b.states,startedAt:b.startedAt,endedAt:b.endedAt,stopReason:b.stopReason,expanded:St(g),perToolExpanded:Ai});I.upsertLines(g,k),Tr.set(g,C)},Gs=()=>{it!==null&&!en.has(gn)&&mt();for(let g of en.keys())Et(g)},Is=()=>{it!==null&&en.set(gn,{order:[...Nt],states:new Map(ut),startedAt:it,endedAt:st??Date.now(),stopReason:Pn,rowOwners:Tr.get(gn)??[]})},ad=()=>{En+=1,gn=`tools:${En}`,it=Date.now(),st=null,Pn=null,mt()};function Pl(g){if(!g||typeof g!="object")return null;let b=g,k=Array.isArray(b.content)?b.content:void 0;if(!k)return null;let C=[],A=_=>{if(typeof _=="string"){C.push({text:yt(_)});return}if(_&&typeof _=="object"){let W=_;typeof W.__hydraBlob=="string"&&C.push({hash:W.__hydraBlob})}};for(let _ of k){if(!_||typeof _!="object")continue;let W=_;if(W.type==="content"&&W.content&&typeof W.content=="object"){let H=W.content;if(H.text!==void 0){A(H.text);continue}}if(W.type==="text"&&W.text!==void 0){A(W.text);continue}W.text!==void 0&&A(W.text)}return C.length>0?C:null}let Ci=(g,b)=>{let k=b.map(_=>"text"in _?_.text:"").join(`
251
+ `);if(k.length===0)return;let{text:C,truncated:A}=zy(k);g.resultText=C,g.resultTruncated=A},Le=new Set,Pt=(g,b)=>{!b.some(C=>"hash"in C)||Le.has(g)||(Le.add(g),(async()=>{let C=await Promise.all(b.map(async _=>"text"in _?_:{text:await Ri(_.hash)??""}));Le.delete(g);let A=ut.get(g);if(!A)for(let _ of en.values()){let W=_.states.get(g);if(W){A=W;break}}if(A){Ci(A,C),ut.has(g)&&mt();for(let[_,W]of en)W.states.has(g)&&Et(_);I.repaintNow()}})().catch(()=>{Le.delete(g)}))},Xs=(g,b,k,C,A,_,W,H,ee,Ee)=>{let be=!ut.has(g),ae=ut.get(g),ge=ae??{initialTitle:b??"tool",latestTitle:b??"tool",status:k??"pending",startedAt:Date.now()};if(!ae&&ee!==void 0&&(ge.workerTaskId=ee),ae&&b!==void 0&&(ge.latestTitle=b),_!==void 0&&ge.detail===void 0&&(ge.detail=_),W!==void 0&&ge.detailFull===void 0&&(ge.detailFull=W),H!==void 0&&H.length>0&&(ge.locations=H),ae&&k!==void 0&&(ge.status=k),ae||(ge.status=k??"pending"),ge.endedAt===void 0&&kf(ge.status)&&(ge.endedAt=Date.now()),C!==void 0&&(ge.errorText=C),A!==void 0&&(ge.editDiff=A),Ee!==void 0){let rt=Pl(Ee);rt!==null&&(Ci(ge,rt),rt.some(Vn=>"hash"in Vn)&&Pt(g,rt))}ut.set(g,ge),be&&(it===null&&(En+=1,gn=`tools:${En}`,it=Date.now(),st=null,Pn=null),Nt.push(g))},Ri=async g=>{try{let b=await y.request("hydra-acp/session/tool_content",{sessionId:he,hash:g});return typeof b?.content=="string"?b.content:null}catch{return null}},dd=new Set,Hv=(g,b)=>{dd.has(g)||b.oldRef===void 0&&b.newRef===void 0||(dd.add(g),(async()=>{let[k,C]=await Promise.all([b.oldRef?Ri(b.oldRef.hash):Promise.resolve(b.oldText),b.newRef?Ri(b.newRef.hash):Promise.resolve(b.newText)]);if(b.oldRef!==void 0&&k===null||b.newRef!==void 0&&C===null){dd.delete(g);let Ee=vf(b,"diff",{deferredStatus:"error"});Ee.length>0&&(I.upsertLines(`editdiff:${g}`,Ee),I.repaintNow());return}let _={...b.path!==void 0?{path:b.path}:{},oldText:k??"",newText:C??""};vt.set(g,_);let W=ut.get(g);W?.editDiff&&(W.editDiff=_),dd.delete(g);let H=mn.get(g),ee=H===void 0?i.showFileUpdates:H?"diff":"edit";ee!=="none"&&(cd(g,_,ee==="diff"?"diff":"edit"),I.repaintNow())})())},cd=(g,b,k)=>{let C=`editdiff:${g}`,A=vf(b,k);if(A.length===0){I.removeKey(C);return}I.upsertLines(C,A),k==="diff"&&(b.oldRef!==void 0||b.newRef!==void 0)&&I.notifyWhenVisible(C)},Uv=g=>{if(!g.startsWith("editdiff:"))return;let b=g.slice(9),k=vt.get(b);k&&(k.oldRef!==void 0||k.newRef!==void 0)&&Hv(b,k)},Bp=g=>{let b=`editdiff:${g}`,k=i.showFileUpdates,C=ut.get(g),A;if(k==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let W=mn.get(g);A=W!==void 0?W?"diff":"edit":k==="diff"?"diff":"edit"}if(A===null){I.removeKey(b);return}let _=C.editDiff;vt.set(g,_),cd(g,_,A)},jv=()=>{let g=i.showFileUpdates;for(let[b,k]of vt){let C=`editdiff:${b}`,A=mn.get(b),_=A===void 0?g:A?"diff":"edit";if(_==="none"){I.removeKey(C);continue}cd(b,k,_==="diff"?"diff":"edit")}},qv=g=>{if(!g.path)return null;let b=yt(g.oldText).split(`
252
252
  `),k=yt(g.newText).split(`
253
- `),C=0,A=Math.min(w.length,k.length);for(;C<A&&w[C]===k[C];)C++;let _=k[C];if(!_)return null;let W=ri.isAbsolute(g.path)?g.path:ri.resolve(qe,g.path),H;try{H=XT(W,"utf8")}catch{return null}let ee=H.split(`
254
- `);for(let Ee=0;Ee<ee.length;Ee++)if(ee[Ee]===_)return Ee+1;return null},Hv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=vt.get(k),_=ut.get(k)?.locations?.[0],W=_?.path??C?.path;if(!W)return!1;let H=null;_?.line!==void 0?H=_.line:C&&(H=Dv(C));let ee=H===null?"":`:${H}`;return I.tryOpenPathString(W+ee)}if(g.startsWith("tools:")){if(w===0)return!1;let k=Ar.get(g),C=k?k[w]:void 0;if(!C)return!1;let A=ut.get(C),_=A?.locations?.[0];if(_){let H=_.line===void 0?"":`:${_.line}`;if(I.tryOpenPathString(_.path+H))return!0}let W=A?.detailFull??A?.detail;if(W)return I.tryOpenPathString(W)}return!1},Uv=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=vt.get(k);if(!C)return;let A=mn.get(k)??i.showFileUpdates==="diff";mn.set(k,!A),dd(k,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(Kn===null)return;Js=!(Js??i.planExpanded),Tr(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=xr.get(g)??i.toolsExpanded;xr.set(g,!A),g===gn&&it!==null?mt():Et(g),I.repaintNow();return}let k=Ar.get(g);if(!k)return;let C=k[w];if(!C)return;lE(C,Ii),Et(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Ks.has(g))return;let k=Cr.get(g);if(k!==void 0){Cr.delete(g),I.setRunCollapsed(k,!1,tn(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Ks.keys()));if(C.length===0)return;let A=C[0];Cr.set(A,C),I.setRunCollapsed(C,!0,[We()]),I.repaintNow();return}};v=(g,w)=>{if(g.kind==="available-commands"){gr=g.commands,qt();return}if(g.kind==="available-modes"){qn=g.modes;return}if(g.kind==="config-options"){Do=g.options;let C=g.options.find(_=>_.id==="agent");C&&C.currentValue&&C.currentValue!==Ke&&(Ke=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(_=>_.id==="mode");A&&(qn=A.options.map(_=>({id:_.value,name:_.name??_.value,..._.description!==void 0?{description:_.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Ke&&(Ke=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Gt.used!==g.used&&(Gt.used=g.used,C=!0),g.size!==void 0&&Gt.size!==g.size&&(Gt.size=g.size,C=!0),g.costAmount!==void 0&&Gt.costAmount!==g.costAmount&&(Gt.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Gt.costCurrency!==g.costCurrency&&(Gt.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...Gt}});return}if(g.kind==="user-text"){ed&&$e(g.text),de(),ze(),it!==null&&(st=Date.now(),mt()),Ce=null,I.ensureSeparator();let C=lr(g);C.length>0&&I.appendLines(C),Ss(),I.clearKey("plan"),Kn=null,Js=null,ut.clear(),zs.clear(),Nt.length=0,st=null,od(),I.redraw();return}if(g.kind==="agent-text"){ze(),F===null&&$(g.workerTaskId),J(g.text);return}if(g.kind==="agent-thought"){de(),Te===null&&$(g.workerTaskId),Jn(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),ze();let C=zs.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(zs.set(g.toolCallId,A),A.plan.length===0)return;let _=Jy(A);_.length>0&&I.upsertLines(g.toolCallId,_);return}if(g.kind==="tool-call"){de(),ze(),ut.has(g.toolCallId)||$(g.workerTaskId),Qs(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),mt(),Fp(g.toolCallId);return}if(g.kind==="plan"){de(),ze(),Kn=g;let C=lr(g,Rr());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(_=>(_.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){de(),ze(),Qs(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(cs=!0),mt(),Fp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let k=lr(g);if(k.length>0&&I.appendLines(k),g.kind==="turn-complete"){Z=void 0,de(),ze();let C=g.amended?"amended":g.stopReason;if(!g.amended&&cs&&(C===void 0||C==="end_turn")&&(C="error"),Kn!==null&&C!==void 0&&C!=="end_turn"){let A=lr({...Kn,stopped:!0,amended:g.amended===!0},Rr());A.length>0&&I.upsertLines("plan",[{body:""},...A])}Kn=null,Js=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),it!==null?(st=Date.now(),Pn=C??null,mt(),Ss()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),ut.clear(),zs.clear(),Nt.length=0,it=null,st=null,Pn=null,cs=!1,I.ensureSeparator(),hv({pendingTurns:O,queueSize:Y.size,ownTurnInFlight:Tt!==null,hasInFlightHead:Z!==void 0,replayDraining:x,amended:g.amended===!0})&&Se(-O)}};let Op=b;b=[];let cd=[];for(let{event:g}of Op)g.kind==="user-text"&&typeof g.text=="string"&&cd.push(g.text);I.pauseRepaint(),x=!0;try{for(let{event:g,rawUpdate:w}of Op)v(g,w)}finally{x=!1,I.resumeRepaint()}if(cd.length>0){let g=Hu(Rt,cd);g!==Rt&&(Rt=g,Hn=Hu(Hn,cd),Re.setHistory(Dd(Vt,Hn)),Dr(Ds,Rt).catch(()=>{}))}ed=!0,(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let w=await g.json(),k=w.compactionState?.status;if(k==="requested"||k==="running"?I.setCompactionIndicator("compacting..."):(k==="swap_pending"||k==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!Bo||w.shouldCompact!==!0)return;let C=w.approxTokens??0;K=!0,I.setCompactionPrompt({message:`This session has ~${fg(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let w=await g.json();w.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),xn()):w.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Dn!==void 0&&O>0?(Q=Dn,I.setBanner({status:"busy",elapsedMs:Date.now()-Dn}),fe===null&&(fe=De()),it===null&&od(),it=Dn,mt()):Dn===void 0&&O>0&&Se(-O);let jv=()=>{if(me){let g=me.resolve;me=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),ze()},Lp=()=>{it!==null&&(st=Date.now(),Pn="reconnect-recovery-failed",mt(),Ss(),ut.clear(),zs.clear(),Nt.length=0,it=null,st=null,Pn=null)};return h=g=>{oe({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},p=async()=>{if(oe({src:"reconnect",step:"begin",sessionId:he}),t.isLocal)try{let H=await Dt(await xe());(H.baseUrl!==t.baseUrl||H.wsUrl!==t.wsUrl)&&(oe({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:H.baseUrl}),t.baseUrl=H.baseUrl,t.wsUrl=H.wsUrl,t.display=H.display)}catch(H){oe({src:"reconnect",step:"target-refresh-failed",message:H instanceof Error?H.message:String(H)})}jv();let g={jsonrpc:"2.0",id:`tui-reinit-${yv()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ye}}};oe({src:"reconnect",step:"initialize-send"});try{await m.request(g),oe({src:"reconnect",step:"initialize-ok"})}catch(H){oe({src:"reconnect",step:"initialize-fail",message:H.message})}let w=je!==void 0,k={jsonrpc:"2.0",id:`tui-reattach-${yv()}`,method:"session/attach",params:{sessionId:he,historyPolicy:w?"after_message":"none",...w?{afterMessageId:je}:{},clientInfo:{name:"hydra-acp-tui",version:ye},...(()=>{let H={};return di!==void 0&&(H.resume={upstreamSessionId:di,agentId:Ke,cwd:qe}),e.tui.toolContent==="references"&&(H.toolContent="references"),Object.keys(H).length>0?{_meta:{[$t]:H}}:{}})()}};Yt=[];let C,A,_;oe({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:je});try{let H=await m.request(k);if(oe({src:"reconnect",step:"attach-resp",hasError:!!H.error}),H.error)throw new Error(H.error.message);_=pv(H.result),C=_.appliedPolicy,_.clientId!==void 0&&(Bs=_.clientId)}catch(H){A=H,oe({src:"reconnect",step:"attach-fail",message:A.message})}let W=Yt??[];if(Yt=null,A)Lp(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")Lp(),I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{x=!0;try{for(let H of W)un(H)}finally{x=!1}}if(_){let H=mv({daemonTurnStartedAt:_.turnStartedAt,pendingTurns:O});H.pendingTurnsDelta!==0&&Se(H.pendingTurnsDelta),H.banner==="busy"&&H.busySince!==void 0?(Q=H.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-H.busySince}),fe===null&&(fe=De())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:O>0?"busy":"ready",elapsedMs:O>0?0:void 0});oe({src:"reconnect",step:"end"})},y.onClose(g=>{g&&n.red(`
253
+ `),C=0,A=Math.min(b.length,k.length);for(;C<A&&b[C]===k[C];)C++;let _=k[C];if(!_)return null;let W=oi.isAbsolute(g.path)?g.path:oi.resolve(qe,g.path),H;try{H=sE(W,"utf8")}catch{return null}let ee=H.split(`
254
+ `);for(let Ee=0;Ee<ee.length;Ee++)if(ee[Ee]===_)return Ee+1;return null},Wv=(g,b)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=vt.get(k),_=ut.get(k)?.locations?.[0],W=_?.path??C?.path;if(!W)return!1;let H=null;_?.line!==void 0?H=_.line:C&&(H=qv(C));let ee=H===null?"":`:${H}`;return I.tryOpenPathString(W+ee)}if(g.startsWith("tools:")){if(b===0)return!1;let k=Tr.get(g),C=k?k[b]:void 0;if(!C)return!1;let A=ut.get(C),_=A?.locations?.[0];if(_){let H=_.line===void 0?"":`:${_.line}`;if(I.tryOpenPathString(_.path+H))return!0}let W=A?.detailFull??A?.detail;if(W)return I.tryOpenPathString(W)}return!1},zv=(g,b)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=vt.get(k);if(!C)return;let A=mn.get(k)??i.showFileUpdates==="diff";mn.set(k,!A),cd(k,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(Jn===null)return;Vs=!(Vs??i.planExpanded),Mr(),I.repaintNow();return}if(g.startsWith("tools:")){if(b===0){let A=Rr.get(g)??i.toolsExpanded;Rr.set(g,!A),g===gn&&it!==null?mt():Et(g),I.repaintNow();return}let k=Tr.get(g);if(!k)return;let C=k[b];if(!C)return;mE(C,Ai),Et(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!Ys.has(g))return;let k=Er.get(g);if(k!==void 0){Er.delete(g),I.setRunCollapsed(k,!1,tn(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(Ys.keys()));if(C.length===0)return;let A=C[0];Er.set(A,C),I.setRunCollapsed(C,!0,[We()]),I.repaintNow();return}};v=(g,b)=>{if(g.kind==="available-commands"){br=g.commands,qt();return}if(g.kind==="available-modes"){Wn=g.modes;return}if(g.kind==="config-options"){Ho=g.options;let C=g.options.find(_=>_.id==="agent");C&&C.currentValue&&C.currentValue!==Ke&&(Ke=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(_=>_.id==="mode");A&&(Wn=A.options.map(_=>({id:_.value,name:_.name??_.value,..._.description!==void 0?{description:_.description}:{}})));return}if(g.kind==="mode-changed"){I.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&I.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Ke&&(Ke=g.agentId,I.setSessionbar({agent:g.agentId})),g.pendingAgentSwap!==void 0&&(typeof g.pendingAgentSwap=="string"?I.setCompactionIndicator(`switching to ${g.pendingAgentSwap}...`):(I.setCompactionIndicator(null),g.agentId!==void 0&&I.notify(`switched to ${g.agentId}`,2e3)));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&Gt.used!==g.used&&(Gt.used=g.used,C=!0),g.size!==void 0&&Gt.size!==g.size&&(Gt.size=g.size,C=!0),g.costAmount!==void 0&&Gt.costAmount!==g.costAmount&&(Gt.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&Gt.costCurrency!==g.costCurrency&&(Gt.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...Gt}});return}if(g.kind==="user-text"){td&&$e(g.text),de(),ze(),it!==null&&(st=Date.now(),mt()),Ce=null,I.ensureSeparator();let C=fr(g);C.length>0&&I.appendLines(C),Is(),I.clearKey("plan"),Jn=null,Vs=null,ut.clear(),Js.clear(),Nt.length=0,st=null,ad(),I.redraw();return}if(g.kind==="agent-text"){ze(),F===null&&$(g.workerTaskId),J(g.text);return}if(g.kind==="agent-thought"){de(),Te===null&&$(g.workerTaskId),Yn(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){de(),ze();let C=Js.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(Js.set(g.toolCallId,A),A.plan.length===0)return;let _=Gy(A);_.length>0&&I.upsertLines(g.toolCallId,_);return}if(g.kind==="tool-call"){de(),ze(),ut.has(g.toolCallId)||$(g.workerTaskId),Xs(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,b),mt(),Bp(g.toolCallId);return}if(g.kind==="plan"){de(),ze(),Jn=g;let C=fr(g,Pr());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(_=>(_.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){de(),ze(),Xs(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,b),g.upstreamInterrupted&&(us=!0),mt(),Bp(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let k=fr(g);if(k.length>0&&I.appendLines(k),g.kind==="turn-complete"){Z=void 0,de(),ze();let C=g.amended?"amended":g.stopReason;if(!g.amended&&us&&(C===void 0||C==="end_turn")&&(C="error"),Jn!==null&&C!==void 0&&C!=="end_turn"){let A=fr({...Jn,stopped:!0,amended:g.amended===!0},Pr());A.length>0&&I.upsertLines("plan",[{body:""},...A])}Jn=null,Vs=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),it!==null?(st=Date.now(),Pn=C??null,mt(),Is()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),ut.clear(),Js.clear(),Nt.length=0,it=null,st=null,Pn=null,us=!1,I.ensureSeparator(),wv({pendingTurns:O,queueSize:Y.size,ownTurnInFlight:Tt!==null,hasInFlightHead:Z!==void 0,replayDraining:x,amended:g.amended===!0})&&Se(-O)}};let Np=w;w=[];let ld=[];for(let{event:g}of Np)g.kind==="user-text"&&typeof g.text=="string"&&ld.push(g.text);I.pauseRepaint(),x=!0;try{for(let{event:g,rawUpdate:b}of Np)v(g,b)}finally{x=!1,I.resumeRepaint()}if(ld.length>0){let g=Uu(Rt,ld);g!==Rt&&(Rt=g,Un=Uu(Un,ld),Re.setHistory(Hd(Vt,Un)),jr(Us,Rt).catch(()=>{}))}td=!0,(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}/compact/status`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let b=await g.json(),k=b.compactionState?.status;if(k==="requested"||k==="running"?I.setCompactionIndicator("compacting..."):(k==="swap_pending"||k==="swap_deferred")&&I.setCompactionIndicator("compaction queued (waiting for idle)"),!No||b.shouldCompact!==!0)return;let C=b.approxTokens??0;K=!0,I.setCompactionPrompt({message:`This session has ~${mg(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),(async()=>{try{let g=await fetch(`${t.baseUrl}/v1/sessions/${encodeURIComponent(he)}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!g.ok)return;let b=await g.json();b.forkSynthesisState==="running"?(I.setSynthesisIndicator("synthesizing context\u2026"),xn()):b.forkSynthesisState==="failed"&&(I.setSynthesisIndicator("\u26A0 synthesis failed"),I.notify("synthesis failed \u2014 fork still usable via recall",8e3))}catch{}})(),Hn!==void 0&&O>0?(Q=Hn,I.setBanner({status:"busy",elapsedMs:Date.now()-Hn}),fe===null&&(fe=De()),it===null&&ad(),it=Hn,mt()):Hn===void 0&&O>0&&Se(-O);let Kv=()=>{if(me){let g=me.resolve;me=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}de(),ze()},Dp=()=>{it!==null&&(st=Date.now(),Pn="reconnect-recovery-failed",mt(),Is(),ut.clear(),Js.clear(),Nt.length=0,it=null,st=null,Pn=null)};return h=g=>{oe({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},p=async()=>{if(oe({src:"reconnect",step:"begin",sessionId:he}),t.isLocal)try{let H=await Dt(await xe());(H.baseUrl!==t.baseUrl||H.wsUrl!==t.wsUrl)&&(oe({src:"reconnect",step:"target-refresh",oldBase:t.baseUrl,newBase:H.baseUrl}),t.baseUrl=H.baseUrl,t.wsUrl=H.wsUrl,t.display=H.display)}catch(H){oe({src:"reconnect",step:"target-refresh-failed",message:H instanceof Error?H.message:String(H)})}Kv();let g={jsonrpc:"2.0",id:`tui-reinit-${Sv()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:ye}}};oe({src:"reconnect",step:"initialize-send"});try{await m.request(g),oe({src:"reconnect",step:"initialize-ok"})}catch(H){oe({src:"reconnect",step:"initialize-fail",message:H.message})}let b=je!==void 0,k={jsonrpc:"2.0",id:`tui-reattach-${Sv()}`,method:"session/attach",params:{sessionId:he,historyPolicy:b?"after_message":"none",...b?{afterMessageId:je}:{},clientInfo:{name:"hydra-acp-tui",version:ye},...(()=>{let H={};return li!==void 0&&(H.resume={upstreamSessionId:li,agentId:Ke,cwd:qe}),e.tui.toolContent==="references"&&(H.toolContent="references"),Object.keys(H).length>0?{_meta:{[$t]:H}}:{}})()}};Yt=[];let C,A,_;oe({src:"reconnect",step:"attach-send",useAfterMessage:b,lastSeenMessageId:je});try{let H=await m.request(k);if(oe({src:"reconnect",step:"attach-resp",hasError:!!H.error}),H.error)throw new Error(H.error.message);_=yv(H.result),C=_.appliedPolicy,_.clientId!==void 0&&(Ds=_.clientId)}catch(H){A=H,oe({src:"reconnect",step:"attach-fail",message:A.message})}let W=Yt??[];if(Yt=null,A)Dp(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(b&&C!=="after_message")Dp(),I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{x=!0;try{for(let H of W)un(H)}finally{x=!1}}if(_){let H=bv({daemonTurnStartedAt:_.turnStartedAt,pendingTurns:O});H.pendingTurnsDelta!==0&&Se(H.pendingTurnsDelta),H.banner==="busy"&&H.busySince!==void 0?(Q=H.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-H.busySince}),fe===null&&(fe=De())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:O>0?"busy":"ready",elapsedMs:O>0?0:void 0});oe({src:"reconnect",step:"end"})},y.onClose(g=>{g&&n.red(`
255
255
  connection lost: ${g.message}
256
- `),Zt(g?1:0)}),process.on("SIGINT",br),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&Ve(s.initialPrompt??"",s.initialAttachments??[]),await wr}async function hE(n,e,t,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await Sv(n,t,s,i)!=="ok"?null:vv(s,o,e);if(s.resume){let a=await ss(t,{cwd:o,all:!0}),c=Rc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(n.yellow(`No sessions found for ${o}.
257
- `),null)}for(;;){let a=await ss(t,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await zr(t)}catch{}let u=await xp(n,{cwd:o,sessions:a,config:e,target:t,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(u.kind==="abort"||u.kind==="exit")return null;if(u.kind==="new"){u.agentId!==void 0&&(s.agentId=u.agentId,i.lastChosenAgent=u.agentId),u.model!==void 0&&(s.model=u.model),u.prompt!==void 0&&(s.initialPrompt=u.prompt),u.attachments&&u.attachments.length>0&&(s.initialAttachments=u.attachments),u.cwd!==void 0&&(o=u.cwd,s.cwd=u.cwd);let b=u.installStatus,v=await Sv(n,t,s,i,()=>{b&&(b.finalize(),b=void 0)});if(v==="cancel")return b&&b.finalize(),null;if(v==="back"){b&&b.finalize();continue}let S=vv(s,o,e);return b&&(S.installStatus=b),S}if(u.kind==="fork"){let b=await Av(n,t,u,a);if(b.kind==="cancel")return null;if(b.kind==="back")continue;return b.ctx}s.readonly=u.readonly===!0;let f=u.installStatus,p=()=>{f&&(f.finalize(),f=void 0)},h=a.find(b=>b.sessionId===u.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let b=await Iv(n,t,h,u,s);if(b.kind==="cancel")return null;if(b.kind==="back")continue;return b.ctx}if(t.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await Da(h.cwd)).ok){p();let v=await si(n,h,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(v.kind==="cancel")return null;if(v.kind==="back")continue;let S=u.agentId??h.agentId??"";return{sessionId:u.sessionId,agentId:S,cwd:v.path,resumeHint:{agentId:S,cwd:v.path,upstreamSessionId:""}}}let y={sessionId:u.sessionId,agentId:u.agentId??"",cwd:o};return f&&(y.installStatus=f),y}}async function Iv(n,e,t,s,r){for(;;){let i=await Jb(n,t);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??t.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:t.cwd}}}let o=await xv(n,e,s.agentId??t.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await si(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function xv(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let s;try{s=await zr(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(s.length===0||s.some(i=>i.id===t))return{kind:"ok",agentId:t,changed:!1};let r=await Ha(n,s,t,{title:"Agent not available here",intro:`Source agent "${t}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Av(n,e,t,s){let r=s.find(u=>u.sessionId===t.sourceSessionId),i=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,o=t.sourceCwd,a=await xv(n,e,t.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let u=await si(n,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??t.sourceAgentId??"",l;try{l=await Cc(e,t.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return n.red(`
256
+ `),Zt(g?1:0)}),process.on("SIGINT",kr),a.sessionId==="__new__"&&(s.initialPrompt||s.initialAttachments&&s.initialAttachments.length>0)&&Ve(s.initialPrompt??"",s.initialAttachments??[]),await Sr}async function bE(n,e,t,s,r,i){let o=s.cwd??process.cwd();if(s.sessionId){let a={sessionId:s.sessionId,agentId:s.agentId??"",cwd:o};return s.resumeHint!==void 0&&(a.resumeHint=s.resumeHint),a}if(s.forceNew)return await Av(n,t,s,i)!=="ok"?null:xv(s,o,e);if(s.resume){let a=await is(t,{cwd:o,all:!0}),c=Tc(a,o);return c?{sessionId:c.sessionId,agentId:c.agentId??"",cwd:o}:(n.yellow(`No sessions found for ${o}.
257
+ `),null)}for(;;){let a=await is(t,{includeNonInteractive:!0}),c=s.agentId??i.lastChosenAgent??e.defaultAgent,d=c?e.defaultModels?.[c]:void 0,l=[];try{l=await Yr(t)}catch{}let u=await Rp(n,{cwd:o,sessions:a,config:e,target:t,prefs:r,...c?{composerAgentId:c}:{},...d?{composerModel:d}:{},...l.length>0?{availableAgents:l}:{},...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{},...s.initialAttachments&&s.initialAttachments.length>0?{initialAttachments:s.initialAttachments}:{}});if(u.kind==="abort"||u.kind==="exit")return null;if(u.kind==="new"){u.agentId!==void 0&&(s.agentId=u.agentId,i.lastChosenAgent=u.agentId),u.model!==void 0&&(s.model=u.model),u.prompt!==void 0&&(s.initialPrompt=u.prompt),u.attachments&&u.attachments.length>0&&(s.initialAttachments=u.attachments),u.cwd!==void 0&&(o=u.cwd,s.cwd=u.cwd);let w=u.installStatus,v=await Av(n,t,s,i,()=>{w&&(w.finalize(),w=void 0)});if(v==="cancel")return w&&w.finalize(),null;if(v==="back"){w&&w.finalize();continue}let S=xv(s,o,e);return w&&(S.installStatus=w),S}if(u.kind==="fork"){let w=await Ev(n,t,u,a);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}s.readonly=u.readonly===!0;let f=u.installStatus,p=()=>{f&&(f.finalize(),f=void 0)},h=a.find(w=>w.sessionId===u.sessionId);if(h!==void 0&&!!h.importedFromMachine&&!h.upstreamSessionId&&!s.readonly){p();let w=await Rv(n,t,h,u,s);if(w.kind==="cancel")return null;if(w.kind==="back")continue;return w.ctx}if(t.isLocal&&h&&!h.importedFromMachine&&!s.readonly&&!(await Ha(h.cwd)).ok){p();let v=await ii(n,h,{defaultCwd:et(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(v.kind==="cancel")return null;if(v.kind==="back")continue;let S=u.agentId??h.agentId??"";return{sessionId:u.sessionId,agentId:S,cwd:v.path,resumeHint:{agentId:S,cwd:v.path,upstreamSessionId:""}}}let y={sessionId:u.sessionId,agentId:u.agentId??"",cwd:o};return f&&(y.installStatus=f),y}}async function Rv(n,e,t,s,r){for(;;){let i=await Gb(n,t);if(i==="cancel")return{kind:"cancel"};if(i==="back")return{kind:"back"};if(i==="view"){r.readonly=!0;let d=s.agentId??t.agentId??"";return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:d,cwd:t.cwd}}}let o=await Tv(n,e,s.agentId??t.agentId??"");if(o.kind==="cancel")return{kind:"cancel"};if(o.kind==="back")continue;let a=await ii(n,t);if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")continue;let c=o.agentId;return{kind:"ctx",ctx:{sessionId:s.sessionId,agentId:c,cwd:a.path,resumeHint:{agentId:c,cwd:a.path,upstreamSessionId:""}}}}}async function Tv(n,e,t){if(!t)return{kind:"ok",agentId:t,changed:!1};let s;try{s=await Yr(e)}catch{return{kind:"ok",agentId:t,changed:!1}}if(s.length===0||s.some(i=>i.id===t))return{kind:"ok",agentId:t,changed:!1};let r=await Ua(n,s,t,{title:"Agent not available here",intro:`Source agent "${t}" isn't installed on this machine \u2014 pick a local agent to fork to:`});return r.kind==="cancel"?{kind:"cancel"}:r.kind==="back"?{kind:"back"}:{kind:"ok",agentId:r.agentId,changed:!0}}async function Ev(n,e,t,s){let r=s.find(u=>u.sessionId===t.sourceSessionId),i=!!t.sourceImportedFromMachine&&!t.sourceUpstreamSessionId,o=t.sourceCwd,a=await Tv(n,e,t.sourceAgentId??r?.agentId??"");if(a.kind==="cancel")return{kind:"cancel"};if(a.kind==="back")return{kind:"back"};let c=a.changed?a.agentId:void 0;if(i){if(!r)return{kind:"back"};let u=await ii(n,r);if(u.kind==="cancel")return{kind:"cancel"};if(u.kind==="back")return{kind:"back"};o=u.path}let d=c??t.sourceAgentId??"",l;try{l=await Rc(e,t.sourceSessionId,{...i?{cwd:o}:{},...c?{agentId:c}:{}})}catch(u){return n.red(`
258
258
  fork failed: ${u.message}
259
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function vv(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function Sv(n,e,t,s,r){if(t.agentId||await Yp())return"ok";let i;try{i=await zr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await xe(),a=s.lastChosenAgent??o.defaultAgent,c=await Ha(n,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(t.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await Mi(c.agentId)}catch{}return"ok"}function mE(n,e){oe({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Tp,dE,cE,bv,Cv=V(()=>{"use strict";Br();Ft();jf();Qe();Jf();Fr();qr();ya();Vo();hb();Xn();ve();Or();an();Gc();zf();Hd();Aa();gb();yb();rv();Sp();qc();bp();yp();Qf();Uf();ov();gp();Xu();np();sl();ol();dv();fv();ml();vp();gv();rr();So();Tp="dismiss";dE=12e4;cE=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next warm session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];bv=!1});var Rv={};Pl(Rv,{runTui:()=>kv});var Tv=V(()=>{"use strict";Cv()});import{readFileSync as gE}from"fs";import{fileURLToPath as yE}from"url";import{dirname as wE,resolve as bE}from"path";var Bp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),Wv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Np(n){for(let e of Object.keys(n))if(!Bp.has(e)&&!Wv.has(e))return e}function Ml(n){let e=[],t={},s=0;for(;s<n.length;){let r=n[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);t[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(Bp.has(o)){t[o]=!0,s+=1;continue}let a=n[s+1];if(a!==void 0&&!a.startsWith("--")){t[o]=a,s+=2;continue}t[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:t}}function zv(n,e){let t=n[e];if(typeof t=="string")return t}function Ci(n,e){return n[e]===!0||n[e]==="true"}var Kv="HYDRA_ACP_";function Jv(n){return Kv+n.toUpperCase().replace(/-/g,"_")}function kt(n,e){let t=zv(n,e);return t!==void 0?t:process.env[Jv(e)]}Qe();Fr();async function uh(n,e){let t=typeof n=="string"&&n.trim().length>0?n.trim():void 0;if(t===void 0)return;if(t.startsWith("hydra://")){let i=Bl(t);return{target:await ch(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await xe();return{target:await Dt(s),sessionId:t,fromUrl:!1}}function Yl(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_SESSION;if(typeof t=="string"&&t.length>0)return t}Or();ve();Qe();ks();import*as hh from"fs/promises";async function mh(n){if(await hh.mkdir(L.home(),{recursive:!0}),await ud(),!await Ei()){let t=Ti();await Pi(t),process.stdout.write(`Initialized ${L.authToken()}
259
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:l.sessionId,agentId:d,cwd:o,isFreshFork:!0,...i?{resumeHint:{agentId:d,cwd:o,upstreamSessionId:""}}:{}}}}function xv(n,e,t){return{sessionId:"__new__",agentId:n.agentId??t.defaultAgent??"",cwd:e}}async function Av(n,e,t,s,r){if(t.agentId||await Gp())return"ok";let i;try{i=await Yr(e)}catch{return"ok"}if(i.length===0)return"ok";r&&r();let o=await xe(),a=s.lastChosenAgent??o.defaultAgent,c=await Ua(n,i,a);if(c.kind==="cancel")return"cancel";if(c.kind==="back")return"back";if(t.agentId=c.agentId,s.lastChosenAgent=c.agentId,c.persist)try{await $i(c.agentId)}catch{}return"ok"}function vE(n,e){oe({src:"session/update",update:n,event:e===null?null:{kind:e.kind}})}var Mp,pE,hE,Iv,Pv=V(()=>{"use strict";Hr();Ft();qf();Qe();Yf();Br();Kr();wa();Qo();wb();Zn();ve();Nr();an();Xc();Kf();Ud();Ca();vb();Sb();dv();xp();Wc();kp();vp();Gf();jf();lv();bp();Zu();sp();rl();al();fv();gv();gl();Ip();vv();or();Io();Mp="dismiss";pE=12e4;hE=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next warm session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["Right-click","extend selection to click (drag past top/bottom to autoscroll)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];Iv=!1});var Mv={};Ml(Mv,{runTui:()=>Cv});var _v=V(()=>{"use strict";Pv()});import{readFileSync as SE}from"fs";import{fileURLToPath as kE}from"url";import{dirname as IE,resolve as xE}from"path";var Hp=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","tools","raw","reattach","readonly","replace","rotate-token","verbose","version"]),Yv=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function Up(n){for(let e of Object.keys(n))if(!Hp.has(e)&&!Yv.has(e))return e}function _l(n){let e=[],t={},s=0;for(;s<n.length;){let r=n[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);t[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(Hp.has(o)){t[o]=!0,s+=1;continue}let a=n[s+1];if(a!==void 0&&!a.startsWith("--")){t[o]=a,s+=2;continue}t[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:t}}function Vv(n,e){let t=n[e];if(typeof t=="string")return t}function Ti(n,e){return n[e]===!0||n[e]==="true"}var Qv="HYDRA_ACP_";function Gv(n){return Qv+n.toUpperCase().replace(/-/g,"_")}function kt(n,e){let t=Vv(n,e);return t!==void 0?t:process.env[Gv(e)]}Qe();Br();async function hh(n,e){let t=typeof n=="string"&&n.trim().length>0?n.trim():void 0;if(t===void 0)return;if(t.startsWith("hydra://")){let i=Nl(t);return{target:await fh(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await xe();return{target:await Dt(s),sessionId:t,fromUrl:!1}}function Vl(n){let e=n.session;if(typeof e=="string"&&e.length>0)return e;let t=process.env.HYDRA_ACP_SESSION;if(typeof t=="string"&&t.length>0)return t}Nr();ve();Qe();xs();import*as yh from"fs/promises";async function wh(n){if(await yh.mkdir(L.home(),{recursive:!0}),await fd(),!await Mi()){let t=Pi();await _i(t),process.stdout.write(`Initialized ${L.authToken()}
260
260
  Service token: ${t}
261
- `);return}if(Ci(n,"rotate-token")){let t=Ti();await Pi(t),process.stdout.write(`Rotated token in ${L.authToken()}
261
+ `);return}if(Ti(n,"rotate-token")){let t=Pi();await _i(t),process.stdout.write(`Rotated token in ${L.authToken()}
262
262
  New token: ${t}
263
263
  `);return}process.stdout.write(`Service token already exists at ${L.authToken()}.
264
264
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
265
- `)}ve();$i();Qe();ks();import{setTimeout as zA}from"timers/promises";import cy from"chalk";import*as sy from"fs";import*as ao from"fs/promises";import*as ry from"net";import*as iy from"tls";import FA from"fastify";import OA from"@fastify/websocket";var gh="acp.v1";function yh(n,e){return n.has(gh)?gh:!1}Qe();import ny from"pino";import LA from"pino-roll";ve();import*as _t from"fs/promises";import{createHash as $S}from"crypto";import{gzip as FS,gunzip as OS}from"zlib";import{promisify as wh}from"util";var bh=wh(FS),LS=wh(OS),vh=/^[A-Za-z0-9_-]+$/,BS=/^[a-f0-9]{64}$/,Vl=!0;function Sh(n){Vl=n}function gd(n,e){return vh.test(n)?e===void 0||BS.test(e):!1}function yd(n,e){return`${L.toolBlobFile(n,e)}.gz`}async function Ql(n,e){if(!gd(n))return null;let t=$S("sha256").update(e,"utf8").digest("hex"),s=yd(n,t),r=L.toolBlobFile(n,t);for(let a of[s,r])try{return await _t.access(a),t}catch{}await _t.mkdir(L.toolsDir(n),{recursive:!0});let i=Vl?s:r,o=Vl?await bh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await _t.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function wd(n,e){if(!gd(n,e))return null;try{let t=await _t.readFile(yd(n,e));return(await LS(t)).toString("utf8")}catch{}try{return await _t.readFile(L.toolBlobFile(n,e),"utf8")}catch{return null}}async function kh(n,e){if(!gd(n,e))return null;try{return await _t.readFile(yd(n,e))}catch{}try{let t=await _t.readFile(L.toolBlobFile(n,e));return await bh(t)}catch{return null}}async function Ih(n,e,t){if(!gd(n,e))return;let s=yd(n,e);try{await _t.access(s);return}catch{}await _t.mkdir(L.toolsDir(n),{recursive:!0}),await _t.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function xh(n){vh.test(n)&&await _t.rm(L.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}ve();Qe();Pr();Li();import*as Oh from"fs/promises";import*as vd from"path";import{z as le}from"zod";ve();Li();import*as sn from"fs/promises";import*as Qn from"path";import{spawn as WS}from"child_process";var nu=n=>{process.stderr.write(n+`
266
- `)};function su(n){nu=n??(e=>process.stderr.write(e+`
267
- `))}async function Ph(n){let e=wn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentNpmInstallDir(n.agentId,e,n.version),s=VS(n.packageSpec),r=QS(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=Qn.join(t,"node_modules",".bin",n.bin);if(await Lr(o))return o;if(await Lr(t)){let u=await Eh(i);if(u)return u.binPath}await zS({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Eh(i);if(a)return a.binPath;let c=await _h(t,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 ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${l}`)}async function zS(n){await sn.mkdir(Qn.dirname(n.installDir),{recursive:!0});let e=await sn.mkdtemp(`${n.installDir}.partial-`);try{nu(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),tu(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await YS({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await sn.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Lr(n.installDir)){await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),tu(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}nu(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),tu(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function tu(n,e){if(n)try{n(e)}catch{}}var KS=5,JS=25;function YS(n){return Mh(n,0)}async function Mh(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=WS("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.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){t();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${d})
268
- stderr: ${l}`:`npm install ${n.packageSpec} failed (${d})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<KS)return await new Promise(r=>setTimeout(r,JS*(e+1))),Mh(n,e+1);throw t}}function VS(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function QS(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function _h(n,e){let t=Qn.join(n,"node_modules",e,"package.json");try{let s=await sn.readFile(t,"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 Eh(n){let e=Qn.join(n.installDir,"node_modules",".bin"),t=Qn.join(e,n.hint);if(await Lr(t))return{binName:n.hint,binPath:t};let s=await _h(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Qn.join(e,i);if(await Lr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=Qn.join(e,i);if(await Lr(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=Qn.join(e,n.basename);if(await Lr(r))return{binName:n.basename,binPath:r}}}async function Lr(n){try{return await sn.access(n),!0}catch{return!1}}var GS=le.object({package:le.string(),bin:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),Bi=le.object({archive:le.string().url().optional(),cmd:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),XS=le.object({"darwin-aarch64":Bi.optional(),"darwin-x86_64":Bi.optional(),"linux-aarch64":Bi.optional(),"linux-x86_64":Bi.optional(),"windows-x86_64":Bi.optional(),"windows-aarch64":Bi.optional()}),ZS=le.object({package:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ek=le.object({command:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),tk=le.object({command:le.string().optional(),url:le.string().optional(),description:le.string().optional()}),nk=le.object({npx:GS.optional(),binary:XS.optional(),uvx:ZS.optional(),exec:ek.optional()}),sk=le.object({id:le.string(),name:le.string(),version:le.string().optional(),description:le.string().optional(),authors:le.array(le.string()).optional(),license:le.string().optional(),icon:le.string().optional(),repository:le.string().optional(),website:le.string().optional(),distribution:nk,onboarding:tk.optional(),requiredEnv:le.array(le.string().min(1)).optional()}),$h=le.object({version:le.string(),agents:le.array(sk),extensions:le.array(le.unknown()).optional()}),bd=class{constructor(e,t={}){this.config=e;this.options=t}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 t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}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 t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>ru(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:et(t.command??e),args:t.args?.map(et),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:rk(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=$h.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await yn(L.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=$h.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await nn(L.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function rk(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function ru(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ni(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.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 iu(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function iu(n){let e=wn();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Zl(n.distribution.binary,e);if(s?.cmd){let r=vd.resolve(L.agentInstallDir(n.id,e,t),s.cmd);if(await Fh(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??ru(n)??s.package,i=L.agentNpmInstallDir(n.id,e,t),o=vd.join(i,"node_modules",".bin",r);if(await Fh(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Fh(n){try{return await Oh.access(n),!0}catch{return!1}}async function bn(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.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??ru(n)??r.package,a=t.onInstallProgress;return{command:await Ph({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=Zl(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${wn()??"this platform"}.`);let i=t.onInstallProgress,o=await Th({agentId:n.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(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as ck}from"child_process";import*as Rd from"fs";import*as Gh from"path";Ft();function Cd(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
265
+ `)}ve();Oi();Qe();xs();import{setTimeout as QA}from"timers/promises";import py from"chalk";import*as ay from"fs";import*as rs from"fs/promises";import*as dy from"net";import*as lo from"path";import*as cy from"tls";import NA from"fastify";import DA from"@fastify/websocket";var bh="acp.v1";function vh(n,e){return n.has(bh)?bh:!1}Qe();import iy from"pino";import HA from"pino-roll";ve();import*as _t from"fs/promises";import{createHash as BS}from"crypto";import{gzip as NS,gunzip as DS}from"zlib";import{promisify as Sh}from"util";var kh=Sh(NS),HS=Sh(DS),Ih=/^[A-Za-z0-9_-]+$/,US=/^[a-f0-9]{64}$/,Ql=!0;function xh(n){Ql=n}function yd(n,e){return Ih.test(n)?e===void 0||US.test(e):!1}function wd(n,e){return`${L.toolBlobFile(n,e)}.gz`}async function Gl(n,e){if(!yd(n))return null;let t=BS("sha256").update(e,"utf8").digest("hex"),s=wd(n,t),r=L.toolBlobFile(n,t);for(let a of[s,r])try{return await _t.access(a),t}catch{}await _t.mkdir(L.toolsDir(n),{recursive:!0});let i=Ql?s:r,o=Ql?await kh(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await _t.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function bd(n,e){if(!yd(n,e))return null;try{let t=await _t.readFile(wd(n,e));return(await HS(t)).toString("utf8")}catch{}try{return await _t.readFile(L.toolBlobFile(n,e),"utf8")}catch{return null}}async function Ah(n,e){if(!yd(n,e))return null;try{return await _t.readFile(wd(n,e))}catch{}try{let t=await _t.readFile(L.toolBlobFile(n,e));return await kh(t)}catch{return null}}async function Ch(n,e,t){if(!yd(n,e))return;let s=wd(n,e);try{await _t.access(s);return}catch{}await _t.mkdir(L.toolsDir(n),{recursive:!0}),await _t.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Rh(n){Ih.test(n)&&await _t.rm(L.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}ve();Qe();$r();Ni();import*as Nh from"fs/promises";import*as Sd from"path";import{z as le}from"zod";ve();Ni();import*as sn from"fs/promises";import*as Gn from"path";import{spawn as YS}from"child_process";var su=n=>{process.stderr.write(n+`
266
+ `)};function ru(n){su=n??(e=>process.stderr.write(e+`
267
+ `))}async function $h(n){let e=wn();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=L.agentNpmInstallDir(n.agentId,e,n.version),s=ZS(n.packageSpec),r=ek(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=Gn.join(t,"node_modules",".bin",n.bin);if(await Dr(o))return o;if(await Dr(t)){let u=await _h(i);if(u)return u.binPath}await VS({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await _h(i);if(a)return a.binPath;let c=await Oh(t,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 ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${l}`)}async function VS(n){await sn.mkdir(Gn.dirname(n.installDir),{recursive:!0});let e=await sn.mkdtemp(`${n.installDir}.partial-`);try{su(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),nu(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await XS({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await sn.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Dr(n.installDir)){await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),nu(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}su(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),nu(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await sn.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function nu(n,e){if(n)try{n(e)}catch{}}var QS=5,GS=25;function XS(n){return Fh(n,0)}async function Fh(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=YS("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.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){t();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${d})
268
+ stderr: ${l}`:`npm install ${n.packageSpec} failed (${d})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<QS)return await new Promise(r=>setTimeout(r,GS*(e+1))),Fh(n,e+1);throw t}}function ZS(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function ek(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Oh(n,e){let t=Gn.join(n,"node_modules",e,"package.json");try{let s=await sn.readFile(t,"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 _h(n){let e=Gn.join(n.installDir,"node_modules",".bin"),t=Gn.join(e,n.hint);if(await Dr(t))return{binName:n.hint,binPath:t};let s=await Oh(n.installDir,n.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 Dr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=Gn.join(e,i);if(await Dr(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=Gn.join(e,n.basename);if(await Dr(r))return{binName:n.basename,binPath:r}}}async function Dr(n){try{return await sn.access(n),!0}catch{return!1}}var tk=le.object({package:le.string(),bin:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),Di=le.object({archive:le.string().url().optional(),cmd:le.string().optional(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),nk=le.object({"darwin-aarch64":Di.optional(),"darwin-x86_64":Di.optional(),"linux-aarch64":Di.optional(),"linux-x86_64":Di.optional(),"windows-x86_64":Di.optional(),"windows-aarch64":Di.optional()}),sk=le.object({package:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),rk=le.object({command:le.string(),args:le.array(le.string()).optional(),env:le.record(le.string()).optional()}),ik=le.object({command:le.string().optional(),url:le.string().optional(),description:le.string().optional()}),ok=le.object({npx:tk.optional(),binary:nk.optional(),uvx:sk.optional(),exec:rk.optional()}),ak=le.object({id:le.string(),name:le.string(),version:le.string().optional(),description:le.string().optional(),authors:le.array(le.string()).optional(),license:le.string().optional(),icon:le.string().optional(),repository:le.string().optional(),website:le.string().optional(),distribution:ok,onboarding:ik.optional(),requiredEnv:le.array(le.string().min(1)).optional()}),Lh=le.object({version:le.string(),agents:le.array(ak),extensions:le.array(le.unknown()).optional()}),vd=class{constructor(e,t={}){this.config=e;this.options=t}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 t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}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 t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(a=>iu(a)===e);if(i)return this.applyOverride(i);let o=e.toLowerCase();if(o.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(o));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:et(t.command??e),args:t.args?.map(et),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:dk(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=Lh.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await yn(L.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Lh.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await nn(L.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function dk(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function iu(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Hi(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.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 ou(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function ou(n){let e=wn();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=eu(n.distribution.binary,e);if(s?.cmd){let r=Sd.resolve(L.agentInstallDir(n.id,e,t),s.cmd);if(await Bh(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??iu(n)??s.package,i=L.agentNpmInstallDir(n.id,e,t),o=Sd.join(i,"node_modules",".bin",r);if(await Bh(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Bh(n){try{return await Nh.access(n),!0}catch{return!1}}async function bn(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.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??iu(n)??r.package,a=t.onInstallProgress;return{command:await $h({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=eu(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${wn()??"this platform"}.`);let i=t.onInstallProgress,o=await Mh({agentId:n.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(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as pk}from"child_process";import*as Td from"fs";import*as em from"path";Ft();function Rd(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
269
269
  `);for(;c!==-1;){let d=t.slice(0,c).trim();if(t=t.slice(c+1),d.length>0)try{let l=JSON.parse(d);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:j.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=t.indexOf(`
270
270
  `)}}),n.on("end",()=>o()),n.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)+`
271
- `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Br();ve();var lk=4096,er=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??lk,this.killEscalationMs=e.killEscalationMs??uk,this.logger=e.logger,this.fileLog=fk(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
272
- `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Cd(t.stdout,t.stdin);this.connection=new Kt(s),t.stderr?.setEncoding("utf8"),t.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}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
271
+ `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}Hr();ve();var hk=4096,nr=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??hk,this.killEscalationMs=e.killEscalationMs??mk,this.logger=e.logger,this.fileLog=gk(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
272
+ `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Rd(t.stdout,t.stdin);this.connection=new Kt(s),t.stderr?.setEncoding("utf8"),t.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}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
273
273
  `),this.connection.fail(new Error(i))}),t.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
274
274
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.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=${t.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 t=this.stderrTail.trim();return t?`${e}
275
- stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=ck(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(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()} ---
275
+ stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=pk(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(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()} ---
276
276
  `),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()} ---
277
- `),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 t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},uk=2e3;function fk(n){try{let e=L.agentLogFile(n);Rd.mkdirSync(Gh.dirname(e),{recursive:!0});let t=Rd.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Ur from"fs/promises";import*as qd from"os";import*as pa from"path";import{customAlphabet as kI}from"nanoid";lu();Xn();Pu();ve();Pr();import*as As from"fs/promises";import{z as Zn}from"zod";var oI=Zn.object({version:Zn.literal(1),agentId:Zn.string(),upstreamSessionId:Zn.string(),deletedAt:Zn.string(),upstreamUpdatedAt:Zn.string().optional(),cwd:Zn.string().optional(),title:Zn.string().optional(),reason:Zn.enum(["user","expired"]).optional(),interactive:Zn.boolean().optional()}),Fd=class{async add(e){let t={version:1,...e};await nn(L.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await As.access(L.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=L.tombstoneFile(e,t),r=await yn(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return oI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await As.unlink(L.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await As.rmdir(L.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 t;try{t=await As.readdir(L.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await As.readdir(L.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Cm(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as Dm from"fs/promises";Ft();an();_d();Pd();var cI=12e4;async function Tm(n,e,t){let s=n.timeoutMs??cI,r,i,o=!1;try{let a=(async()=>{r=er.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ye}}),d=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(l,r.pid),n.modelId){let h=uI(d);if(h.size===0||h.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=lI(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=t(f);if(!p){let h=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.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;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Ld(n){let e=zi(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
277
+ `),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 t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},mk=2e3;function gk(n){try{let e=L.agentLogFile(n);Td.mkdirSync(em.dirname(e),{recursive:!0});let t=Td.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Wr from"fs/promises";import*as Wd from"os";import*as ha from"path";import{customAlphabet as CI}from"nanoid";uu();Zn();Mu();ve();$r();import*as Rs from"fs/promises";import{z as es}from"zod";var lI=es.object({version:es.literal(1),agentId:es.string(),upstreamSessionId:es.string(),deletedAt:es.string(),upstreamUpdatedAt:es.string().optional(),cwd:es.string().optional(),title:es.string().optional(),reason:es.enum(["user","expired"]).optional(),interactive:es.boolean().optional()}),Od=class{async add(e){let t={version:1,...e};await nn(L.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await Rs.access(L.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=L.tombstoneFile(e,t),r=await yn(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return lI.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await Rs.unlink(L.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await Rs.rmdir(L.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 t;try{t=await Rs.readdir(L.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await Rs.readdir(L.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Em(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as jm from"fs/promises";Ft();an();$d();Md();var pI=12e4;async function Mm(n,e,t){let s=n.timeoutMs??pI,r,i,o=!1;try{let a=(async()=>{r=nr.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:ye}}),d=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(l,r.pid),n.modelId){let h=mI(d);if(h.size===0||h.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...h].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",h=>{let m=hI(h);m.length>0&&u.push(m)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=t(f);if(!p){let h=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${h})`);let m=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${m}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.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;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Bd(n){let e=Ji(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
278
278
 
279
279
  ${e}
280
280
 
281
- ${ku}`:`${t}
281
+ ${Iu}`:`${t}
282
282
 
283
- ${ku}`;return Tm(n,s,Im)}async function Em(n){let e=zi(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
283
+ ${Iu}`;return Mm(n,s,Cm)}async function _m(n){let e=Ji(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
284
284
 
285
285
  ${e}
286
286
 
287
- ${Iu}`:`${t}
287
+ ${xu}`:`${t}
288
288
 
289
- ${Iu}`;return Tm(n,s,xm)}function lI(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function uI(n){let e=new Set;Rm(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Rm(e,t.availableModels),e}function Rm(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}$u();ve();var fI=2,Bd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??fI}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-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 t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await bn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=L.sessionDir(e);if(await Dm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,b,v=0,S,x=Date.now(),T={targetAgentId:r},E=N=>this.opts.onCompactionStateChange?.(e,N,T)??Promise.resolve(),$=N=>{this.opts.broadcastHydraCompaction?.(e,N,T)};await E({status:"requested",requestedAt:x}),$({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:x});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let N=await this.opts.histories.load(e,{maxEntries:1/0});if(N.length===y)break;let M=await Em({agentId:c,cwd:p,plan:l,history:N,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(B,O)=>{E({status:"running",requestedAt:x,iter:m,worker:{upstreamSessionId:B,pid:O??0}})},onFailure:B=>{S=B}});if(M){let B=Lm(M.synopsis,N);B&&Bm(B)&&(await this.opts.persistSynopsis(e,B,N.length),b=B,v=N.length,S=void 0,await E({status:"running",requestedAt:x,iter:m}),$({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:N.length}),await this.opts.onSynthesisArtifact?.(e,B,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Nm(B)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=N.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(b)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let N=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:x,iter:m,lastError:N}),$({sessionUpdate:"hydra_compaction",phase:"failed",error:N})}}catch(N){let M=N instanceof Error?N.message:String(N);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${M}`),await E({status:"failed",requestedAt:x,iter:m,lastError:M}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:M},{targetAgentId:r})}}else{let h=await Ld({agentId:c,cwd:p,plan:l,history:o,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=Lm(h.synopsis,o);m&&Bm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${Nm(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function Lm(n,e){let t=$m(e),s=_m(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Bm(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Nm(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}ve();import*as jt from"fs/promises";function Hm(n){return n==="summary"?"summary":"inline"}var Fu=256;function Um(n,e){return e!=="summary"?n:n.map(pI)}function pI(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(jm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Ou(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...n,params:{...t,update:i}}}function hI(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function jm(n){if(hI(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Ou(e.text)),typeof e.content=="string"?t.content=Ou(e.content):e.content&&typeof e.content=="object"&&(t.content=jm(e.content)),t}function Ou(n){if(typeof n=="string"&&n.length>Fu){let e=n.length-Fu;return`${n.slice(0,Fu)}\u2026[+${e} chars omitted from summary export]`}return n}var mI=2048;function qm(n){let e=new Set,t=s=>{if(Wm(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function Wm(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function gI(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Nu(n,e){if(!gI(n))return n;let t=n.params,s=t.update,r=await Lu(s,e);return{...n,params:{...t,update:r}}}async function Lu(n,e){if(typeof n=="string"){if(n.length<=mI)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await Lu(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Lu(r,e);return t}return n}async function zm(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Bu(t,e);return s===t?n:{...n,params:s}}async function Bu(n,e){if(Wm(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Bu(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await Bu(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var oa=/^[A-Za-z0-9_-]+$/,yI=1e3,Nd=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??yI}async append(e,t){if(oa.test(e))return this.enqueue(e,async()=>{await jt.mkdir(L.sessionDir(e),{recursive:!0});let s=await Nu(t,i=>Ql(e,i)),r=JSON.stringify(s)+`
290
- `;await jt.appendFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(oa.test(e))return this.enqueue(e,async()=>{await jt.mkdir(L.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await Nu(i,o=>Ql(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
289
+ ${xu}`;return Mm(n,s,Rm)}function hI(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function mI(n){let e=new Set;Pm(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Pm(e,t.availableModels),e}function Pm(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}Fu();ve();var gI=2,Nd=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??gI}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-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 t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let i=await this.opts.store.read(e);if(!i){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let o=await this.opts.histories.load(e,{maxEntries:1/0}),a=i.summarizedThroughEntry;if(a!==void 0&&o.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${o.length})`);return}a!==void 0&&o.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${o.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??i.agentId:this.opts.synopsisAgent??i.agentId,d=await this.opts.registry.getAgent(c);if(!d){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let l=await bn(d,[],{npmRegistry:this.opts.npmRegistry}),u=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(u?i.currentModel:void 0):this.opts.synopsisModel,p=L.sessionDir(e);if(await jm.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${o.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let h=this.opts.compactionMaxIterations??3,m=0,y=a??0,w,v=0,S,x=Date.now(),T={targetAgentId:r},E=N=>this.opts.onCompactionStateChange?.(e,N,T)??Promise.resolve(),$=N=>{this.opts.broadcastHydraCompaction?.(e,N,T)};await E({status:"requested",requestedAt:x}),$({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:x});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${o.length} watermark=${y}`);let N=await this.opts.histories.load(e,{maxEntries:1/0});if(N.length===y)break;let M=await _m({agentId:c,cwd:p,plan:l,history:N,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(B,O)=>{E({status:"running",requestedAt:x,iter:m,worker:{upstreamSessionId:B,pid:O??0}})},onFailure:B=>{S=B}});if(M){let B=Dm(M.synopsis,N);B&&Hm(B)&&(await this.opts.persistSynopsis(e,B,N.length),w=B,v=N.length,S=void 0,await E({status:"running",requestedAt:x,iter:m}),$({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:N.length}),await this.opts.onSynthesisArtifact?.(e,B,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${Um(B)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(y=N.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===y)break}while(m<h);if(w)m>=h&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${h} without producing artifact sessionId=${e}: ${S??"no reason captured"}`);let N=S??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await E({status:"failed",requestedAt:x,iter:m,lastError:N}),$({sessionUpdate:"hydra_compaction",phase:"failed",error:N})}}catch(N){let M=N instanceof Error?N.message:String(N);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${M}`),await E({status:"failed",requestedAt:x,iter:m,lastError:M}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:M},{targetAgentId:r})}}else{let h=await Bd({agentId:c,cwd:p,plan:l,history:o,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!h){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=Dm(h.synopsis,o);m&&Hm(m)?(await this.opts.persistSynopsis(e,m,o.length),h.title&&await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!h.title)} fields=${Um(m)}`)):h.title&&(await this.opts.persistTitle(e,h.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(i){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${i.message}`)}}};function Dm(n,e){let t=Lm(e),s=Om(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Hm(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Um(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}ve();import*as jt from"fs/promises";function qm(n){return n==="summary"?"summary":"inline"}var Ou=256;function Wm(n,e){return e!=="summary"?n:n.map(yI)}function yI(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(zm));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=Lu(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...n,params:{...t,update:i}}}function wI(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function zm(n){if(wI(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=Lu(e.text)),typeof e.content=="string"?t.content=Lu(e.content):e.content&&typeof e.content=="object"&&(t.content=zm(e.content)),t}function Lu(n){if(typeof n=="string"&&n.length>Ou){let e=n.length-Ou;return`${n.slice(0,Ou)}\u2026[+${e} chars omitted from summary export]`}return n}var bI=2048;function Km(n){let e=new Set,t=s=>{if(Jm(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function Jm(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function vI(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Du(n,e){if(!vI(n))return n;let t=n.params,s=t.update,r=await Bu(s,e);return{...n,params:{...t,update:r}}}async function Bu(n,e){if(typeof n=="string"){if(n.length<=bI)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await Bu(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Bu(r,e);return t}return n}async function Ym(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Nu(t,e);return s===t?n:{...n,params:s}}async function Nu(n,e){if(Jm(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Nu(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await Nu(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var aa=/^[A-Za-z0-9_-]+$/,SI=1e3,Dd=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??SI}async append(e,t){if(aa.test(e))return this.enqueue(e,async()=>{await jt.mkdir(L.sessionDir(e),{recursive:!0});let s=await Du(t,i=>Gl(e,i)),r=JSON.stringify(s)+`
290
+ `;await jt.appendFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(aa.test(e))return this.enqueue(e,async()=>{await jt.mkdir(L.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await Du(i,o=>Gl(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
291
291
  `)+`
292
- `;await jt.writeFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(oa.test(e))return this.enqueue(e,async()=>{let s;try{s=await jt.readFile(L.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
292
+ `;await jt.writeFile(L.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(aa.test(e))return this.enqueue(e,async()=>{let s;try{s=await jt.readFile(L.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
293
293
  `).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await jt.writeFile(L.historyFile(e),i.join(`
294
294
  `)+`
295
- `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!oa.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await jt.readFile(L.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
296
- `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=t.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async f=>{let p=d.get(f);if(p!==void 0)return p;let h=await wd(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await zm(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(oa.test(e))return this.enqueue(e,async()=>{try{await jt.unlink(L.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await xh(e);try{await jt.rmdir(L.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};ve();Qe();Hd();Hr();Ed();Ft();Ft();an();yu();var Ym=900*1e3,II="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ud=kI(II,16),jd=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>er.spawn(a)),this.store=s??new $d,this.tombstones=r.tombstones??new Fd,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Nd({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 Bd({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ni(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${Ud()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Yi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=j.AlreadyAttached,i}return t}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 t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=j.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await bn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Di,clientInfo:{name:"hydra",version:ye}});o=m.agentCapabilities,i.authMethods=ua(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),nr(m,i)}let a;try{let m=Vm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===j.AuthRequired)throw await i.kill().catch(()=>{}),nr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
297
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=zu(a??{}),d=e.agentModes??ju(Wu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await Hi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=Uu(a??{}),f=ju(qu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ui({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Yi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:f,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Hi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Ui({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Yi({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Ur.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:et(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=j.AgentNotInstalled,p}let s=await bn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:qd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Di,clientInfo:{name:"hydra",version:ye}})}catch(p){throw await r.kill().catch(()=>{}),nr(p,r)}if(r.authMethods=ua(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=L.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(xI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Cm(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${Ut}${Ud()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:ra(),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=Eu(S);await this.store.write(x),u.push({version:1,...x})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],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),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,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 t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=j.AgentNotInstalled,i}let s=await bn(t,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:Di,clientInfo:{name:"hydra",version:ye}}),o=i.agentCapabilities;r.authMethods=ua(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=Uu(a),l=qu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Wi(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Wu(a),p=zu(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),nr(Gm(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=j.AgentNotInstalled,o}let r=await bn(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Di,clientInfo:{name:"hydra",version:ye}}),a=o.agentCapabilities;i.authMethods=ua(o.authMethods);let c=Vm(t.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),l=Uu(d),u=ju(qu(d)),f=Wu(d),p=zu(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),nr(Gm(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)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 t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){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=j.AgentNotInstalled,c}let i=await bn(r,[],{npmRegistry:this.npmRegistry}),o=t??et(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Di,clientInfo:{name:"hydra",version:ye}});a.authMethods=ua(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),nr(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=j.AgentNotInstalled,s}return bn(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Xi({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:Zm(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=AI(e,t);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,t){return wd(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:CI(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Ki(r.update.prompt),o=Su(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 t of this.sessions.values()){let s=t.agent.agentId,r=t.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(Ut))return;let t=Ut+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=j.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await fa(t.sessionId),c=Xi({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:d,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await fa(s.sessionId),i=Xi(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],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=>fa(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Xi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>fa(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=Xi(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=ra(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Xm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of qm(o)){let l=await kh(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=j.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:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Ut}${Ud()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=j.SessionNotFound,S}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let x=new Error(`agent ${r} not found in registry`);throw x.code=j.AgentNotInstalled,x}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=t.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(t.forkAt!==void 0){let S=vu(o,t.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw x.code=j.InvalidParams,x}c=t.forkAt,a=o.slice(0,S+1)}else{let S=TI(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let x=new Error(`agent ${r} not found in registry`);throw x.code=j.AgentNotInstalled,x}f=S,u=s.currentModel,l="running"}let h=await Xm(e),m=d==="synthesis",y={...s,lineageId:ra(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},b=la({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:ye,machine:qd.hostname()}),v=`${Ut}${Ud()}`;return await this.writeImportedRecord({sessionId:v,bundle:b,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await bn(f,[],{npmRegistry:this.npmRegistry}),x=await Ld({agentId:r,cwd:t.cwd??L.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});x&&x.synopsis?await this.mutateRecord(v,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Ih(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Ur.utimes(L.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Dr(L.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await fa(e),i=Xi(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),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(t=>t.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,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await lm(t.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 ${t.sessionId} (TTL ${Ym/1e3}s)`),await ta(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await ta(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function xI(n,e){if(typeof n!="string"||n.length===0)return!1;let t=pa.resolve(n),s=pa.resolve(e);return t===s||t.startsWith(s+pa.sep)}function AI(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return Eu({sessionId:n.sessionId,lineageId:e?.lineageId??ra(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:Zm(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Zm(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function CI(n){return n?{...n}:void 0}function Vm(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Wd(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._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=RI(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Uu(n){return Wd(n,{nestedKey:"models",configId:"model",fromObject:e=>es(e.currentModelId)??es(e.currentModel)??es(e.modelId)??es(e.model),fromConfig:e=>es(e.currentValue)})}function nr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==j.AuthRequired)return n;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=j.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function Qm(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function Gm(n,e,t,s){if(n&&typeof n=="object"&&n.code===j.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${Qm(s.cwd)} && ${[s.command,...s.args].map(Qm).join(" ")})`:"";if(!o&&!a)return n;let c=[i?r:`agent ${t} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
298
- `));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function ua(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;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 es(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function RI(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function ju(n){return n.length>0?n:void 0}function qu(n){return Wd(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ji(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ji(e.options);return t.length>0?t:void 0}})??[]}function Wu(n){return Wd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=na(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=na(e.options);return t.length>0?t:void 0}})??[]}function zu(n){return Wd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>es(e.currentModeId)??es(e.currentMode)??es(e.modeId)??es(e.mode),fromConfig:e=>es(e.currentValue)})}function TI(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Xm(n){try{let e=await Ur.readFile(L.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
299
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function fa(n){try{let e=await Ur.stat(L.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Xi(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Nr?!1:e?!0:void 0}import{spawn as EI}from"child_process";import*as Kd from"fs";import*as Cs from"fs/promises";import*as Jd from"path";import PI from"pino-roll";var zd=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,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;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 ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Qe();var MI=1e3,_I=6e4,Ku=3e3,Zi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??MI,this.restartCapMs=r.restartCapMs??_I;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Cs.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.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()},Ku);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw ha(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw ha(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw ha(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw ha(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 t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw ha(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Ku);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,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 zd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Cs.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let i=await Cs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Ju(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ku;for(;Date.now()<i&&Ju(r);)await new Promise(o=>setTimeout(o,50));if(Ju(r))try{process.kill(r,"SIGKILL")}catch{}}await Cs.unlink(s).catch(()=>{})}}async spawn(e,t){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=Jd.dirname(this.adapter.paths.logFile(r.name)),a;try{await Cs.mkdir(o,{recursive:!0}),a=await PI({file:Jd.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
295
+ `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!aa.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await jt.readFile(L.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
296
+ `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let h=p;typeof h.method=="string"&&typeof h.recordedAt=="number"&&o.push({method:h.method,params:h.params,recordedAt:h.recordedAt})}let a=t.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async f=>{let p=d.get(f);if(p!==void 0)return p;let h=await bd(e,f);return d.set(f,h),h},u=[];for(let f of c)u.push(await Ym(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(aa.test(e))return this.enqueue(e,async()=>{try{await jt.unlink(L.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Rh(e);try{await jt.rmdir(L.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};ve();Qe();Ud();qr();Pd();Ft();Ft();an();wu();var Gm=900*1e3,RI="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jd=CI(RI,16),qd=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>nr.spawn(a)),this.store=s??new Fd,this.tombstones=r.tombstones??new Od,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Dd({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new Nd({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,d)=>{if(d.targetAgentId)return;let l=this.get(a);l&&(l.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,d)=>{this.emitSwapPhase(a,d.targetAgentId,c)},onSynthesisArtifact:async(a,c,d,l)=>{await this.dispatchSynthesisSwap(a,c,d,l)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let i=this.get(e);if(!i){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let o=this.compactionTailK;try{if(await i.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(i,t,o,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=i.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let o=i.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>i.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${i.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),o?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:o}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,i.synopsis,s,i.summarizedThroughEntry,o)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,i){try{let o=i?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:o,summarizedThroughEntry:r,...i?{newAgentId:i}:{}}),i?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(o){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${o instanceof Error?o.message:String(o)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Hi(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let i={...s.agentCapabilities??{}};for(let o of e.transformChain)if(o.intercepts.has("agent:initialize"))try{let a=await o.connection.request("hydra-acp/transformer/message",{token:`t_${jd()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:i});a.action==="stop"&&a.payload&&(i=a.payload)}catch{}s.agentCapabilities=i}let r=new Qi({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:i=>this.bootstrapAgent({...i,mcpServers:i.mcpServers??[]}),loadExistingAgentSession:(i,o)=>this.bootstrapAgentLoad(i,{...o,mcpServers:o.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:i=>this.scheduleCompaction(r.sessionId,i),resolveAgentId:async i=>(await this.registry.getAgent(i))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:i=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:i}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=j.AlreadyAttached,i}return t}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 t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=j.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await bn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ui,clientInfo:{name:"hydra",version:ye}});o=m.agentCapabilities,i.authMethods=fa(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),rr(m,i)}let a;try{let m=Xm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===j.AuthRequired)throw await i.kill().catch(()=>{}),rr(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
297
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Ku(a??{}),d=e.agentModes??qu(zu(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(m=>m.id))}`);let l=await ji({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=ju(a??{}),f=qu(Wu(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await qi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let h=new Qi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,y)=>this.bootstrapAgentLoad(m,{...y,mcpServers:y.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:f,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(h.sessionId),scheduleCompaction:m=>this.scheduleCompaction(h.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(h.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(h.sessionId),uncompactHook:()=>this.performUncompact(h.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(h.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(h.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(h),h}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await ji({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await qi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Qi({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:d=>this.scheduleCompaction(c.sessionId,d),resolveAgentId:async d=>(await this.registry.getAgent(d))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Wr.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:et(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=j.AgentNotInstalled,p}let s=await bn(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Wd.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ui,clientInfo:{name:"hydra",version:ye}})}catch(p){throw await r.kill().catch(()=>{}),rr(p,r)}if(r.authMethods=fa(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=L.sessionsDir(),u=[],f=0;for(let p of a){let h=`${e}::${p.sessionId}`;if(c.has(h)){f+=1;continue}if(TI(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!Em(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}c.add(h);let y=`${Ut}${jd()}`,w=new Date().toISOString(),v=p.updatedAt??w,S={sessionId:y,lineageId:ia(),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=Pu(S);await this.store.write(x),u.push({version:1,...x})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],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),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,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 t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=j.AgentNotInstalled,i}let s=await bn(t,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:Ui,clientInfo:{name:"hydra",version:ye}}),o=i.agentCapabilities;r.authMethods=fa(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=ju(a),l=Wu(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let h=Ki(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(h.kind==="exact"||h.kind==="none")await this.applySeedModel(r,c,u,m)&&(d=u);else if(h.kind==="resolved")(h.modelId===d||await this.applySeedModel(r,c,h.modelId,`${m} resolved to ${JSON.stringify(h.modelId)}`))&&(d=h.modelId);else if(h.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${h.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(w=>w.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=zu(a),p=Ku(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),rr(eg(i,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let o=new Error(`agent ${t.agentId} not found in registry`);throw o.code=j.AgentNotInstalled,o}let r=await bn(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ui,clientInfo:{name:"hydra",version:ye}}),a=o.agentCapabilities;i.authMethods=fa(o.authMethods);let c=Xm(t.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),l=ju(d),u=qu(Wu(d)),f=zu(d),p=Ku(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:u,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),rr(eg(o,i,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)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 t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){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=j.AgentNotInstalled,c}let i=await bn(r,[],{npmRegistry:this.npmRegistry}),o=t??et(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Ui,clientInfo:{name:"hydra",version:ye}});a.authMethods=fa(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),rr(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=j.AgentNotInstalled,s}return bn(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=eo({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),i=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===i&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,i);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:ng(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=EI(e,t);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,t){return bd(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:PI(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Yi(r.update.prompt),o=ku(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 t of this.sessions.values()){let s=t.agent.agentId,r=t.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(Ut))return;let t=Ut+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=j.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await pa(t.sessionId),c=eo({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:d,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await pa(s.sessionId),i=eo(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],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=>pa(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=eo({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let h=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:u.attachedCount,status:"warm",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>pa(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=eo(u,f.hasContent);if(!r(p))continue;let h=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:h,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState,forkSynthesisState:u.forkSynthesisState})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=ia(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await tg(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Km(o)){let l=await Ah(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=j.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:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Ut}${jd()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let S=new Error(`source session not found: ${e}`);throw S.code=j.SessionNotFound,S}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let x=new Error(`agent ${r} not found in registry`);throw x.code=j.AgentNotInstalled,x}let o=await this.histories.load(e).catch(()=>[]),a=o,c,d=t.mode??"synthesis",l,u,f,p=12e4;if(d==="verbatim")if(t.forkAt!==void 0){let S=Su(o,t.forkAt);if(S<0){let x=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw x.code=j.InvalidParams,x}c=t.forkAt,a=o.slice(0,S+1)}else{let S=_I(o);S?(c=S.messageId,a=o.slice(0,S.index+1)):(c="",a=o.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),c="",a=o;let S=await this.registry.getAgent(r);if(!S){let x=new Error(`agent ${r} not found in registry`);throw x.code=j.AgentNotInstalled,x}f=S,u=s.currentModel,l="running"}let h=await tg(e),m=d==="synthesis",y={...s,lineageId:ia(),agentId:r,interactive:!1,...l!==void 0?{forkSynthesisState:l}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},w=ua({record:y,history:a,promptHistory:h.length>0?h:void 0,hydraVersion:ye,machine:Wd.hostname()}),v=`${Ut}${jd()}`;return await this.writeImportedRecord({sessionId:v,bundle:w,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...l!==void 0?{forkSynthesisState:l}:{}}),m&&(async()=>{try{let S=await bn(f,[],{npmRegistry:this.npmRegistry}),x=await Bd({agentId:r,cwd:t.cwd??L.sessionDir(e),plan:S,history:o,modelId:u,sessionId:e,logger:this.logger,timeoutMs:p});x&&x.synopsis?await this.mutateRecord(v,{synopsis:x.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(S){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${S.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(x){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${x.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Ch(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Wr.utimes(L.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await jr(L.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await pa(e),i=eo(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let i=await this.store.read(e);if(!i)return;let o={...i.extensionState??{}},a={...o[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);o[t]=a;let d={...i,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(d)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let i={...r.extensionState},o={...i[t]};if(!(s in o))return;delete o[s],Object.keys(o).length===0?delete i[t]:i[t]=o;let a={...r,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),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(t=>t.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,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let i=s.phase==="failed";r.broadcastPendingAgentSwap(i?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;t+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await pm(t.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 ${t.sessionId} (TTL ${Gm/1e3}s)`),await na(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await na(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function TI(n,e){if(typeof n!="string"||n.length===0)return!1;let t=ha.resolve(n),s=ha.resolve(e);return t===s||t.startsWith(s+ha.sep)}function EI(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return Pu({sessionId:n.sessionId,lineageId:e?.lineageId??ia(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:ng(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function ng(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function PI(n){return n?{...n}:void 0}function Xm(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function zd(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._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=MI(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function ju(n){return zd(n,{nestedKey:"models",configId:"model",fromObject:e=>ts(e.currentModelId)??ts(e.currentModel)??ts(e.modelId)??ts(e.model),fromConfig:e=>ts(e.currentValue)})}function rr(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==j.AuthRequired)return n;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(t.data)?t.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=j.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function Zm(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function eg(n,e,t,s){if(n&&typeof n=="object"&&n.code===j.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),i=r.includes("stderr:"),o=i?"":e.stderrTailText(),a=s?`to reproduce: (cd ${Zm(s.cwd)} && ${[s.command,...s.args].map(Zm).join(" ")})`:"";if(!o&&!a)return n;let c=[i?r:`agent ${t} failed to start: ${r}`];o&&c.push(`stderr: ${o}`),a&&c.push(a);let d=new Error(c.join(`
298
+ `));if(n&&typeof n=="object"){let l=n;typeof l.code=="number"&&(d.code=l.code),l.data!==void 0&&(d.data=l.data)}return d}function fa(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;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 ts(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function MI(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function qu(n){return n.length>0?n:void 0}function Wu(n){return zd(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Vi(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Vi(e.options);return t.length>0?t:void 0}})??[]}function zu(n){return zd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=sa(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=sa(e.options);return t.length>0?t:void 0}})??[]}function Ku(n){return zd(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ts(e.currentModeId)??ts(e.currentMode)??ts(e.modeId)??ts(e.mode),fromConfig:e=>ts(e.currentValue)})}function _I(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function tg(n){try{let e=await Wr.readFile(L.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
299
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function pa(n){try{let e=await Wr.stat(L.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function eo(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Ur?!1:e?!0:void 0}import{spawn as $I}from"child_process";import*as Jd from"fs";import*as Ts from"fs/promises";import*as Yd from"path";import FI from"pino-roll";var Kd=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,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;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 ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Qe();var OI=1e3,LI=6e4,Ju=3e3,to=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??OI,this.restartCapMs=r.restartCapMs??LI;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Ts.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.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()},Ju);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw ma(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw ma(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw ma(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw ma(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 t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw ma(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Ju);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,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 Kd(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ts.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let i=await Ts.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Yu(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Ju;for(;Date.now()<i&&Yu(r);)await new Promise(o=>setTimeout(o,50));if(Yu(r))try{process.kill(r,"SIGKILL")}catch{}}await Ts.unlink(s).catch(()=>{})}}async spawn(e,t){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=Yd.dirname(this.adapter.paths.logFile(r.name)),a;try{await Ts.mkdir(o,{recursive:!0}),a=await FI({file:Yd.join(o,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}}),a.on("error",y=>{e.failureReason=`log stream: ${y.message}`})}catch(y){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${y.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
300
300
  `);let c=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=c,e.version=void 0;let d={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:c,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[l,...u]=i;if(l===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
301
- `),a.end();return}let f=et(l),p=[...u,...r.args].map(et),h;try{h=EI(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
302
- `),a.end(),this.scheduleRestart(e,t);return}let m=y=>{try{a.write(typeof y=="string"?y:y.toString())}catch{}};if(h.stdout?.on("data",m),h.stderr?.on("data",m),typeof h.pid=="number")try{Kd.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
301
+ `),a.end();return}let f=et(l),p=[...u,...r.args].map(et),h;try{h=$I(f,p,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(y){a.write(`[hydra-acp] failed to spawn ${r.name}: ${y.message}
302
+ `),a.end(),this.scheduleRestart(e,t);return}let m=y=>{try{a.write(typeof y=="string"?y:y.toString())}catch{}};if(h.stdout?.on("data",m),h.stderr?.on("data",m),typeof h.pid=="number")try{Jd.writeFileSync(this.adapter.paths.pidFile(r.name),`${h.pid}
303
303
  `,{encoding:"utf8",mode:384})}catch(y){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${y.message}
304
304
  `)}e.child=h,e.logStream=a,e.pid=typeof h.pid=="number"?h.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,h.on("error",y=>{a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${y.message}
305
- `)}),h.on("exit",(y,b)=>{try{Kd.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${b??"null"}
305
+ `)}),h.on("exit",(y,w)=>{try{Jd.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${y??"null"} signal=${w??"null"}
306
306
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof y=="number"?y:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let v=e.exitWaiters.splice(0);for(let x of v)x();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let S=e.breaker.recordExit(y,r.name,this.adapter.kind);if(typeof S=="object"){e.failureReason=S.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${S.tripped}
307
- `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Ju(n){try{return process.kill(n,0),!0}catch{return!1}}function ha(n,e){return n.code=e,n}ve();var $I={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:L.extensionsDir,logFile:L.extensionLogFile,pidFile:L.extensionPidFile}},Yd=class extends Zi{constructor(e,t,s={}){super(e,$I,t,s)}};ve();var FI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:L.transformersDir,logFile:L.transformerLogFile,pidFile:L.transformerPidFile}},Vd=class extends Zi{connected=new Map;constructor(e,t,s={}){super(e,FI,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var Qd=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,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[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};ve();$i();Li();ve();Li();import*as ga from"fs/promises";import*as Gd from"path";var ma=n=>{process.stderr.write(n+`
308
- `)};function Yu(n){ma=n??(e=>process.stderr.write(e+`
309
- `))}async function eg(n,e){let t=wn();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Gd.join(L.agentsDir(),t),a;try{a=await ga.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ma(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=Gd.join(o,d),p;try{p=await ga.readdir(f,{withFileTypes:!0})}catch(h){ma(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Gd.join(f,m);try{await ga.rm(y,{recursive:!0,force:!0}),ma(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(b){ma(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function tg(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await iu(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Vu(n){let e=n.maxDeletions??200,t=(p,h)=>{n.logger&&n.logger[p](`session-gc: ${h}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,t("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(n.verbose||d>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${d} ${p} session(s) older than ${OI(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function ng(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Vu({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function OI(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}an();ya();ve();Pr();import*as ig from"path";import{createHash as BI,randomBytes as NI,timingSafeEqual as DI}from"crypto";var og="hydra_session_",HI=3600*24*30,sg=12,UI=32,jI=50;function qI(){return ig.join(L.home(),"session-tokens.json")}function rg(n){return BI("sha256").update(n).digest("hex")}function ag(n){return NI(n).toString("hex")}function WI(){return ag(sg).slice(0,sg*2)}function zI(){return`${og}${ag(UI)}`}var Xd=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=qI(),s=await yn(t);s&&Array.isArray(s.records)&&(e=s.records.filter(KI));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=zI(),s=rg(t),r=WI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:HI,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:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(og))return;let t=rg(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!DI(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),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:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}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(()=>{})},jI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>nn(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 KI(n){if(!n||typeof n!="object")return!1;let e=n;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")}ks();var dg="Bearer ",Zd=class{constructor(e){this.token=e}token;async validate(e){return JI(e,this.token)?"service":void 0}},ec=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},tc=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function cg(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(dg)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(dg.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function lg(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var nc=class{tokens=new Map;mint(e,t){let s=Ti();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function JI(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var sc=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};ve();Qe();Xu();Hr();oc();import*as nf from"fs";import*as va from"os";import*as Pg from"path";import*as sf from"readline";rr();Xn();function ac(n,e={}){let t=Sx(n),s=kx(t),r=[];Ix(r,n),xx(r,t,s,e.includeTools??!1);let i=r.join(`
307
+ `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Yu(n){try{return process.kill(n,0),!0}catch{return!1}}function ma(n,e){return n.code=e,n}ve();var BI={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:L.extensionsDir,logFile:L.extensionLogFile,pidFile:L.extensionPidFile}},Vd=class extends to{constructor(e,t,s={}){super(e,BI,t,s)}};ve();var NI={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:L.transformersDir,logFile:L.transformerLogFile,pidFile:L.transformerPidFile}},Qd=class extends to{connected=new Map;constructor(e,t,s={}){super(e,NI,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var Gd=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,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[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};ve();Oi();Ni();ve();Ni();import*as ya from"fs/promises";import*as Xd from"path";var ga=n=>{process.stderr.write(n+`
308
+ `)};function Vu(n){ga=n??(e=>process.stderr.write(e+`
309
+ `))}async function sg(n,e){let t=wn();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=Xd.join(L.agentsDir(),t),a;try{a=await ya.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ga(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=Xd.join(o,d),p;try{p=await ya.readdir(f,{withFileTypes:!0})}catch(h){ga(`hydra-acp: prune: failed to read ${f}: ${h.message}`);continue}for(let h of p){if(!h.isDirectory())continue;let m=h.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let y=Xd.join(f,m);try{await ya.rm(y,{recursive:!0,force:!0}),ga(`hydra-acp: pruned stale ${d} ${m} (${y})`)}catch(w){ga(`hydra-acp: prune: failed to remove ${y}: ${w.message}`)}}}}function rg(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await ou(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Qu(n){let e=n.maxDeletions??200,t=(p,h)=>{n.logger&&n.logger[p](`session-gc: ${h}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,h)=>p.lastUsedMs-h.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(d+=1)}catch(h){l+=1,t("warn",`delete ${p} failed: ${h.message}`)}let u=o.length-a.length;if(n.verbose||d>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${d} ${p} session(s) older than ${DI(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function ig(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Qu({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function DI(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}an();wa();ve();$r();import*as dg from"path";import{createHash as UI,randomBytes as jI,timingSafeEqual as qI}from"crypto";var cg="hydra_session_",WI=3600*24*30,og=12,zI=32,KI=50;function JI(){return dg.join(L.home(),"session-tokens.json")}function ag(n){return UI("sha256").update(n).digest("hex")}function lg(n){return jI(n).toString("hex")}function YI(){return lg(og).slice(0,og*2)}function VI(){return`${cg}${lg(zI)}`}var Zd=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=JI(),s=await yn(t);s&&Array.isArray(s.records)&&(e=s.records.filter(QI));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=VI(),s=ag(t),r=YI(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:WI,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:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(cg))return;let t=ag(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!qI(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),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:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}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(()=>{})},KI))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>nn(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 QI(n){if(!n||typeof n!="object")return!1;let e=n;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")}xs();var ug="Bearer ",ec=class{constructor(e){this.token=e}token;async validate(e){return GI(e,this.token)?"service":void 0}},tc=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},nc=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function fg(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(ug)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(ug.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function pg(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var sc=class{tokens=new Map;mint(e,t){let s=Pi();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function GI(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var rc=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};ve();Qe();Zu();qr();ac();import*as sf from"fs";import*as Sa from"os";import*as $g from"path";import*as rf from"readline";or();Zn();function dc(n,e={}){let t=Ax(n),s=Cx(t),r=[];Rx(r,n),Tx(r,t,s,e.includeTools??!1);let i=r.join(`
310
310
  `);return i.endsWith(`
311
311
  `)||(i+=`
312
- `),i}function Sx(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=ts(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function kx(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Ix(n,e){let t=e.session,s=ft(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${no(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${ef(a.size)}`:void 0;c.push(d?`${ef(a.used)} / ${d} tokens`:`${ef(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 ")}`)}n.push(i.join(`
313
- `)),n.push("")}function xx(n,e,t,s){if(!e.some(p=>Ax(p.event))){n.push("_No conversation history recorded._"),n.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)n.push(p);n.push(""),a=[]}},u=()=>{l(),o.length>0&&(Sg(n,o.trimEnd(),"*"),n.push(""),o=""),i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},f=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{u(),n.push("---"),n.push(""),r+=1,Sg(n,p.text,"**"),n.push(""),d=!0;break}case"agent-text":f(),i+=p.text;break;case"agent-thought":{f(),i.length>0&&(n.push(i.trimEnd()),n.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(f(),(i.length>0||o.length>0)&&u(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=t.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${Rx(h.status)} ${Cx(h)}`);break}case"tool-call-update":break;case"plan":{f(),u(),n.push("**Plan:**"),n.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";n.push(`- ${m} ${no(h.content)}`)}n.push("");break}case"mode-changed":f(),u(),n.push(`_mode: ${no(p.mode)}_`),n.push("");break;case"model-changed":f(),u(),n.push(`_model: ${no(p.model)}_`),n.push("");break;case"turn-complete":u();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}u()}function Ax(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Cx(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${no(n.title)}${t}`}function Rx(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function Sg(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
314
- `);for(let a=0;a<o.length;a++){let c=o[a],d=no(c);n.push(a===0&&a===o.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===o.length-1?`${d}${t}`:d)}r<s.length-1&&n.push("")}}function no(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ef(n){return n.toLocaleString("en-US")}Ft();an();Yo();rr();function Tx(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>Ex(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function Ex(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:kg(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:kg(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function kg(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Px(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Mx=5,_x=200,Ig=30;async function Cg(n,e,t={}){let s=Tx(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Mx,i=t.maxSessions??_x,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await n.loadHistory(u.sessionId).catch(()=>[]),p=$x(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function $x(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Fx(n,o,i,t-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 Fx(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let c=Ox(a).filter(d=>Px(t,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:Hx(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Ox(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=dc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?yt(s.text):dc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Nx(s))return[];let i=dc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Dx(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Lx(s);default:return[]}}function Lx(n){let e=xg(n,"name"),t=xg(n,"title"),s=[];if(t!==void 0){let a=Pe(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=Pe(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Ag(r);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Ag(i);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Bx(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Bx(n){let e=n.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=Pe(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=Pe(s);if(r.length>0)return r}}return null}function Nx(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function dc(n){if(typeof n=="string")return yt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?yt(e.text):""}function Dx(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=dc(t);s.length>0&&e.push(s)}return e.join("")}function xg(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Ag(n){try{return JSON.stringify(n)}catch{return""}}function Hx(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Ig),c=Math.min(s.length,o+i.length+Ig),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Tg}from"crypto";function Rg(n){let e=Tg(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function tf(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Rg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Rg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=so(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function so(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Tg(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var cc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Eg(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Mr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Mg(n,e,t,s={}){n.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),n.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),n.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Cg(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=et(u.cwd??t.cwd),p=u.agentId??t.agentId,h=so(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),n.post("/v1/sessions/collect",async(d,l)=>{let u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await Vu({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>Pg.join(va.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),n.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(b){return l.code(409).send({error:b.message}),l}}),n.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":Hm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=la({record:m.record,history:h==="summary"?Um(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:ye,machine:va.hostname(),hydraHost:Eg(t)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),n.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,b=eo(p.history);y&&(b=b.filter(v=>y.has(v.path))),m&&(b=b.map(v=>({...v,hunks:to(v.hunks)}))),l.code(200).send(b)}),n.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),n.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=la({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:ye,machine:va.hostname(),hydraHost:Eg(t)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(ac(h,{includeTools:y}))}),n.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=et(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===j.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===j.InvalidParams||y.code===j.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.post("/v1/sessions/import",async(d,l)=>{let u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=On(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===j.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&t.compaction){let T=h??0,E=x.length,N=x.slice(T).reduce((O,K)=>O+JSON.stringify(K.params).length,0);v=Gu(N);let M=p?.currentModel,D=x.at(-1).recordedAt,B=p?.currentUsage;b=ug({summarizedThroughEntry:T,totalEntries:E,unsummarizedChars:N,compactionInFlight:e.getCompactionInFlight(),currentModel:M,lastActivityMs:D,nowMs:Date.now(),config:t.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),n.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),n.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,b,v=!1,S=1e4,x=[];if(m){p&&(b=m.onBroadcast(E=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(E)+`
315
- `):(x.push(E),x.length>S&&x.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(E){throw b?.(),E}}else{let E=await e.getHistory(h);if(E===void 0)return l.code(404).send({error:"session not found"}),l;y=E}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let E of y??[]){l.raw.write(JSON.stringify(E)+`
312
+ `),i}function Ax(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=ns(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Cx(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Rx(n,e){let t=e.session,s=ft(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${ro(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${tf(a.size)}`:void 0;c.push(d?`${tf(a.used)} / ${d} tokens`:`${tf(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 ")}`)}n.push(i.join(`
313
+ `)),n.push("")}function Tx(n,e,t,s){if(!e.some(p=>Ex(p.event))){n.push("_No conversation history recorded._"),n.push("");return}let r=0,i="",o="",a=[],c=new Set,d=!1,l=()=>{if(a.length!==0){for(let p of a)n.push(p);n.push(""),a=[]}},u=()=>{l(),o.length>0&&(xg(n,o.trimEnd(),"*"),n.push(""),o=""),i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},f=()=>{d||(d=!0)};for(let{event:p}of e)switch(p.kind){case"user-text":{u(),n.push("---"),n.push(""),r+=1,xg(n,p.text,"**"),n.push(""),d=!0;break}case"agent-text":f(),i+=p.text;break;case"agent-thought":{f(),i.length>0&&(n.push(i.trimEnd()),n.push(""),i=""),o+=p.text;break}case"tool-call":{if(!s||(f(),(i.length>0||o.length>0)&&u(),c.has(p.toolCallId)))break;c.add(p.toolCallId);let h=t.get(p.toolCallId)??{title:p.title,status:p.status??"pending"};a.push(`- ${Mx(h.status)} ${Px(h)}`);break}case"tool-call-update":break;case"plan":{f(),u(),n.push("**Plan:**"),n.push("");for(let h of p.entries){let m=h.status==="completed"?"[x]":"[ ]";n.push(`- ${m} ${ro(h.content)}`)}n.push("");break}case"mode-changed":f(),u(),n.push(`_mode: ${ro(p.mode)}_`),n.push("");break;case"model-changed":f(),u(),n.push(`_model: ${ro(p.model)}_`),n.push("");break;case"turn-complete":u();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}u()}function Ex(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Px(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${ro(n.title)}${t}`}function Mx(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function xg(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let i=s[r];if(i.trim().length===0)continue;let o=i.split(`
314
+ `);for(let a=0;a<o.length;a++){let c=o[a],d=ro(c);n.push(a===0&&a===o.length-1?`${t}${d}${t}`:a===0?`${t}${d}`:a===o.length-1?`${d}${t}`:d)}r<s.length-1&&n.push("")}}function ro(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function tf(n){return n.toLocaleString("en-US")}Ft();an();Vo();or();function _x(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>$x(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function $x(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Ag(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Ag(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Ag(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Fx(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Ox=5,Lx=200,Cg=30;async function Eg(n,e,t={}){let s=_x(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Ox,i=t.maxSessions??Lx,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await n.loadHistory(u.sessionId).catch(()=>[]),p=Bx(f,s,r);if(p.snippets.length===0)continue;let h={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(h.title=u.title),d.push(h)}return{query:e,truncated:l,results:d}}function Bx(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Nx(n,o,i,t-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 Nx(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let c=Dx(a).filter(d=>Fx(t,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),h={kind:d.kind,text:Wx(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(h.toolName=d.toolName),o.push(h)}}}return{totalMatches:i,snippets:o}}function Dx(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=cc(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?yt(s.text):cc(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(jx(s))return[];let i=cc(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=qx(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Hx(s);default:return[]}}function Hx(n){let e=Rg(n,"name"),t=Rg(n,"title"),s=[];if(t!==void 0){let a=Pe(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=Pe(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Tg(r);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Tg(i);if(a.length>0){let c={kind:"tool-input",text:Pe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Ux(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Ux(n){let e=n.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=Pe(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=Pe(s);if(r.length>0)return r}}return null}function jx(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function cc(n){if(typeof n=="string")return yt(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?yt(e.text):""}function qx(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=cc(t);s.length>0&&e.push(s)}return e.join("")}function Rg(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Tg(n){try{return JSON.stringify(n)}catch{return""}}function Wx(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Cg),c=Math.min(s.length,o+i.length+Cg),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Mg}from"crypto";function Pg(n){let e=Mg(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function nf(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Pg({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Pg({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let i=io(n.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function io(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Mg(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var lc=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function _g(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Fr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function Fg(n,e,t,s={}){n.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),n.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),n.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Eg(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=et(u.cwd??t.cwd),p=u.agentId??t.agentId,h=io(s),m=h!==void 0?[...u.mcpServers??[],...h.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,agentId:p,mcpServers:m});h!==void 0&&h.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){h!==void 0&&h.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),n.post("/v1/sessions/collect",async(d,l)=>{let u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,h=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let m=await Qu({manager:e,maxAgeMs:f,maxDeletions:p,selection:h,verbose:!1});l.code(200).send(m)}catch(m){l.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m={};(h.mode==="memory"||h.mode==="file")&&(m.mode=h.mode),typeof h.capacityBytes=="number"&&(m.capacityBytes=h.capacityBytes),typeof h.fileCapBytes=="number"&&(m.fileCapBytes=h.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=y=>$g.join(Sa.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(m)}catch(y){return l.code(409).send({error:y.message}),l}}),n.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let h=d.body??{},m=typeof h.chunk=="string"?h.chunk:"",y=h.eof===!0;try{return p.streamWrite(m,y)}catch(w){return l.code(409).send({error:w.message}),l}}),n.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let m=p.priority,y;if(m===null||m===0)y=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)y=m;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),n.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,h=p==="references"?"references":qm(p),m=await e.exportBundle(f,h==="references"?{tools:"references"}:{});if(!m){l.code(404).send({error:"session not found"});return}let y=ua({record:m.record,history:h==="summary"?Wm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:ye,machine:Sa.hostname(),hydraHost:_g(t)}),w=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),l.code(200).send(y)}),n.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=d.query??{},m=h.fold==="true"||h.fold==="1",y=typeof h.paths=="string"&&h.paths.length>0?new Set(h.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,w=no(p.history);y&&(w=w.filter(v=>y.has(v.path))),m&&(w=w.map(v=>({...v,hunks:so(v.hunks)}))),l.code(200).send(w)}),n.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),n.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let h=ua({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:ye,machine:Sa.hostname(),hydraHost:_g(t)}),m=d.query,y=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(dc(h,{includeTools:y}))}),n.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{},h={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){l.code(400).send({error:"forkAt must be a non-empty string"});return}h.forkAt=p.forkAt}if(p.cwd!==void 0){if(typeof p.cwd!="string"||p.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}h.cwd=et(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){l.code(400).send({error:"agentId must be a non-empty string"});return}h.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}h.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){l.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}h.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){l.code(400).send({error:"model must be a non-empty string"});return}h.model=p.model}try{let m=await e.forkSession(f,h);l.code(201).send(m)}catch(m){let y=m;if(y.code===j.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===j.InvalidParams||y.code===j.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),n.post("/v1/sessions/import",async(d,l)=>{let u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=On(u.bundle)}catch(h){l.code(400).send({error:"invalid bundle",details:h.message});return}try{let h=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(h)}catch(h){let m=h;if(m.code===j.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}l.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),h;if(p?h=p.summarizedThroughEntry:h=await e.getSummarizedThroughEntry(f),h===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let m=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),w=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&t.compaction){let T=h??0,E=x.length,N=x.slice(T).reduce((O,K)=>O+JSON.stringify(K.params).length,0);v=Xu(N);let M=p?.currentModel,D=x.at(-1).recordedAt,B=p?.currentUsage;w=hg({summarizedThroughEntry:T,totalEntries:E,unsummarizedChars:N,compactionInFlight:e.getCompactionInFlight(),currentModel:M,lastActivityMs:D,nowMs:Date.now(),config:t.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:h??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...v!=null?{approxTokens:v}:{},...m!=null?{compactionState:m}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),n.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let h=p instanceof Error?p.message:String(p);l.code(409).send({error:h})}}),n.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",h=await e.resolveCanonicalId(u)??u,m=e.get(h),y,w,v=!1,S=1e4,x=[];if(m){p&&(w=m.onBroadcast(E=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(E)+`
315
+ `):(x.push(E),x.length>S&&x.shift()))})),d.raw.on("close",()=>{w?.(),l.raw.writableEnded||l.raw.end()});try{y=await m.getHistorySnapshot()}catch(E){throw w?.(),E}}else{let E=await e.getHistory(h);if(E===void 0)return l.code(404).send({error:"session not found"}),l;y=E}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let E of y??[]){l.raw.write(JSON.stringify(E)+`
316
316
  `);let $=E;typeof $.recordedAt=="number"&&T.add(String($.recordedAt))}for(;x.length>0;){let E=x.splice(0,x.length);for(let $ of E){let N=$,M=typeof N.recordedAt=="number"?String(N.recordedAt):"";M&&T.has(M)||l.raw.write(JSON.stringify($)+`
317
- `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||u!==void 0&&h.recordedAt<u||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let b=m.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=sf.createInterface({input:nf.createReadStream(l),crlfDelay:1/0}),h=o(d,p,u,f),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}n.get("/v1/sessions/events",async(d,l)=>{let u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!cc.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...cc].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),b=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of b)try{let x=L.historyFile(S.sessionId),T=await a(S.sessionId,x,h,m);T.exhausted||v.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,x=1/0;for(let E=0;E<v.length;E++){let $=v[E];$.current!==null&&$.current.ts<x&&(x=$.current.ts,S=E)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
318
- `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let x of v)try{x.rl.close()}catch{}throw S}return l.raw.end(),l}),n.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=f.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(E=>E.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let E of y)if(!cc.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...cc].join(", ")}`}),l;let b=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let E=new Date(f.since);if(isNaN(E.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=E.getTime()}let S=L.historyFile(p),x=nf.createReadStream(S),T=sf.createInterface({input:x,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let E of T){let $=typeof E=="string"?E.trim():"";if($.length===0)continue;let N;try{N=JSON.parse($)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!N||typeof N!="object"||Array.isArray(N)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let M=N;if(typeof M.recordedAt!="number"||typeof M.params!="object"||M.params===null||Array.isArray(M.params))continue;let D=M.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let B=D.update,O=B.sessionUpdate;if(typeof O!="string"||!b.has(O)||v!==void 0&&M.recordedAt<v)continue;let K={ts:new Date(M.recordedAt).toISOString(),kind:O,update:B};B.messageId!==void 0&&B.messageId!==null&&(K.messageId=B.messageId),l.raw.write(JSON.stringify(K)+`
319
- `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),n.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:h.sessionId})}return{flags:p}}),n.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let b=e.get(f);if(b){if(m.length>0&&y.length>0)b.clearAttentionFlag(m,y);else{let E=Array.from(b.listAttentionFlags()).map($=>`${$.source}::${$.reason}`);for(let $ of E)b.clearAttentionFlag($.split("::")[0],$.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let E=`${m}::${y}`;T=x.filter($=>`${$.source}::${$.reason}`!==E)}else T=[];if(T.length===x.length&&T.every((E,$)=>E.source===x[$].source&&E.reason===x[$].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Ft();function _g(n,e,t,s={}){n.get("/v1/agents",async()=>Ni(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.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 bn(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})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await t.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===j.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function $g(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Ux=/^[A-Za-z0-9._-]+$/;function lc(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=t.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(i,o)=>{let a=i.body??{},c=jx(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=t.register(c.config);o.code(201).send(d)}catch(d){Sa(o,d)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(c){Sa(o,c)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await t.startByName(a);o.code(200).send(c)}catch(c){Sa(o,c)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await t.stopByName(a);o.code(200).send(c)}catch(c){Sa(o,c)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await t.restartByName(a);o.code(200).send(c)}catch(c){Sa(o,c)}})}function Sa(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function jx(n){let e=n.name;if(typeof e!="string"||!Ux.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.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=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function Fg(n,e){lc(n,"extension",e)}function Og(n,e){lc(n,"transformer",e)}function Lg(n,e){n.get("/v1/config",async()=>e)}import{z as ro}from"zod";ve();import*as ir from"fs/promises";import*as Hg from"path";import{randomBytes as qx,scrypt as Wx,timingSafeEqual as zx}from"crypto";import{promisify as Kx}from"util";var Ug=Kx(Wx);function rf(){return Hg.join(L.home(),"password-hash")}var Bg=32768,Ng=8,Dg=1,Jx=64,Yx=16,jg=128*1024*1024;async function qg(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=qx(Yx),t=await Ug(n,e,Jx,{N:Bg,r:Ng,p:Dg,maxmem:jg}),s=`scrypt$${Bg}$${Ng}$${Dg}$${e.toString("hex")}$${t.toString("hex")}
320
- `;await ir.mkdir(L.home(),{recursive:!0}),await ir.writeFile(rf(),s,{encoding:"utf8",mode:384})}async function uc(){try{return(await ir.readFile(rf(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fc(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ir.readFile(rf(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let c=await Ug(n,o,a.length,{N:s,r,p:i,maxmem:jg});return c.length!==a.length?!1:zx(c,a)}var Vx=ro.object({password:ro.string().min(1),label:ro.string().min(1).max(256).optional(),ttlSec:ro.number().int().positive().optional()}),Qx=ro.object({id:ro.string().optional()}).optional();function Wg(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Gx(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Vx.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await uc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await fc(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})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=Qx.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.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})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function Gx(n){return n.ip||"unknown"}Br();io();import{nanoid as of}from"nanoid";Ed();Ft();an();import{randomBytes as Kg}from"crypto";import*as Jg from"os";import*as Yg from"path";function se(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function nA(n){if(!n||typeof n!="object")return 512;let s=n.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 dn(n,e,t){let s=n.get(e);if(!s)throw se(j.SessionNotFound,t??`session ${e} not found`);return s}async function pc(n,e){let t=so(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=Kg(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],c=tf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),d;try{d=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(d),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,u=n.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return uA(d,n),Qg(d.sessionId,n),d}function Vg(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=lg({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=ns(t),a=new Kt(o),c={clientId:`hydra_client_${of(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw se(j.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Lh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),lA()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let b={verb:y.verb};return typeof y.argsHint=="string"&&(b.argsHint=y.argsHint),typeof y.description=="string"&&(b.description=y.description),b}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(b=>{if(!b||typeof b!="object")return;let v=b;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let S={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(S.outputSchema=v.outputSchema),S}).filter(b=>b!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,y),{ok:!0,registered:y.length}});let f=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw se(j.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=f(p);if(!e.manager)throw se(j.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(m.value===void 0)throw se(j.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(j.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(j.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(j.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{u.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async f=>{let p=f??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,b=p.route;if(!h)throw se(-32602,"emit_message requires sessionId");if(!m&&b!=="client_broadcast")throw se(-32602,"emit_message requires method");let v=dn(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return v.dischargeClaim(S,y),{ok:!0};if(b==="chain")return{ok:!0,response:await v.emitToChain(i.name,m,y)};if(b==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await v.emitToQueue(i.name,y)}}if(b==="daemon")return{ok:!0,response:await v.emitToChain(i.name,m,y)};if(b==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return v.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(b)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return dn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>oA(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let p=f??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,b=p._meta&&typeof p._meta=="object"?p._meta:void 0,v=b&&b["hydra-acp"]&&typeof b["hydra-acp"]=="object"?b["hydra-acp"]:void 0,S=v&&typeof v.title=="string"?v.title:void 0,x=v&&typeof v.model=="string"?v.model:void 0;if(!m&&y){let $=e.manager.get(y);$&&(m=$.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let T=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:T,transformChain:[],title:S,model:x})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,b=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,v=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...b!==void 0?{mode:b}:{},...v!==void 0?{model:v}:{}})}),a.onRequest("session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let u=async(f,p)=>{let h=f??{};if(typeof h.sessionId!="string")throw se(j.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let b=await e.manager.deleteRecord(m);return{id:m,existed:b}};a.onRequest("session/delete",async f=>(await u(f,"session/delete"),{})),a.onRequest("session/close",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(j.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async f=>{let{id:p,existed:h}=await u(f,"hydra-acp/session/delete");if(!h)throw se(j.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw se(-32602,"await_child requires childSessionId");let b=dn(e.manager,h,`child session ${h} not found`);return new Promise(v=>{let T=[],E=[],$=0,N=!1,M,D,B=!1,O=()=>{B||(B=!0,clearTimeout(K),M?.(),D?.(),v(N?{entries:T,truncated:!0}:{entries:T}))};M=b.onBroadcast(X=>{let Z=nA(X);for(T.push(X),E.push(Z),$+=Z;T.length>0&&(T.length>1e3||$>1048576);)T.shift(),$-=E.shift()??0,N=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&O()});let K=setTimeout(O,y);typeof K.unref=="function"&&K.unref(),D=b.onClose(()=>O())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>aA(f,i.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>dA(f,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let p=f??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw se(j.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw se(j.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>sA(u,e)),a.onRequest("logout",async u=>rA(u,e)),a.onRequest("session/new",async u=>{let f=Bh.parse(u),p=rn(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(O=>typeof O=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Kg(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let K={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],K]}let S,x,T=so(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let E=tf({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:zg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(O){throw b!==void 0&&b.abandon(O instanceof Error?O:void 0),x!==void 0&&x.abandon(O instanceof Error?O:void 0),T!==void 0&&T.abandon(O instanceof Error?O:void 0),O}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let O=y,K=e.mcpTokenRegistry;b.complete($),$.onClose(()=>{K.unbind(O)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let O=S,K=e.mcpTokenRegistry;x.complete($),$.onClose(()=>{K.unbind(O)})}T!==void 0&&T.bindToSession($),Qg($.sessionId,e);let N,M;try{yc(c,$,$.sessionId),N=ka(a,$,c),{entries:M}=await $.attach(N,"full")}catch(O){throw await $.close({deleteRecord:!1}).catch(()=>{}),O}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let O of M){if(a.isClosed())break;await a.notify(O.method,O.params).catch(()=>{})}})()});let D=hc($),B=mc($);return{sessionId:$.sessionId,...D?{modes:D}:{},...B?{models:B}:{},configOptions:$.buildConfigOptions(),_meta:gc(e.manager,$,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=Dh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=rn(f._meta),m=h.resume,y=h.readonly===!0,b=h.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let B=await e.manager.loadFromDisk(v);if(!B)throw se(j.SessionNotFound,`session ${f.sessionId} not found`);let O=await e.manager.loadHistory(v),K=f.clientId??`cli_${of(8)}`;c.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:K,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${K} attachedCount=${c.attached.size} replayed=${O.length}`);for(let X of O)await a.notify(X.method,X.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:K,connectedClients:[K],historyPolicy:"full",replayed:O.length,_meta:cA(B)}}let x=!S;if(!S){let B=await e.manager.loadFromDisk(v),O=B;if(m&&(O={...B,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!O)throw se(j.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(O.agentId,O.upstreamSessionId))throw se(j.SessionNotFound,`session ${f.sessionId} was deleted`);let K=O.originatingClient?O:{...O,originatingClient:c.clientInfo},X=b!==void 0?{...K,forwardedEnv:b}:K;S=await pc(e,{...X,onInstallProgress:zg(a)})}yc(c,S,S.sessionId);let T=ka(a,S,c,f.clientInfo,f.clientId),E=h.replayMode==="drip",{entries:$,appliedPolicy:N}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${N} replayed=${$.length} readonly=${y}${E?" replayMode=drip":""}`),E){let B=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,O=750;(async()=>{let K=null;for(let X of $){let Z=typeof X.recordedAt=="number"?X.recordedAt:null;if(K!==null&&Z!==null){let Q=Math.min(O,Math.max(0,(Z-K)/B));Q>0&&await new Promise(fe=>setTimeout(fe,Q))}Z!==null&&(K=Z);try{await a.notify(X.method,X.params)}catch{return}}})()}else for(let B=0;B<$.length&&!a.isClosed();B++){let O=$[B],K=a.notify(O.method,O.params).catch(()=>{});(B+1)%200===0&&await K}S.replayPendingPermissions(T);let M=hc(S),D=mc(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:N,replayed:$.length,...M?{modes:M}:{},...D?{models:D}:{},configOptions:S.buildConfigOptions(),_meta:gc(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=Hh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw se(j.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[$t]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Uh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Nr).map(jh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(j.InternalError,"agent registry unavailable");return Ni(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw se(j.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=qh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),se(j.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw se(j.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await pc(e,m);let y=ka(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=xd.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=xd.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=zh.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),dn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=xd.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),dn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Kh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),dn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Jh.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw se(j.SessionNotFound,"not attached to session");return dn(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let S=await e.manager.loadFromDisk(h);if(!S)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await pc(e,S)}yc(c,m,m.sessionId);let y=ka(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let b=hc(m),v=mc(m);return{sessionId:m.sessionId,...b?{modes:b}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:gc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let x=await e.manager.loadFromDisk(h);if(!x)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await pc(e,x)}yc(c,m,m.sessionId);let y=ka(a,m,c),{entries:b}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let v=hc(m),S=mc(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:gc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=iA(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),se(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:h}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw se(j.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw se(j.InvalidParams,"session/set_mode requires string modeId");let h=dn(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>se(j.InvalidParams,b),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=dn(e.manager,f.sessionId),y=m.buildConfigOptions().find(b=>b.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(b=>b.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw se(j.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw se(j.MethodNotFound,`Method not found: ${f}`);return d(y,f),dn(e.manager,y).forwardRequest(f,u)})})}async function sA(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw se(j.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw se(j.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,x)=>{if(!Array.isArray(S))throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Yg.isAbsolute(S)?S:h.command,y=p(u.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,x=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...x]}let b={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(b[S]=x);Object.assign(b,h.env);let v=Jg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:b,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw nr(p,a)}}async function rA(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function zg(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Ad,t).catch(()=>{})}}function hc(n){let e=n.availableModes();if(e.length===0)return;let t=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:n.currentMode??e[0].id,availableModes:t}}function mc(n){let e=n.availableModels();if(e.length===0)return;let t=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:n.currentModel??e[0].modelId,availableModels:t}}function iA(n,e){if(!n||typeof n!="object")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:j.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Wi(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.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:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:j.InvalidParams,message:`model "${t.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=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function oA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(j.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw se(j.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw se(j.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return dn(t.manager,r).addTransformer(i),{ok:!0}}async function aA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/set requires string reason");return dn(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function dA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string reason");return dn(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function cA(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[$t]:kd(e,t)}}function gc(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.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(),...t.resurrected===!0?{resurrected:!0}:{}};return Zo(e.agentMeta,kd(s,r))}function lA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ye},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:Zo(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function uA(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Qg(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function ka(n,e,t,s,r){return{clientId:r??`cli_${of(8)}`,connection:n,clientInfo:s}}function yc(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var wc=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as fA}from"crypto";import{McpServer as pA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as hA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ot}from"zod";function*af(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;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 cn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var Gg="Bearer ";function oo(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Gg))return;let t=e.slice(Gg.length).trim();return t.length>0?t:void 0}function mA(n){let e=new pA({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:Ot.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return cn(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:Ot.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return cn(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:Ot.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:Ot.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ot.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:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return cn(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:Ot.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ot.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return cn({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:Ot.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ot.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ot.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ot.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ot.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ot.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ot.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ot.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ot.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 t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return cn(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return cn(t)}),e}var gA=1e4;function Xg(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=mA(a),l=new hA({sessionIdGenerator:()=>fA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=oo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),gA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Pd();import{randomUUID as yA}from"crypto";import{McpServer as wA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as bA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as or}from"zod";function vA(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function SA(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function kA(n){let e=new wA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:or.string().min(1).describe("Case-insensitive substring to search for."),limit:or.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:or.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:u}of af(o)){if(u==="tool_call"&&!r)continue;let f=zi([l]),p=f.toLowerCase().indexOf(t.toLowerCase());if(p<0)continue;let h=vA(u),m=SA(f,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return cn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:or.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:or.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return cn({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(t,o.length-1),c=Math.min(s,o.length-1),d=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),u=zi(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:or.string().optional(),file_path:or.string().optional(),limit:or.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of af(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let b=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(b);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(b,v),d.push(b)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))v.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];for(let p of d){let h=l.get(p);if(t!==void 0&&h.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let y=s.toLowerCase(),b=["file_path","filePath","path"],v=!1;for(let S of b){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,b]of Object.entries(h.rawInput))typeof b=="string"?m[y]=b.length>500?b.slice(0,497)+"\u2026":b:(typeof b=="number"||typeof b=="boolean")&&(m[y]=b);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return cn({calls:u,truncated:f})}),e}var IA=1e4;function Zg(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=kA(a),l=new bA({sessionIdGenerator:()=>yA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=oo(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),IA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var bc=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,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 t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as MA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as _A}from"crypto";import{Server as xA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as AA,ListToolsRequestSchema as CA}from"@modelcontextprotocol/sdk/types.js";function ey(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new xA({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(CA,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(AA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,u=TA(l,c.sendNotification);try{let f=await r(),p=await EA(e.connection,n,d,a.params.arguments??{},f);return PA(p,d)}catch(f){return df(f instanceof Error?f.message:String(f))}finally{u()}}),i}var RA=15e3;function TA(n,e,t=RA){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function EA(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function PA(n,e){if(n===null||typeof n!="object")return df(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:df(`extension ${e} omitted content array`)}function df(n){return{content:[{type:"text",text:n}],isError:!0}}var $A=1e4;function ty(n,e,t){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let u of s.values()){let f=u.get(l);f!==void 0&&(u.delete(l),r(f))}}async function o(l,u){for(let[f,p]of s){if(e.lookup(f)?.session?.sessionId!==l)continue;let m=p.get(u);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(l=>{i(l)});async function a(l,u){let f=s.get(l);f===void 0&&(f=new Map,s.set(l,f),e.addDisposer(l,async()=>{let x=s.get(l);if(x!==void 0){s.delete(l);for(let T of x.values())await r(T)}}));let p=f.get(u);if(p!==void 0)return p.transport;let h=t.lookup(u);if(h===void 0)return;let v=ey(u,h,async()=>{let x=e.lookup(l);if(x===void 0)throw new Error("mcp token no longer bound");if(x.session!==void 0)return x.session.sessionId;let T,E=new Promise(N=>{T=setTimeout(()=>N(void 0),$A)}),$=await Promise.race([x.sessionReady.catch(()=>{}),E]);if(T!==void 0&&clearTimeout(T),$===void 0)throw new Error("session not ready");return $.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async x=>{let T=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:x});if(!T||typeof T!="object")return;let E=T.tools;if(!Array.isArray(E))return;let $=[];for(let N of E){if(!N||typeof N!="object")continue;let M=N;if(typeof M.name!="string"||M.name.length===0||typeof M.description!="string"||M.inputSchema===null||typeof M.inputSchema!="object")continue;let D={name:M.name,description:M.description,inputSchema:M.inputSchema};M.outputSchema!==null&&typeof M.outputSchema=="object"&&(D.outputSchema=M.outputSchema),$.push(D)}return $}}),S=new MA({sessionIdGenerator:()=>_A()});return await v.connect(S),f.set(u,{server:v,transport:S}),S}async function c(l,u){let f=oo(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let h=l.params.name,m=await a(f,h);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${h}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let d={config:{skipAuth:!0}};return n.post("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.get("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.delete("/mcp/:name",d,async(l,u)=>{await c(l,u)}),{notifyToolListChanged:o}}async function oy(n,e){DA(n);let t=n.daemon.tls?await ao.readFile(et(n.daemon.tls.key)):void 0,s=n.daemon.tls?await ao.readFile(et(n.daemon.tls.cert)):void 0;await ao.mkdir(L.home(),{recursive:!0});let{stream:r,fileStream:i}=await BA(n.daemon.logLevel),o=FA({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(OA,{options:{handleProtocols:yh}}),eu(G=>{o.log.info(G)}),su(G=>{o.log.info(G)});let a=await Xd.load(),c=new sc,d=new nc,l=new tc([new Zd(e),new ec(a),d]),u=cg({validator:l});o.addHook("onRequest",async(G,Ie)=>{G.routeOptions.config?.skipAuth||G.url==="/acp"||G.url?.startsWith("/acp?")||await u(G,Ie)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new bd(n,{onFetched:()=>{eg(h,v)}});Yu(G=>o.log.info(G));let m={info:G=>o.log.info(G),warn:G=>o.log.warn(G)},y=G=>er.spawn({...G,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Sh(n.compressToolContent);let b=new Qd,v=new jd(h,y,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:n.npmRegistry,extensionCommands:b,defaultCwd:n.defaultCwd}),S=new Yd(qp(n),void 0,{tokenRegistry:d}),x=new Vd(Wp(n),void 0,{tokenRegistry:d});$g(o,ye,sr(n));let T=new wc,E=new bc,$,N=()=>{if($!==void 0)return $;let G=o.server.address();return $=`http://127.0.0.1:${G&&typeof G=="object"?G.port:n.daemon.port}`,$};Mg(o,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:E,mcpTokenRegistry:T,getDaemonOrigin:N}),_g(o,h,v,{npmRegistry:n.npmRegistry}),Fg(o,S),Og(o,x),Lg(o,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),Wg(o,{store:a,rateLimiter:c}),Xg(o,T),Zg(o,T);let M=ty(o,T,E);Vg(o,{validator:l,manager:v,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(G,Ie)=>S.reportVersion(G,Ie),onTransformerVersion:(G,Ie)=>x.reportVersion(G,Ie),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:E,extensionMcpControls:M,getDaemonOrigin:N,registry:h});let D=!!n.daemon.tls;await o.listen({host:D?"127.0.0.1":n.daemon.host,port:D?0:n.daemon.port});let B=o.server.address(),O=B&&typeof B=="object"?B.port:n.daemon.port,K,X=n.daemon.host,Z=O;if(D&&t&&s){K=NA({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:O,tlsOptions:{key:t,cert:s},logger:o.log});let G=K.address();G&&typeof G=="object"&&(Z=G.port)}await ao.mkdir(L.home(),{recursive:!0}),await Xp({pid:process.pid,host:X,port:Z,loopbackPort:O,startedAt:new Date().toISOString()});let Q={daemonUrl:`http://127.0.0.1:${O}`,daemonHost:"127.0.0.1",daemonPort:O,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${O}/acp`,hydraHome:L.home()};S.setContext(Q),x.setContext(Q),await S.start(),await x.start();try{await v.reconcilePermissionFlags()}catch(G){o.log.warn(`permission flag reconcile failed: ${G.message}`)}v.resurrectPendingQueues().catch(G=>{o.log.warn(`queue replay scan failed: ${G.message}`)}),v.resumePendingCompactions().catch(G=>{o.log.warn(`compaction resume scan failed: ${G.message}`)}),v.resumePendingAgentSwaps().catch(G=>{o.log.warn(`agent-swap resume scan failed: ${G.message}`)});let fe=n.daemon.agentSyncIntervalMinutes*60*1e3,Me=fe>0?tg({registry:h,manager:v,intervalMs:fe,logger:m}):void 0,In=n.daemon.sessionGcIntervalMinutes*60*1e3,De=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,cs=In>0?ng({manager:v,intervalMs:In,maxAgeMs:De,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:E,processRegistry:d,shutdown:async()=>{cs&&cs(),Me&&Me(),clearInterval(f),clearInterval(p);let G=async(Ie,je)=>{try{await je()}catch(Yt){o.log.warn(`shutdown step ${Ie} failed: ${Yt instanceof Error?Yt.message:String(Yt)}`)}};await G("sessionTokenStore.flush",()=>a.flush()),await G("extensions.stop",()=>S.stop()),await G("transformers.stop",()=>x.stop()),await G("manager.closeAll",()=>v.closeAll()),await G("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await G("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await G("manager.flushMetaWrites",()=>v.flushMetaWrites()),await G("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),eu(null),su(null),Yu(null),K&&await G("tlsTerminator.close",()=>new Promise(Ie=>K.close(()=>Ie()))),await G("app.close",()=>o.close());try{sy.unlinkSync(L.pidFile())}catch{}await G("fileStream.flushSync",()=>i.flushSync())}}}async function BA(n){let e=await LA({file:L.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=ny.destination(2);return{stream:ny.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function NA(n){let e=iy.createServer(n.tlsOptions,t=>{let s=ry.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function DA(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}qr();an();ya();Ia();async function ly(n={}){let e=await xe(),t=await Ko();if(await vc(e)){let r=await uo();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
321
- `);return}if(Ci(n,"foreground")){process.title="hydra-daemon";let r=await oy(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
317
+ `)}}return v=!0,w||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let h=p;if(typeof h.recordedAt!="number"||u!==void 0&&h.recordedAt<u||typeof h.params!="object"||h.params===null||Array.isArray(h.params))return null;let m=h.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!l.has(w)?null:{recordedAt:h.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,h={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(h.messageId=p.messageId),h}async function*o(d,l,u,f){for await(let p of l){let h=r(p,u,f);if(h){let m=h.entry.params.update.sessionUpdate;yield{ts:h.recordedAt,row:i(d,h.entry,m)}}}}async function a(d,l,u,f){let p=rf.createInterface({input:sf.createReadStream(l),crlfDelay:1/0}),h=o(d,p,u,f),m=await h.next(),y=m.done?null:m.value;return{sessionId:d,rl:p,gen:h,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}n.get("/v1/sessions/events",async(d,l)=>{let u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!lc.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...lc].join(", ")}`}),l;let h=new Set(p),m;if(u.since!==void 0&&u.since.trim().length>0){let S=new Date(u.since);if(isNaN(S.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;m=S.getTime()}let y=await e.list({includeNonInteractive:!0}),w=m!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=m):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of w)try{let x=L.historyFile(S.sessionId),T=await a(S.sessionId,x,h,m);T.exhausted||v.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,x=1/0;for(let E=0;E<v.length;E++){let $=v[E];$.current!==null&&$.current.ts<x&&(x=$.current.ts,S=E)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
318
+ `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let x of v)try{x.rl.close()}catch{}throw S}return l.raw.end(),l}),n.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let m=f.kinds;if(!m||m.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=m.split(",").map(E=>E.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let E of y)if(!lc.has(E))return l.code(400).send({error:`kind "${E}" is not queryable; allowed kinds: ${[...lc].join(", ")}`}),l;let w=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let E=new Date(f.since);if(isNaN(E.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=E.getTime()}let S=L.historyFile(p),x=sf.createReadStream(S),T=rf.createInterface({input:x,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let E of T){let $=typeof E=="string"?E.trim():"";if($.length===0)continue;let N;try{N=JSON.parse($)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!N||typeof N!="object"||Array.isArray(N)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let M=N;if(typeof M.recordedAt!="number"||typeof M.params!="object"||M.params===null||Array.isArray(M.params))continue;let D=M.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let B=D.update,O=B.sessionUpdate;if(typeof O!="string"||!w.has(O)||v!==void 0&&M.recordedAt<v)continue;let K={ts:new Date(M.recordedAt).toISOString(),kind:O,update:B};B.messageId!==void 0&&B.messageId!==null&&(K.messageId=B.messageId),l.raw.write(JSON.stringify(K)+`
319
+ `)}}catch(E){if(E.code==="ENOENT")return l.raw.end(),l;throw E}return l.raw.end(),l}),n.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let h of f){let m=e.get(h.sessionId),y;m?y=m.listAttentionFlags():y=(await e.store.read(h.sessionId))?.attentionFlags??[];for(let w of y)w.source===u.source&&p.push({...w,sessionId:h.sessionId})}return{flags:p}}),n.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,h=d.body??{},m=typeof h.source=="string"?h.source:"",y=typeof h.reason=="string"?h.reason:"";if((m.length>0||y.length>0)&&!(m.length>0&&y.length>0)){l.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&y.length;let w=e.get(f);if(w){if(m.length>0&&y.length>0)w.clearAttentionFlag(m,y);else{let E=Array.from(w.listAttentionFlags()).map($=>`${$.source}::${$.reason}`);for(let $ of E)w.clearAttentionFlag($.split("::")[0],$.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(m.length>0&&y.length>0){let E=`${m}::${y}`;T=x.filter($=>`${$.source}::${$.reason}`!==E)}else T=[];if(T.length===x.length&&T.every((E,$)=>E.source===x[$].source&&E.reason===x[$].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}Ft();function Og(n,e,t,s={}){n.get("/v1/agents",async()=>Hi(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.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 bn(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})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await t.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===j.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function Lg(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var zx=/^[A-Za-z0-9._-]+$/;function uc(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=t.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(i,o)=>{let a=i.body??{},c=Kx(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=t.register(c.config);o.code(201).send(d)}catch(d){ka(o,d)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(c){ka(o,c)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await t.startByName(a);o.code(200).send(c)}catch(c){ka(o,c)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await t.stopByName(a);o.code(200).send(c)}catch(c){ka(o,c)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await t.restartByName(a);o.code(200).send(c)}catch(c){ka(o,c)}})}function ka(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function Kx(n){let e=n.name;if(typeof e!="string"||!zx.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.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=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function Bg(n,e){uc(n,"extension",e)}function Ng(n,e){uc(n,"transformer",e)}function Dg(n,e){n.get("/v1/config",async()=>e)}import{z as oo}from"zod";ve();import*as ar from"fs/promises";import*as qg from"path";import{randomBytes as Jx,scrypt as Yx,timingSafeEqual as Vx}from"crypto";import{promisify as Qx}from"util";var Wg=Qx(Yx);function of(){return qg.join(L.home(),"password-hash")}var Hg=32768,Ug=8,jg=1,Gx=64,Xx=16,zg=128*1024*1024;async function Kg(n){if(typeof n!="string"||n.length===0)throw new Error("password must be a non-empty string");let e=Jx(Xx),t=await Wg(n,e,Gx,{N:Hg,r:Ug,p:jg,maxmem:zg}),s=`scrypt$${Hg}$${Ug}$${jg}$${e.toString("hex")}$${t.toString("hex")}
320
+ `;await ar.mkdir(L.home(),{recursive:!0}),await ar.writeFile(of(),s,{encoding:"utf8",mode:384})}async function fc(){try{return(await ar.readFile(of(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function pc(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ar.readFile(of(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let c=await Wg(n,o,a.length,{N:s,r,p:i,maxmem:zg});return c.length!==a.length?!1:Vx(c,a)}var Zx=oo.object({password:oo.string().min(1),label:oo.string().min(1).max(256).optional(),ttlSec:oo.number().int().positive().optional()}),eA=oo.object({id:oo.string().optional()}).optional();function Jg(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=tA(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Zx.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await fc())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await pc(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})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=eA.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.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})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function tA(n){return n.ip||"unknown"}Hr();ao();import{nanoid as af}from"nanoid";Pd();Ft();an();import{randomBytes as Vg}from"crypto";import*as Qg from"os";import*as Gg from"path";function se(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function oA(n){if(!n||typeof n!="object")return 512;let s=n.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 dn(n,e,t){let s=n.get(e);if(!s)throw se(j.SessionNotFound,t??`session ${e} not found`);return s}async function hc(n,e){let t=io(n),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=Vg(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...i!==void 0?[i]:[]],c=nf({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),d;try{d=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw t!==void 0&&t.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(t!==void 0&&t.bindToSession(d),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let l=s,u=n.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return mA(d,n),Zg(d.sessionId,n),d}function Xg(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=pg({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=ss(t),a=new Kt(o),c={clientId:`hydra_client_${af(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of c.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);c.attached.clear()});let d=(u,f)=>{if(c.attached.get(u)?.readonly)throw se(j.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Dh.parse(u??{});f.clientInfo?.name&&(c.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),hA()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},h=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let y=m;if(typeof y.verb!="string")return;let w={verb:y.verb};return typeof y.argsHint=="string"&&(w.argsHint=y.argsHint),typeof y.description=="string"&&(w.description=y.description),w}).filter(m=>m!==void 0):[];return u.register(i.name,a,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let h=p??{},m=typeof h.instructions=="string"?h.instructions:void 0,y=Array.isArray(h.tools)?h.tools.map(w=>{if(!w||typeof w!="object")return;let v=w;if(typeof v.name!="string"||v.name.length===0||typeof v.description!="string"||v.inputSchema===null||typeof v.inputSchema!="object")return;let S={name:v.name,description:v.description,inputSchema:v.inputSchema};return v.outputSchema!==null&&typeof v.outputSchema=="object"&&(S.outputSchema=v.outputSchema),S}).filter(w=>w!==void 0):[];if(y.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,y),{ok:!0,registered:y.length}});let f=p=>{let h=p??{};if(typeof h.sessionId!="string"||h.sessionId.length===0)throw se(j.InvalidParams,"sessionId is required");return h.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(h,i.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async p=>{let h=f(p);if(!e.manager)throw se(j.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(h,i.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(m.value===void 0)throw se(j.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw se(j.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(h,i.name,m.key,m.value)}catch(y){throw se(j.InvalidParams,y.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async p=>{let h=f(p),m=p??{};if(typeof m.key!="string"||m.key.length===0)throw se(j.InvalidParams,"key is required");if(!e.manager)throw se(j.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(h,i.name,m.key),{ok:!0}}),e.extensionMcpControls){let p=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async h=>{let m=h??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw se(j.InvalidParams,"refresh_session requires sessionId");return await p.notifyToolListChanged(m.sessionId,i.name),{ok:!0}})}a.onClose(()=>{u.clear(i.name)})}if(i?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async f=>{let p=f??{},h=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,h),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let y of e.manager.liveSessions())y.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,y=p.envelope,w=p.route;if(!h)throw se(-32602,"emit_message requires sessionId");if(!m&&w!=="client_broadcast")throw se(-32602,"emit_message requires method");let v=dn(e.manager,h),S=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(S)return v.dischargeClaim(S,y),{ok:!0};if(w==="chain")return{ok:!0,response:await v.emitToChain(i.name,m,y)};if(w==="queue"){if(m!=="session/prompt")throw se(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await v.emitToQueue(i.name,y)}}if(w==="daemon")return{ok:!0,response:await v.emitToChain(i.name,m,y)};if(w==="client_broadcast"){if(!y||typeof y!="object")throw se(-32602,"client_broadcast requires an envelope object");return v.broadcastClientUpdate(y),{ok:!0}}throw se(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let p=f??{},h=typeof p.sessionId=="string"?p.sessionId:void 0;if(!h)throw se(-32602,"hydra-acp/session/request_permission requires sessionId");return dn(e.manager,h).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async f=>lA(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let p=f??{},h=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,w=p._meta&&typeof p._meta=="object"?p._meta:void 0,v=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,S=v&&typeof v.title=="string"?v.title:void 0,x=v&&typeof v.model=="string"?v.model:void 0;if(!m&&y){let $=e.manager.get(y);$&&(m=$.cwd)}if(!m)throw se(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let T=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:h,cwd:m,parentSessionId:y,interactive:T,transformChain:[],title:S,model:x})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"fork_session requires sessionId");let h=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,y=typeof p.agentId=="string"?p.agentId:void 0,w=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,v=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...h!==void 0?{forkAt:h}:{},...m!==void 0?{cwd:m}:{},...y!==void 0?{agentId:y}:{},...w!==void 0?{mode:w}:{},...v!==void 0?{model:v}:{}})}),a.onRequest("session/fork",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/fork requires sessionId");let h=typeof p.cwd=="string"?p.cwd:void 0;return{sessionId:(await e.manager.forkSession(p.sessionId,{...h!==void 0?{cwd:h}:{},mode:"verbatim"})).sessionId}});let u=async(f,p)=>{let h=f??{};if(typeof h.sessionId!="string")throw se(j.InvalidParams,`${p} requires sessionId`);let m=await e.manager.resolveCanonicalId(h.sessionId)??h.sessionId,y=e.manager.get(m);if(y)return await y.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let w=await e.manager.deleteRecord(m);return{id:m,existed:w}};a.onRequest("session/delete",async f=>(await u(f,"session/delete"),{})),a.onRequest("session/close",async f=>{let p=f??{};if(typeof p.sessionId!="string")throw se(j.InvalidParams,"session/close requires sessionId");d(p.sessionId,"session/close");let h=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(h);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(h))return{};throw se(j.SessionNotFound,`session ${h} not found`)}),a.onRequest("hydra-acp/session/delete",async f=>{let{id:p,existed:h}=await u(f,"hydra-acp/session/delete");if(!h)throw se(j.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",y=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!h)throw se(-32602,"await_child requires childSessionId");let w=dn(e.manager,h,`child session ${h} not found`);return new Promise(v=>{let T=[],E=[],$=0,N=!1,M,D,B=!1,O=()=>{B||(B=!0,clearTimeout(K),M?.(),D?.(),v(N?{entries:T,truncated:!0}:{entries:T}))};M=w.onBroadcast(X=>{let Z=oA(X);for(T.push(X),E.push(Z),$+=Z;T.length>0&&(T.length>1e3||$>1048576);)T.shift(),$-=E.shift()??0,N=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&O()});let K=setTimeout(O,y);typeof K.unref=="function"&&K.unref(),D=w.onClose(()=>O())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let p=f??{},h=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!h)throw se(-32602,"close_child_session requires childSessionId");let m=e.manager.get(h);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async f=>uA(f,i.name,e)),a.onRequest("hydra-acp/attention/clear",async f=>fA(f,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let p=f??{},h=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,y=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return h&&m&&e.manager.get(m)?.keepAliveClaim(h,y),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw se(j.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,h=await e.manager.loadToolBlob(p,f.hash);if(h===null)throw se(j.SessionNotFound,"tool content not found");return{content:h}}),a.onRequest("authenticate",async u=>aA(u,e)),a.onRequest("logout",async u=>dA(u,e)),a.onRequest("session/new",async u=>{let f=Hh.parse(u),p=rn(u?._meta),h=Array.isArray(p.transformers)&&p.transformers.every(O=>typeof O=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(h)??[],y,w,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Vg(32).toString("hex"),w=e.mcpTokenRegistry.reserve(y);let K={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],K]}let S,x,T=io(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let E=nf({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Yg(a),transformChain:m,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...E?{mintMcpServersForSwap:E}:{}})}catch(O){throw w!==void 0&&w.abandon(O instanceof Error?O:void 0),x!==void 0&&x.abandon(O instanceof Error?O:void 0),T!==void 0&&T.abandon(O instanceof Error?O:void 0),O}if(y!==void 0&&w!==void 0&&e.mcpTokenRegistry!==void 0){let O=y,K=e.mcpTokenRegistry;w.complete($),$.onClose(()=>{K.unbind(O)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let O=S,K=e.mcpTokenRegistry;x.complete($),$.onClose(()=>{K.unbind(O)})}T!==void 0&&T.bindToSession($),Zg($.sessionId,e);let N,M;try{wc(c,$,$.sessionId),N=Ia(a,$,c),{entries:M}=await $.attach(N,"full")}catch(O){throw await $.close({deleteRecord:!1}).catch(()=>{}),O}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let O of M){if(a.isClosed())break;await a.notify(O.method,O.params).catch(()=>{})}})()});let D=mc($),B=gc($);return{sessionId:$.sessionId,...D?{modes:D}:{},...B?{models:B}:{},configOptions:$.buildConfigOptions(),_meta:yc(e.manager,$,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=jh.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let h=rn(f._meta),m=h.resume,y=h.readonly===!0,w=h.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${y}`);let v=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let B=await e.manager.loadFromDisk(v);if(!B)throw se(j.SessionNotFound,`session ${f.sessionId} not found`);let O=await e.manager.loadHistory(v),K=f.clientId??`cli_${af(8)}`;c.attached.set(B.hydraSessionId,{sessionId:B.hydraSessionId,clientId:K,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${B.hydraSessionId} clientId=${K} attachedCount=${c.attached.size} replayed=${O.length}`);for(let X of O)await a.notify(X.method,X.params).catch(()=>{});return{sessionId:B.hydraSessionId,clientId:K,connectedClients:[K],historyPolicy:"full",replayed:O.length,_meta:pA(B)}}let x=!S;if(!S){let B=await e.manager.loadFromDisk(v),O=B;if(m&&(O={...B,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!O)throw se(j.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(O.agentId,O.upstreamSessionId))throw se(j.SessionNotFound,`session ${f.sessionId} was deleted`);let K=O.originatingClient?O:{...O,originatingClient:c.clientInfo},X=w!==void 0?{...K,forwardedEnv:w}:K;S=await hc(e,{...X,onInstallProgress:Yg(a)})}wc(c,S,S.sessionId);let T=Ia(a,S,c,f.clientInfo,f.clientId),E=h.replayMode==="drip",{entries:$,appliedPolicy:N}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:E,...h.toolContent!==void 0?{toolContent:h.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),w!==void 0&&await e.manager.setForwardedEnv(S.sessionId,w).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${N} replayed=${$.length} readonly=${y}${E?" replayMode=drip":""}`),E){let B=h.dripSpeed&&h.dripSpeed>0?h.dripSpeed:1,O=750;(async()=>{let K=null;for(let X of $){let Z=typeof X.recordedAt=="number"?X.recordedAt:null;if(K!==null&&Z!==null){let Q=Math.min(O,Math.max(0,(Z-K)/B));Q>0&&await new Promise(fe=>setTimeout(fe,Q))}Z!==null&&(K=Z);try{await a.notify(X.method,X.params)}catch{return}}})()}else for(let B=0;B<$.length&&!a.isClosed();B++){let O=$[B],K=a.notify(O.method,O.params).catch(()=>{});(B+1)%200===0&&await K}S.replayPendingPermissions(T);let M=mc(S),D=gc(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:N,replayed:$.length,...M?{modes:M}:{},...D?{models:D}:{},configOptions:S.buildConfigOptions(),_meta:yc(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=qh.parse(u),p=c.attached.get(f.sessionId);if(!p)throw se(j.SessionNotFound,"client not attached to that session");let h=e.manager.get(f.sessionId);return h?.detach(p.clientId),c.attached.delete(f.sessionId),h&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[$t]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Wh.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==Ur).map(zh)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw se(j.InternalError,"agent registry unavailable");return Hi(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async u=>{let f=u??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw se(j.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async u=>{let f=Kh.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),se(j.SessionNotFound,"not attached to session");let h=e.manager.get(f.sessionId);if(!h){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw se(j.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),h=await hc(e,m);let y=Ia(a,h,c,void 0,p.clientId);await h.attach(y,"none")}return h.prompt(p.clientId,f)});let l=u=>{let f;try{f=Ad.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let h=e.manager.get(f.sessionId);h&&h.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=Ad.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Yh.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),dn(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Ad.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),dn(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Vh.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),dn(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Qh.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw se(j.SessionNotFound,"not attached to session");return dn(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/resume requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let S=await e.manager.loadFromDisk(h);if(!S)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await hc(e,S)}wc(c,m,m.sessionId);let y=Ia(a,m,c);await m.attach(y,"pending_only"),c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1}),m.replayPendingPermissions(y);let w=mc(m),v=gc(m);return{sessionId:m.sessionId,...w?{modes:w}:{},...v?{models:v}:{},configOptions:m.buildConfigOptions(),_meta:yc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw se(j.InvalidParams,"session/load requires sessionId");let h=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(h);if(!m){let x=await e.manager.loadFromDisk(h);if(!x)throw se(j.SessionNotFound,`session ${p} not found in memory or on disk`);m=await hc(e,x)}wc(c,m,m.sessionId);let y=Ia(a,m,c),{entries:w}=await m.attach(y,"pending_only");c.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:y.clientId,readonly:!1});for(let x of w){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}m.replayPendingPermissions(y);let v=mc(m),S=gc(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:yc(e.manager,m,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=cA(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),se(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:h}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:h});return p.session.applyModelChange(h),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw se(j.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw se(j.InvalidParams,"session/set_mode requires string modeId");let h=dn(e.manager,f.sessionId),m=await h.forwardRequest("session/set_mode",u);return h.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=w=>se(j.InvalidParams,w),h=f?.sessionId;if(typeof h=="string"&&d(h,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=dn(e.manager,f.sessionId),y=m.buildConfigOptions().find(w=>w.id===f.configId);if(!y)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!y.options.some(w=>w.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),h=f.startsWith("session/"),m=f.startsWith("hydra-acp/");if(!h&&!m||u===null||typeof u!="object"||p.has(f))throw se(j.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw se(j.MethodNotFound,`Method not found: ${f}`);return d(y,f),dn(e.manager,y).forwardRequest(f,u)})})}async function aA(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw se(j.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let p=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let c=a.authMethods??[],d=c.find(p=>p.id===s);if(!d){let p=c.map(h=>h.id);throw se(j.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(h=>JSON.stringify(h)).join(", ")}]`)}let l=d._meta?.type,u=(()=>{let p=d._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((d.type??(l==="agent"||l==="terminal"?l:u!==void 0?"terminal":"agent"))==="terminal"){let p=(S,x)=>{if(!Array.isArray(S))throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be a string[]; got ${S===null?"null":typeof S}`);for(let T of S)if(typeof T!="string")throw se(j.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${x} must be string[]; got non-string entry ${JSON.stringify(T)}`);return S},h=await e.manager.planSpawnForAgent(a.agentId),m,y;if(u?.args!==void 0){let S=typeof u.command=="string"?u.command:void 0;m=S!==void 0&&Gg.isAbsolute(S)?S:h.command,y=p(u.args,'_meta["terminal-auth"].args')}else{let S=d.args!==void 0?{raw:d.args,label:"args"}:d._meta?.args!==void 0?{raw:d._meta.args,label:"_meta.args"}:void 0,x=S!==void 0?p(S.raw,S.label):[];m=h.command,y=[...h.args,...x]}let w={};for(let[S,x]of Object.entries(process.env))typeof x=="string"&&(w[S]=x);Object.assign(w,h.env);let v=Qg.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:y,env:w,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw rr(p,a)}}async function dA(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,i=typeof s?.agentId=="string"?s.agentId:void 0,o=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!o||!o.isAlive()){let a=i??e.defaultAgent;o=await e.manager.bootstrapAgentForAuth(a)}return await o.connection.request("logout",{})}function Yg(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(Cd,t).catch(()=>{})}}function mc(n){let e=n.availableModes();if(e.length===0)return;let t=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:n.currentMode??e[0].id,availableModes:t}}function gc(n){let e=n.availableModels();if(e.length===0)return;let t=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:n.currentModel??e[0].modelId,availableModels:t}}function cA(n,e){if(!n||typeof n!="object")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:j.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:j.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),i=Ki(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.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:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:j.InvalidParams,message:`model "${t.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=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function lA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw se(j.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw se(j.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw se(j.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return dn(t.manager,r).addTransformer(i),{ok:!0}}async function uA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/set requires string reason");return dn(t.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function fA(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw se(j.InvalidParams,"hydra-acp/attention/clear requires string reason");return dn(t.manager,r).clearAttentionFlag(e,i),{ok:!0}}function pA(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[$t]:Id(e,t)}}function yc(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.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(),...t.resurrected===!0?{resurrected:!0}:{}};return ea(e.agentMeta,Id(s,r))}function hA(){return{protocolVersion:1,agentInfo:{name:"hydra",version:ye},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:ea(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function mA(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Zg(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Ia(n,e,t,s,r){return{clientId:r??`cli_${af(8)}`,connection:n,clientInfo:s}}function wc(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var bc=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as gA}from"crypto";import{McpServer as yA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as wA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ot}from"zod";function*df(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;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 cn(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var ey="Bearer ";function co(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(ey))return;let t=e.slice(ey.length).trim();return t.length>0?t:void 0}function bA(n){let e=new yA({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:Ot.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return cn(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:Ot.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return cn(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:Ot.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:Ot.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Ot.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:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return cn(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:Ot.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Ot.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo();return cn({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:Ot.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Ot.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Ot.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Ot.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Ot.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Ot.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Ot.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Ot.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Ot.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 t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return cn(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return cn(t)}),e}var vA=1e4;function ty(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=bA(a),l=new wA({sessionIdGenerator:()=>gA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=co(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),vA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0){a.code(503).send({error:"session not ready"});return}l=h}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Md();import{randomUUID as SA}from"crypto";import{McpServer as kA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as IA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as dr}from"zod";function xA(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function AA(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>n.length&&(i=n.length-148,i<0&&(i=0));let a=n.slice(i,o);return i>0&&(a="\u2026"+a),o<n.length&&(a=a+"\u2026"),a}function CA(n){let e=new kA({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:dr.string().min(1).describe("Case-insensitive substring to search for."),limit:dr.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:dr.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:u}of df(o)){if(u==="tool_call"&&!r)continue;let f=Ji([l]),p=f.toLowerCase().indexOf(t.toLowerCase());if(p<0)continue;let h=xA(u),m=AA(f,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:h,snippet:m,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return cn({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:dr.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:dr.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return cn({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let i=s-t+1;if(i>50)throw new Error(`range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(t,o.length-1),c=Math.min(s,o.length-1),d=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),u=Ji(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:d}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:dr.string().optional(),file_path:dr.string().optional(),limit:dr.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let i=await n();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return cn({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[],l=new Map;for(let{entryId:p,entry:h,kind:m,update:y}of df(c)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let w=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:`__noid_${p}`,v=l.get(w);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},l.set(w,v),d.push(w)),typeof y.name=="string"&&y.name.length>0?v.toolName=y.name:(v.toolName==="(unnamed)"||m==="tool_call")&&typeof y.title=="string"&&y.title.length>0&&(v.toolName=y.title);let S=y.rawInput;if(S&&typeof S=="object"&&!Array.isArray(S)&&Object.keys(S).length>0)for(let[x,T]of Object.entries(S))v.rawInput[x]=T;if(Array.isArray(y.locations))for(let x of y.locations){let T=x?.path;typeof T=="string"&&T.length>0&&!v.locations.includes(T)&&v.locations.push(T)}typeof y.status=="string"&&(v.status=y.status),h.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(h.recordedAt))}let u=[];for(let p of d){let h=l.get(p);if(t!==void 0&&h.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let y=s.toLowerCase(),w=["file_path","filePath","path"],v=!1;for(let S of w){let x=h.rawInput[S];if(typeof x=="string"&&x.toLowerCase().includes(y)){v=!0;break}}if(!v){for(let S of h.locations)if(S.toLowerCase().includes(y)){v=!0;break}}if(!v)continue}let m={};for(let[y,w]of Object.entries(h.rawInput))typeof w=="string"?m[y]=w.length>500?w.slice(0,497)+"\u2026":w:(typeof w=="number"||typeof w=="boolean")&&(m[y]=w);if(h.locations.length>0&&m.locations===void 0&&(m.locations=h.locations),u.push({entryId:h.entryId,tool:h.toolName,args:m,status:h.status,timestamp:h.timestamp}),u.length>=r)break}let f=u.length>=r;return cn({calls:u,truncated:f})}),e}var RA=1e4;function ny(n,e){let t=new Map;async function s(o,a){let c=t.get(o);if(c!==void 0)return c.transport;let d=CA(a),l=new IA({sessionIdGenerator:()=>SA()});await d.connect(l);let u={server:d,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=co(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let u=await s(c,async()=>{if(d.session!==void 0)return d.session;let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),RA)}),h=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),h===void 0)throw new Error("recall: session not ready");return h});a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var vc=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,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 t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as OA}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as LA}from"crypto";import{Server as TA}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as EA,ListToolsRequestSchema as PA}from"@modelcontextprotocol/sdk/types.js";function sy(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,i=new TA({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return i.setRequestHandler(PA,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(o)}}catch{}return{tools:e.tools.map(o)}}),i.setRequestHandler(EA,async(a,c)=>{let d=a.params.name,l=c._meta?.progressToken??c.requestId,u=_A(l,c.sendNotification);try{let f=await r(),p=await $A(e.connection,n,d,a.params.arguments??{},f);return FA(p,d)}catch(f){return cf(f instanceof Error?f.message:String(f))}finally{u()}}),i}var MA=15e3;function _A(n,e,t=MA){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function $A(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function FA(n,e){if(n===null||typeof n!="object")return cf(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:cf(`extension ${e} omitted content array`)}function cf(n){return{content:[{type:"text",text:n}],isError:!0}}var BA=1e4;function ry(n,e,t){let s=new Map;async function r(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function i(l){for(let u of s.values()){let f=u.get(l);f!==void 0&&(u.delete(l),r(f))}}async function o(l,u){for(let[f,p]of s){if(e.lookup(f)?.session?.sessionId!==l)continue;let m=p.get(u);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(l=>{i(l)});async function a(l,u){let f=s.get(l);f===void 0&&(f=new Map,s.set(l,f),e.addDisposer(l,async()=>{let x=s.get(l);if(x!==void 0){s.delete(l);for(let T of x.values())await r(T)}}));let p=f.get(u);if(p!==void 0)return p.transport;let h=t.lookup(u);if(h===void 0)return;let v=sy(u,h,async()=>{let x=e.lookup(l);if(x===void 0)throw new Error("mcp token no longer bound");if(x.session!==void 0)return x.session.sessionId;let T,E=new Promise(N=>{T=setTimeout(()=>N(void 0),BA)}),$=await Promise.race([x.sessionReady.catch(()=>{}),E]);if(T!==void 0&&clearTimeout(T),$===void 0)throw new Error("session not ready");return $.sessionId},{peekSessionId:()=>e.lookup(l)?.session?.sessionId,fetchSessionTools:async x=>{let T=await h.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:x});if(!T||typeof T!="object")return;let E=T.tools;if(!Array.isArray(E))return;let $=[];for(let N of E){if(!N||typeof N!="object")continue;let M=N;if(typeof M.name!="string"||M.name.length===0||typeof M.description!="string"||M.inputSchema===null||typeof M.inputSchema!="object")continue;let D={name:M.name,description:M.description,inputSchema:M.inputSchema};M.outputSchema!==null&&typeof M.outputSchema=="object"&&(D.outputSchema=M.outputSchema),$.push(D)}return $}}),S=new OA({sessionIdGenerator:()=>LA()});return await v.connect(S),f.set(u,{server:v,transport:S}),S}async function c(l,u){let f=co(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let h=l.params.name,m=await a(f,h);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${h}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let d={config:{skipAuth:!0}};return n.post("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.get("/mcp/:name",d,async(l,u)=>{await c(l,u)}),n.delete("/mcp/:name",d,async(l,u)=>{await c(l,u)}),{notifyToolListChanged:o}}async function ly(n,e){WA(n);let t=n.daemon.tls?await rs.readFile(et(n.daemon.tls.key)):void 0,s=n.daemon.tls?await rs.readFile(et(n.daemon.tls.cert)):void 0;await rs.mkdir(L.home(),{recursive:!0});let{stream:r,fileStream:i}=await jA(n.daemon.logLevel),o=NA({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(DA,{options:{handleProtocols:vh}}),tu(G=>{o.log.info(G)}),ru(G=>{o.log.info(G)});let a=await Zd.load(),c=new rc,d=new sc,l=new nc([new ec(e),new tc(a),d]),u=fg({validator:l});o.addHook("onRequest",async(G,Ie)=>{G.routeOptions.config?.skipAuth||G.url==="/acp"||G.url?.startsWith("/acp?")||await u(G,Ie)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let h=new vd(n,{onFetched:()=>{sg(h,v)}});Vu(G=>o.log.info(G));let m={info:G=>o.log.info(G),warn:G=>o.log.warn(G)},y=G=>nr.spawn({...G,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});xh(n.compressToolContent);let w=new Gd,v=new qd(h,y,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:n.npmRegistry,extensionCommands:w,defaultCwd:n.defaultCwd}),S=new Vd(Kp(n),void 0,{tokenRegistry:d}),x=new Qd(Jp(n),void 0,{tokenRegistry:d});Lg(o,ye,ir(n));let T=new bc,E=new vc,$,N=()=>{if($!==void 0)return $;let G=o.server.address();return $=`http://127.0.0.1:${G&&typeof G=="object"?G.port:n.daemon.port}`,$};Fg(o,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:E,mcpTokenRegistry:T,getDaemonOrigin:N}),Og(o,h,v,{npmRegistry:n.npmRegistry}),Bg(o,S),Ng(o,x),Dg(o,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),Jg(o,{store:a,rateLimiter:c}),ty(o,T),ny(o,T);let M=ry(o,T,E);Xg(o,{validator:l,manager:v,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(G,Ie)=>S.reportVersion(G,Ie),onTransformerVersion:(G,Ie)=>x.reportVersion(G,Ie),transformers:x,extensionCommands:w,mcpTokenRegistry:T,extensionMcp:E,extensionMcpControls:M,getDaemonOrigin:N,registry:h});let D=!!n.daemon.tls;await o.listen({host:D?"127.0.0.1":n.daemon.host,port:D?0:n.daemon.port});let B=o.server.address(),O=B&&typeof B=="object"?B.port:n.daemon.port,K,X=n.daemon.host,Z=O;if(D&&t&&s){K=qA({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:O,tlsOptions:{key:t,cert:s},logger:o.log});let G=K.address();G&&typeof G=="object"&&(Z=G.port)}await rs.mkdir(L.home(),{recursive:!0}),await th({pid:process.pid,host:X,port:Z,loopbackPort:O,startedAt:new Date().toISOString()});let Q={daemonUrl:`http://127.0.0.1:${O}`,daemonHost:"127.0.0.1",daemonPort:O,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${O}/acp`,hydraHome:L.home()};S.setContext(Q),x.setContext(Q),await S.start(),await x.start();try{await v.reconcilePermissionFlags()}catch(G){o.log.warn(`permission flag reconcile failed: ${G.message}`)}v.resurrectPendingQueues().catch(G=>{o.log.warn(`queue replay scan failed: ${G.message}`)}),v.resumePendingCompactions().catch(G=>{o.log.warn(`compaction resume scan failed: ${G.message}`)}),v.resumePendingAgentSwaps().catch(G=>{o.log.warn(`agent-swap resume scan failed: ${G.message}`)});let fe=n.daemon.agentSyncIntervalMinutes*60*1e3,Me=fe>0?rg({registry:h,manager:v,intervalMs:fe,logger:m}):void 0,In=n.daemon.sessionGcIntervalMinutes*60*1e3,De=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,us=In>0?ig({manager:v,intervalMs:In,maxAgeMs:De,logger:m}):void 0;return{app:o,manager:v,registry:h,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:E,processRegistry:d,shutdown:async()=>{us&&us(),Me&&Me(),clearInterval(f),clearInterval(p);let G=async(Ie,je)=>{try{await je()}catch(Yt){o.log.warn(`shutdown step ${Ie} failed: ${Yt instanceof Error?Yt.message:String(Yt)}`)}};await G("sessionTokenStore.flush",()=>a.flush()),await G("extensions.stop",()=>S.stop()),await G("transformers.stop",()=>x.stop()),await G("manager.closeAll",()=>v.closeAll()),await G("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await G("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await G("manager.flushMetaWrites",()=>v.flushMetaWrites()),await G("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),tu(null),ru(null),Vu(null),K&&await G("tlsTerminator.close",()=>new Promise(Ie=>K.close(()=>Ie()))),await G("app.close",()=>o.close());try{ay.unlinkSync(L.pidFile())}catch{}await G("fileStream.flushSync",()=>i.flushSync())}}}var oy=20;async function UA(n,e){let t=lo.dirname(n),s=lo.basename(n,".log"),r=new RegExp(`^${s}\\.(\\d+)\\.log$`),i;try{i=await rs.readdir(t)}catch{return}let o=[];for(let c of i){let d=c.match(r);d&&o.push({name:c,n:Number(d[1])})}if(o.length<=e)return;o.sort((c,d)=>c.n-d.n);let a=o.slice(0,o.length-e);await Promise.allSettled(a.map(c=>rs.unlink(lo.join(t,c.name))))}async function jA(n){await UA(L.logFile(),oy);let e=await HA({file:L.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:oy,removeOtherLogFiles:!0}}),t=iy.destination(2);return{stream:iy.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function qA(n){let e=cy.createServer(n.tlsOptions,t=>{let s=dy.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&n.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",i),s.on("error",i),t.on("close",()=>i()),s.on("close",()=>i()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function WA(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Kr();an();wa();xa();async function hy(n={}){let e=await xe(),t=await Jo();if(await Sc(e)){let r=await po();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
321
+ `);return}if(Ti(n,"foreground")){process.title="hydra-daemon";let r=await ly(e,t);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
322
322
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
323
323
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
324
324
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
325
325
  `),process.exit(1)},i);c.unref();try{await r.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
326
- `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Sc(),await kc(e);let s=await uo();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
327
- `)}async function uy(){let n=await uo();if(!n){process.stdout.write(`No running daemon found.
326
+ `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}kc(),await Ic(e);let s=await po();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
327
+ `)}async function my(){let n=await po();if(!n){process.stdout.write(`No running daemon found.
328
328
  `);return}try{process.kill(n.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${n.pid}
329
329
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
330
- `)}}async function fy(){let n=await xe();await Ko();let e=await uo();if(e&&Fn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
330
+ `)}}async function gy(){let n=await xe();await Jo();let e=await po();if(e&&Fn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
331
331
  `);try{process.kill(e.pid,"SIGTERM")}catch(t){process.stderr.write(`Failed to signal daemon: ${t.message}
332
- `),process.exit(1)}await KA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
332
+ `),process.exit(1)}await GA(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
333
333
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
334
- `);if(Sc(),await kc(n),await vc(n)){let t=await uo();process.stdout.write(`Daemon restarted on ${n.daemon.host}:${n.daemon.port}`+(t?` pid=${t.pid}`:"")+`
335
- `)}}async function KA(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!Fn(n))return!0;await zA(50)}return!1}async function py(n){await lo(L.currentLogFile(),n,"No daemon log file (daemon never ran?)")}async function hy(){let n=await uo();if(!n){process.stdout.write(`Daemon: not running
334
+ `);if(kc(),await Ic(n),await Sc(n)){let t=await po();process.stdout.write(`Daemon restarted on ${n.daemon.host}:${n.daemon.port}`+(t?` pid=${t.pid}`:"")+`
335
+ `)}}async function GA(n,e=5e3){let t=Date.now()+e;for(;Date.now()<t;){if(!Fn(n))return!0;await QA(50)}return!1}async function yy(n){await fo(L.currentLogFile(),n,"No daemon log file (daemon never ran?)")}async function wy(){let n=await po();if(!n){process.stdout.write(`Daemon: not running
336
336
  `),process.stdout.write(`CLI version: ${ye}
337
337
  `);return}let e=Fn(n.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${n.pid} host=${n.host} port=${n.port} started=${n.startedAt}
338
- `);let t,s;if(e)try{let o=await xe();t=await jr(o),s=sr(o)}catch{}if(!t||t.version===void 0){process.stdout.write(`CLI version: ${ye}
338
+ `);let t,s;if(e)try{let o=await xe();t=await zr(o),s=ir(o)}catch{}if(!t||t.version===void 0){process.stdout.write(`CLI version: ${ye}
339
339
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
340
340
  `);return}let r=t.version===ye,i=t.configDigest!==void 0&&s!==void 0&&t.configDigest===s;if(r&&i){process.stdout.write(`Version: ${ye}
341
341
  `);return}process.stdout.write(`CLI version: ${ye}
342
342
  `),process.stdout.write(`Daemon version: ${t.version}
343
- `),r||process.stdout.write(cy.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(cy.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function uo(){return xs()}Qe();ks();dr();Fr();Yo();Xn();Aa();Hr();import*as vn from"fs/promises";import*as Ry from"os";import*as Sn from"path";Pc();async function Ty(n={}){let e=await xe(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",r=(await Fe(`/v1/sessions${t}`,{expectStatus:200})).body,i=r.sessions,o=n.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
343
+ `),r||process.stdout.write(py.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(py.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function po(){return Cs()}Qe();xs();lr();Br();Vo();Zn();Ca();qr();import*as vn from"fs/promises";import*as My from"os";import*as Sn from"path";Mc();async function _y(n={}){let e=await xe(),t=n.includeNonInteractive||n.all?"?includeNonInteractive=true":"",r=(await Fe(`/v1/sessions${t}`,{expectStatus:200})).body,i=r.sessions,o=n.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
344
344
  `);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.
345
345
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
346
346
  `);return}process.stdout.write(`No active sessions.
347
- `);return}let c=a.slice().sort((y,b)=>{let v=(b.status==="warm"?1:0)-(y.status==="warm"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!n.all){let y=c.filter(x=>x.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(y,y+b),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>yo(y,u)),p={columns:n.columns??e.tui.sessionColumns??mo,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=wo(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(cr(go,h,m,p)+`
348
- `);for(let y of f)process.stdout.write(cr(y,h,m,p)+`
347
+ `);return}let c=a.slice().sort((y,w)=>{let v=(w.status==="warm"?1:0)-(y.status==="warm"?1:0);return v!==0?v:String(w.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!n.all){let y=c.filter(x=>x.status!=="cold").length,w=e.sessionListColdLimit,v=c.slice(y,y+w),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>bo(y,u)),p={columns:n.columns??e.tui.sessionColumns??yo,cwdMaxWidth:e.tui.cwdColumnMaxWidth},h=vo(f,p),m=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(wo,h,m,p)+`
348
+ `);for(let y of f)process.stdout.write(ur(y,h,m,p)+`
349
349
  `);l>0&&process.stdout.write(`
350
350
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
351
- `)}async function Ey(n){n||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
351
+ `)}async function $y(n){n||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
352
352
  `),process.exit(2));let e=await Fe(`/v1/sessions/${n}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
353
353
  `),process.exit(1)),process.stdout.write(`Killed ${n}
354
- `)}async function Py(n){n||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
354
+ `)}async function Fy(n){n||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
355
355
  `),process.exit(2));let e=await Fe(`/v1/sessions/${n}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
356
356
  `),process.exit(1)),process.stdout.write(`Removed ${n}
357
- `)}async function My(n){let e=n.maxAgeDays!==void 0?n.maxAgeDays:0,t={maxAgeDays:e};n.limit!==void 0&&(t.limit=n.limit),t.selection=n.keepUndecided?"explicit":"unpromoted";let r=(await Fe("/v1/sessions/collect",{method:"POST",body:t,expectStatus:200})).body;if(n.json){process.stdout.write(`${JSON.stringify(r,null,2)}
357
+ `)}async function Oy(n){let e=n.maxAgeDays!==void 0?n.maxAgeDays:0,t={maxAgeDays:e};n.limit!==void 0&&(t.limit=n.limit),t.selection=n.keepUndecided?"explicit":"unpromoted";let r=(await Fe("/v1/sessions/collect",{method:"POST",body:t,expectStatus:200})).body;if(n.json){process.stdout.write(`${JSON.stringify(r,null,2)}
358
358
  `);return}let i=n.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.
359
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${po(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
359
+ `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${mo(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
360
360
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
361
361
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
362
- `)}async function _y(n,e,t){n||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
363
- `),process.exit(2));let s=await Er(),r=await fo(),i=t==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(n)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
362
+ `)}async function Ly(n,e,t){n||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
363
+ `),process.exit(2));let s=await _r(),r=await ho(),i=t==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(n)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
364
364
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
365
365
  `)||process.stdout.write(`
366
- `);return}let c=e==="."?lC(o,n):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
367
- `)}async function $y(n,e,t={}){n||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
368
- `),process.exit(2));let s=t.includeTools??!1,r,i,o=await iC(n);if(o!==null){let c=oC(o.raw);r=ac(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${Sn.basename(n,Sn.extname(n))}-${d}.md`}else{let c=await Er(),d=await fo(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(n)}/transcript`);s&&l.searchParams.set("tools","1");let u=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!u.ok){let p=await u.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${u.status}: ${p}
366
+ `);return}let c=e==="."?mC(o,n):e;await vn.mkdir(Sn.dirname(Sn.resolve(c)),{recursive:!0}),await vn.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
367
+ `)}async function By(n,e,t={}){n||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.] [--tools]
368
+ `),process.exit(2));let s=t.includeTools??!1,r,i,o=await lC(n);if(o!==null){let c=uC(o.raw);r=dc(c,{includeTools:s});let d=new Date().toISOString().replace(/[:.]/g,"-");i=`${Sn.basename(n,Sn.extname(n))}-${d}.md`}else{let c=await _r(),d=await ho(),l=new URL(`${d}/v1/sessions/${encodeURIComponent(n)}/transcript`);s&&l.searchParams.set("tools","1");let u=await fetch(l,{headers:{Authorization:`Bearer ${c}`}});if(!u.ok){let p=await u.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${u.status}: ${p}
369
369
  `),process.exit(1)}r=await u.text();let f=new Date().toISOString().replace(/[:.]/g,"-");i=`hydra-${n}-${f}.md`}if(!e){process.stdout.write(r),r.endsWith(`
370
370
  `)||process.stdout.write(`
371
371
  `);return}let a=e==="."?i:e;await vn.mkdir(Sn.dirname(Sn.resolve(a)),{recursive:!0}),await vn.writeFile(a,r,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${a}
372
- `)}async function iC(n){try{if(!(await vn.stat(n)).isFile())return null}catch{return null}let e=await vn.readFile(n,"utf8");try{return{raw:JSON.parse(e)}}catch(t){process.stderr.write(`Failed to parse bundle file: ${t.message}
373
- `),process.exit(1)}}function oC(n){try{return On(n)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
374
- `),process.exit(1)}}async function Fy(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
372
+ `)}async function lC(n){try{if(!(await vn.stat(n)).isFile())return null}catch{return null}let e=await vn.readFile(n,"utf8");try{return{raw:JSON.parse(e)}}catch(t){process.stderr.write(`Failed to parse bundle file: ${t.message}
373
+ `),process.exit(1)}}function uC(n){try{return On(n)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
374
+ `),process.exit(1)}}async function Ny(n,e={}){n||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
375
375
  `),process.exit(2));let t;if(e.cwd!==void 0){let a=Sn.resolve(e.cwd);try{(await vn.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
376
376
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
377
- `),process.exit(1)}t=a}let s;n==="-"?s=await cC():s=await vn.readFile(n,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
378
- `),process.exit(1)}if(e.info===!0){let a=await xe();dC(r,a.tui.cwdColumnMaxWidth);return}let i=await Fe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...t!==void 0?{cwd:t}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
377
+ `),process.exit(1)}t=a}let s;n==="-"?s=await hC():s=await vn.readFile(n,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
378
+ `),process.exit(1)}if(e.info===!0){let a=await xe();pC(r,a.tui.cwdColumnMaxWidth);return}let i=await Fe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...t!==void 0?{cwd:t}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
379
379
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
380
380
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
381
381
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
382
- `)}function aC(n){return{sessionId:n.session.sessionId,cwd:n.session.cwd,agentId:n.session.agentId,currentUsage:n.session.currentUsage,title:n.session.title,importedFromMachine:n.exportedFrom.machine,attachedClients:0,updatedAt:n.session.updatedAt,status:"cold",compactionState:n.session.compactionState}}function dC(n,e){let t;try{t=On(n)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
383
- `),process.exit(1)}let s=aC(t),r=yo(s),i={columns:Ec,cwdMaxWidth:e},o=wo([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(cr(go,o,a,i)+`
384
- `),process.stdout.write(cr(r,o,a,i)+`
382
+ `)}function fC(n){return{sessionId:n.session.sessionId,cwd:n.session.cwd,agentId:n.session.agentId,currentUsage:n.session.currentUsage,title:n.session.title,importedFromMachine:n.exportedFrom.machine,attachedClients:0,updatedAt:n.session.updatedAt,status:"cold",compactionState:n.session.compactionState}}function pC(n,e){let t;try{t=On(n)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
383
+ `),process.exit(1)}let s=fC(t),r=bo(s),i={columns:Pc,cwdMaxWidth:e},o=vo([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ur(wo,o,a,i)+`
384
+ `),process.stdout.write(ur(r,o,a,i)+`
385
385
  `);let c=t.session.upstreamSessionId??"-";process.stdout.write(`
386
386
  lineage: ${t.session.lineageId}
387
387
  exported: ${t.exportedAt} from ${t.exportedFrom.machine} (hydra ${t.exportedFrom.hydraVersion})
@@ -389,75 +389,75 @@ origin session: ${t.session.sessionId}
389
389
  origin upstream: ${c}
390
390
  history entries: ${t.history.length}`+(t.promptHistory?`, prompt history: ${t.promptHistory.length}
391
391
  `:`
392
- `))}async function cC(){let n=[];for await(let e of process.stdin)n.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(n).toString("utf8")}function lC(n,e){let t=n.headers.get("content-disposition");if(t){let r=t.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function Oy(n,e={}){let t=await xe(),s;if(n!==void 0&&n.length>0)s=n;else{let d=await Dt(t),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),u=await ss(d,{cwd:l,all:!0}),f=Rc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
393
- `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=uC(e.host,t),a=ft(s),c=Vp({host:r,port:i,sessionId:a});process.stdout.write(c+`
392
+ `))}async function hC(){let n=[];for await(let e of process.stdin)n.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(n).toString("utf8")}function mC(n,e){let t=n.headers.get("content-disposition");if(t){let r=t.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function Dy(n,e={}){let t=await xe(),s;if(n!==void 0&&n.length>0)s=n;else{let d=await Dt(t),l=e.cwd?Sn.resolve(e.cwd):process.cwd(),u=await is(d,{cwd:l,all:!0}),f=Tc(u,l);f||(process.stderr.write(`No sessions found for ${l}.
393
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=gC(e.host,t),a=ft(s),c=Xp({host:r,port:i,sessionId:a});process.stdout.write(c+`
394
394
  `),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.
395
- `)}function uC(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Cy(n,$n);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Cy(e.daemon.publicHost,$n);return{host:t,port:s,isFallback:!1}}return fC(e.daemon.host)?{host:pC(),port:e.daemon.port,isFallback:!1}:Mr(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 fC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function pC(){let n=Ry.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Cy(n,e){if(n.startsWith("[")){let s=n.indexOf("]");if(s>0){let r=n.slice(1,s),i=n.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 t=n.lastIndexOf(":");if(t>0&&n.indexOf(":")===t){let s=n.slice(0,t),r=Number(n.slice(t+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:n,port:e}}Rf();Pc();If();Qe();ve();Ia();dr();var QC={extension:{singular:"extension",plural:"extensions",logFile:n=>L.extensionLogFile(n)},transformer:{singular:"transformer",plural:"transformers",logFile:n=>L.transformerLogFile(n)}};function Lc(n){if(n&&typeof n=="object"&&"error"in n){let e=n.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function ko(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function Bc(n){let e=QC[n],t=`/v1/${e.plural}`;async function s(){let u=(await Fe(t,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
396
- `);return}let f=u.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?po(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:ko(p.name,f.map(y=>y.name)),status:ko(p.status,f.map(y=>y.status)),version:ko(p.version,f.map(y=>y.version)),pid:ko(p.pid,f.map(y=>y.pid)),restarts:ko(p.restarts,f.map(y=>y.restarts)),started:ko(p.started,f.map(y=>y.started))},m=y=>[y.name.padEnd(h.name),y.status.padEnd(h.status),y.version.padEnd(h.version),y.pid.padStart(h.pid),y.restarts.padStart(h.restarts),y.started.padEnd(h.started),y.log].join(" ");process.stdout.write(m(p)+`
395
+ `)}function gC(n,e){if(n!==void 0&&n.length>0){let{host:t,port:s}=Py(n,$n);return{host:t,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:t,port:s}=Py(e.daemon.publicHost,$n);return{host:t,port:s,isFallback:!1}}return yC(e.daemon.host)?{host:wC(),port:e.daemon.port,isFallback:!1}:Fr(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 yC(n){return n==="0.0.0.0"||n==="::"||n==="0.0.0.0/0"}function wC(){let n=My.hostname();return!n||n.length===0?"127.0.0.1":n.includes(".")?n:`${n}.local`}function Py(n,e){if(n.startsWith("[")){let s=n.indexOf("]");if(s>0){let r=n.slice(1,s),i=n.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 t=n.lastIndexOf(":");if(t>0&&n.indexOf(":")===t){let s=n.slice(0,t),r=Number(n.slice(t+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:n,port:e}}Tf();Mc();xf();Qe();ve();xa();lr();var tR={extension:{singular:"extension",plural:"extensions",logFile:n=>L.extensionLogFile(n)},transformer:{singular:"transformer",plural:"transformers",logFile:n=>L.transformerLogFile(n)}};function Bc(n){if(n&&typeof n=="object"&&"error"in n){let e=n.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function xo(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}function Nc(n){let e=tR[n],t=`/v1/${e.plural}`;async function s(){let u=(await Fe(t,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
396
+ `);return}let f=u.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?mo(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},h={name:xo(p.name,f.map(y=>y.name)),status:xo(p.status,f.map(y=>y.status)),version:xo(p.version,f.map(y=>y.version)),pid:xo(p.pid,f.map(y=>y.pid)),restarts:xo(p.restarts,f.map(y=>y.restarts)),started:xo(p.started,f.map(y=>y.started))},m=y=>[y.name.padEnd(h.name),y.status.padEnd(h.status),y.version.padEnd(h.version),y.pid.padStart(h.pid),y.restarts.padStart(h.restarts),y.started.padEnd(h.started),y.log].join(" ");process.stdout.write(m(p)+`
397
397
  `);for(let y of f)process.stdout.write(m(y)+`
398
398
  `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
399
399
  `)}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]
400
400
  `),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._-]+
401
- `),process.exit(2);return}await xe();let u=await ho(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${Gy(e.singular)} '${d}' already exists in config.
402
- `),process.exit(1);return}let h=Ac(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await lf(u),process.stdout.write(`Added ${e.singular} '${d}' to ${L.config()}
403
- `);let b={name:d,...y};try{let v=await Fe(t,{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}
404
- `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${Lc(v.body)}). Restart the daemon to apply.
401
+ `),process.exit(2);return}await xe();let u=await go(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${tw(e.singular)} '${d}' already exists in config.
402
+ `),process.exit(1);return}let h=Cc(l,e.singular),m=h.command,y={};m.length>0&&(y.command=m),h.args.length>0&&(y.args=h.args),Object.keys(h.env).length>0&&(y.env=h.env),h.enabled||(y.enabled=!1),p[d]=y,await uf(u),process.stdout.write(`Added ${e.singular} '${d}' to ${L.config()}
403
+ `);let w={name:d,...y};try{let v=await Fe(t,{method:"POST",body:w,rethrowNetworkError:!0});if(v.ok){let S=v.body,x=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${x}
404
+ `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${Bc(v.body)}). Restart the daemon to apply.
405
405
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
406
- `),process.exit(2);return}await xe();let l=await ho(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${Gy(e.singular)} '${d}' not found in config.
407
- `),process.exit(1);return}delete f[d],u[e.plural]=f,await lf(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${L.config()}
406
+ `),process.exit(2);return}await xe();let l=await go(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${tw(e.singular)} '${d}' not found in config.
407
+ `),process.exit(1);return}delete f[d],u[e.plural]=f,await uf(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${L.config()}
408
408
  `);try{let p=await Fe(`${t}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
409
- `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Lc(p.body)}).
409
+ `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Bc(p.body)}).
410
410
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
411
411
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
412
- `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Fe(`${t}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${Lc(u.body)}
412
+ `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Fe(`${t}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${Bc(u.body)}
413
413
  `),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${d}: ${f.status}${p}
414
414
  `)}async function a(d){let p=((await Fe(t,{expectStatus:200})).body[e.plural]??[]).filter(m=>d==="start"?m.enabled&&m.status!=="running":m.status==="running");if(p.length===0){let m=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${m}.
415
- `);return}let h=0;for(let m of p)try{let y=await Fe(`${t}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${Lc(y.body)}
416
- `),h+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${m.name}: ${b.status}${v}
415
+ `);return}let h=0;for(let m of p)try{let y=await Fe(`${t}/${encodeURIComponent(m.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${m.name}: ERROR HTTP ${y.status}${Bc(y.body)}
416
+ `),h+=1;continue}let w=y.body,v=w.pid!=null?` pid=${w.pid}`:"";process.stdout.write(`${m.name}: ${w.status}${v}
417
417
  `)}catch(y){process.stdout.write(`${m.name}: ERROR ${y.message}
418
- `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Ic(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
419
- `),process.exit(2);return}let f=e.logFile(l);await lo(f,u,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function Gy(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Kr=Bc("extension"),Xy=Kr.list,Zy=Kr.add,ew=Kr.remove,tw=Kr.start,nw=Kr.stop,sw=Kr.restart,rw=Kr.logs;var Jr=Bc("transformer"),iw=Jr.list,ow=Jr.add,aw=Jr.remove,dw=Jr.start,cw=Jr.stop,lw=Jr.restart,uw=Jr.logs;qc();xa();io();Br();Qe();Fr();qr();Ft();an();Sd();Uf();import pR from"os";import{spawn as hR}from"child_process";async function mR({conn:n,agentId:e,authMethods:t,method:s,spawn:r}){let i;try{let c=await n.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await gR(c,s),u=await Hf(l,{authenticate:f=>n.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
418
+ `),h+=1}h>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=xc(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
419
+ `),process.exit(2);return}let f=e.logFile(l);await fo(f,u,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function tw(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Vr=Nc("extension"),nw=Vr.list,sw=Vr.add,rw=Vr.remove,iw=Vr.start,ow=Vr.stop,aw=Vr.restart,dw=Vr.logs;var Qr=Nc("transformer"),cw=Qr.list,lw=Qr.add,uw=Qr.remove,fw=Qr.start,pw=Qr.stop,hw=Qr.restart,mw=Qr.logs;Wc();Aa();ao();Hr();Qe();Br();Kr();Ft();an();kd();jf();import wR from"os";import{spawn as bR}from"child_process";async function vR({conn:n,agentId:e,authMethods:t,method:s,spawn:r}){let i;try{let c=await n.request("hydra-acp/agents/auth_methods",{agentId:e});i=Array.isArray(c?.authMethods)?c.authMethods:[]}catch{i=void 0}let o=c=>new Promise(d=>{let l=r(c.command,c.args,{stdio:"inherit",env:c.env,cwd:c.cwd});l.on("exit",u=>{d({exitCode:u})}),l.on("error",()=>{d({exitCode:-1})})}),a=async(c,d)=>{let l=await SR(c,s),u=await Uf(l,{authenticate:f=>n.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:d}}}),runTerminalAuth:o});return u.kind==="terminal-completed"?{exitCode:0}:u.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
420
420
  `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
421
421
  `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
422
- `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await n.request("session/new",{cwd:pR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
423
- `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===j.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??t,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function gR(n,e){if(e!==void 0){let s=n.find(i=>i.id===e);if(s)return s;let r=n.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
422
+ `),{exitCode:1})};if(i!==void 0&&i.length>0)return a(i,e);try{return await n.request("session/new",{cwd:wR.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
423
+ `),{exitCode:0}}catch(c){if(c instanceof Error&&"code"in c&&c.code===j.AuthRequired){let d=c.data,l=d?._meta?.["hydra-acp"]?.authMethods??t,u=d?._meta?.["hydra-acp"]?.agentId??e;return a(l,u)}throw c}}async function SR(n,e){if(e!==void 0){let s=n.find(i=>i.id===e);if(s)return s;let r=n.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
424
424
  `),process.exit(2)}if(n.length===1)return n[0];if(process.stdin.isTTY===!0){let s=n.map((c,d)=>`${d+1}) ${c.id} \u2014 ${c.name??c.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
425
425
  ${s.join(`
426
426
  `)}
427
427
  `);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>n.length)&&(process.stderr.write(`invalid selection "${o}" \u2014 enter a number between 1 and ${n.length}
428
428
  `),process.exit(2)),n[a-1]}let t=n.map(s=>s.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${t})
429
- `),process.exit(2)}async function Fw(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
430
- `),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(qc(),gw)),s=await t(n,"hydra agent auth"),r=await xe(),i=await Dt(r);await ar(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Wr(i.wsUrl,o),c=ns(a),d=new Kt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:ye}})}catch{}let l;try{l=await mR({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:hR})}finally{a.close()}process.exit(l.exitCode)}Ia();Hl();dr();async function Ow(n){let e=Ci(n,"force");if(await uc()&&!e){let r=await _i("Current password: ");await fc(r)||(process.stderr.write(`Wrong password.
431
- `),process.exit(1))}let t=await _i("New password: ");t.length===0&&(process.stderr.write(`Password must not be empty.
432
- `),process.exit(2));let s=await _i("Confirm new password: ");t!==s&&(process.stderr.write(`Passwords did not match.
433
- `),process.exit(1)),await qg(t),process.stdout.write(`Password set.
434
- `)}async function Lw(){let e=(await Fe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
435
- `);return}let t={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:Yc(t.id,s.map(o=>o.id)),label:Yc(t.label,s.map(o=>o.label)),createdAt:Yc(t.createdAt,s.map(o=>o.createdAt)),expiresAt:Yc(t.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(t)+`
429
+ `),process.exit(2)}async function Nw(n,e){(n===void 0||n.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
430
+ `),process.exit(2));let{resolveAgentIdOrExit:t}=await Promise.resolve().then(()=>(Wc(),vw)),s=await t(n,"hydra agent auth"),r=await xe(),i=await Dt(r);await cr(r);let o=["acp.v1",`hydra-acp-token.${i.token}`],a=await Jr(i.wsUrl,o),c=ss(a),d=new Kt(c);try{await d.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:ye}})}catch{}let l;try{l=await vR({conn:d,agentId:s,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:bR})}finally{a.close()}process.exit(l.exitCode)}xa();Ul();lr();async function Dw(n){let e=Ti(n,"force");if(await fc()&&!e){let r=await Fi("Current password: ");await pc(r)||(process.stderr.write(`Wrong password.
431
+ `),process.exit(1))}let t=await Fi("New password: ");t.length===0&&(process.stderr.write(`Password must not be empty.
432
+ `),process.exit(2));let s=await Fi("Confirm new password: ");t!==s&&(process.stderr.write(`Passwords did not match.
433
+ `),process.exit(1)),await Kg(t),process.stdout.write(`Password set.
434
+ `)}async function Hw(){let e=(await Fe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
435
+ `);return}let t={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:Vc(t.id,s.map(o=>o.id)),label:Vc(t.label,s.map(o=>o.label)),createdAt:Vc(t.createdAt,s.map(o=>o.createdAt)),expiresAt:Vc(t.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(t)+`
436
436
  `);for(let o of s)process.stdout.write(i(o)+`
437
- `)}async function Bw(n){n||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
437
+ `)}async function Uw(n){n||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
438
438
  `),process.exit(2));let e=await Fe(`/v1/auth/sessions/${n}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${n}
439
439
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${n}
440
440
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
441
- `),process.exit(1)}function Yc(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as fr from"fs";Qe();Fr();qr();jf();Ft();var Vc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Wf(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(qf(e)){if(e.method==="session/new"){let t=e.params??{},s=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"",r=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!qf(e)&&!Wf(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(qf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!Wf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let t=this.pending.get(e.id);if(!t)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=rn(i),a=o.upstreamSessionId,c=o.agentId,d="";(t.kind==="new"||t.kind==="load")&&(d=t.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 t=this.pendingPermissions.get(e);return t&&this.deletePendingPermission(t),t}takePendingPermissionByToolCall(e){let t=this.pendingPermissionsByToolCall.get(e);if(!t||t.length===0)return;let s=t[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let t=this.pendingPermissionsByToolCall.get(e.toolCallId);if(t){let s=t.indexOf(e.requestId);s>=0&&t.splice(s,1),t.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function qf(n){return"method"in n&&"id"in n&&n.id!==void 0}function Wf(n){return!("method"in n)&&"id"in n}Gc();an();ve();Vo();import{writeFileSync as kR}from"fs";var IR=n=>{kR("/proc/self/comm",n)};function Eo(n,e={}){if(process.title=n,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??IR;try{s(e.commName??Vn())}catch{}}function Po(n,e=Vn()){return n.length===0?e:`${e} ${n.join(" ")}`}async function Zc(n){Eo(Po(process.argv.slice(2)),{commName:"hydra-shim"});let e=await xe(),t=n.target??await Dt(e);t.isLocal&&!n.target&&await ar(e);let s=new Vc,r=Cd(process.stdin,process.stdout),i=t.isLocal?async()=>(await Dt(await xe())).wsUrl:t.wsUrl,o=["acp.v1",`hydra-acp-token.${t.token}`],a=new To({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await ER(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
442
- `);for(let l of d)await PR(a,l,s.lastMessageId(l.sessionId))}}});xR({opts:n,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
443
- `),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 xR({opts:n,upstream:e,downstream:t,tracker:s}){e.onMessage(i=>{if(Ww("daemon\u2192client",i),s.observeFromServer(i),n.dangerouslySkipPermissions===!0&&FR(i)){e.send({jsonrpc:"2.0",id:i.id,result:Zr(i.params)});return}AR(i,s,t),t.send(i)});let r={name:n.name,used:!1};t.onMessage(i=>{if(Ww("client\u2192daemon",i),s.observeFromClient(i),_R(i)){e.send($R(i));return}if(MR(i)){if(n.sessionId){e.send(OR(i,n.sessionId));return}let o=i;n.agentId&&(o=Xc(o,{agentId:n.agentId})),n.agentArgs&&n.agentArgs.length>0&&(o=Xc(o,{agentArgs:n.agentArgs})),r.name&&!r.used&&(o=Xc(o,{title:r.name}),r.used=!0),n.model&&(o=Xc(o,{model:n.model})),e.send(o);return}e.send(i)})}function AR(n,e,t){let s=CR(n);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=TR(s);t.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function CR(n){if(!RR(n))return;let t=(n.params??{}).update;if(!(!t||typeof t!="object"||t.sessionUpdate!=="permission_resolved"))return t}function RR(n){return"method"in n&&n.method==="session/update"&&!("id"in n&&n.id!==void 0)}function TR(n){if(n.outcome&&typeof n.outcome=="object")return n.outcome;if(typeof n.chosenOptionId=="string")return{kind:"selected",optionId:n.chosenOptionId}}async function ER(n,e){let t=n.takePendingPermissions();if(t.length!==0){process.stderr.write(`hydra-acp: cancelling ${t.length} pending permission request(s)
444
- `);for(let s of t){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 PR(n,e,t){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}}};t?(r.historyPolicy="after_message",r.afterMessageId=t):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await n.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
441
+ `),process.exit(1)}function Vc(n,e){let t=n.length;for(let s of e)s.length>t&&(t=s.length);return t}import*as hr from"fs";Qe();Br();Kr();qf();Ft();var Qc=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(zf(e)){if(e.id===null)return;let t=this.pendingPermissions.get(e.id);t&&this.deletePendingPermission(t);return}if(Wf(e)){if(e.method==="session/new"){let t=e.params??{},s=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let t=e.params??{},s=typeof t.sessionId=="string"?t.sessionId:"",r=typeof t.cwd=="string"?t.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!Wf(e)&&!zf(e)&&"method"in e){if(e.method==="session/update"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0,p=typeof u.update?.messageId=="string"?u.update.messageId:void 0;f&&p&&this.lastMessageIds.set(f,p)}return}if(Wf(e)){if(e.method==="session/request_permission"){let u=e.params??{},f=typeof u.sessionId=="string"?u.sessionId:void 0;if(f){let p=u.toolCall,h=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,m={requestId:e.id,sessionId:f,toolCallId:h,params:u};if(this.pendingPermissions.set(e.id,m),h){let y=this.pendingPermissionsByToolCall.get(h);y?y.push(e.id):this.pendingPermissionsByToolCall.set(h,[e.id])}}}return}if(!zf(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let t=this.pending.get(e.id);if(!t)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=rn(i),a=o.upstreamSessionId,c=o.agentId,d="";(t.kind==="new"||t.kind==="load")&&(d=t.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 t=this.pendingPermissions.get(e);return t&&this.deletePendingPermission(t),t}takePendingPermissionByToolCall(e){let t=this.pendingPermissionsByToolCall.get(e);if(!t||t.length===0)return;let s=t[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let t=this.pendingPermissionsByToolCall.get(e.toolCallId);if(t){let s=t.indexOf(e.requestId);s>=0&&t.splice(s,1),t.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Wf(n){return"method"in n&&"id"in n&&n.id!==void 0}function zf(n){return!("method"in n)&&"id"in n}Xc();an();ve();Qo();import{writeFileSync as RR}from"fs";var TR=n=>{RR("/proc/self/comm",n)};function Mo(n,e={}){if(process.title=n,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??TR;try{s(e.commName??Qn())}catch{}}function _o(n,e=Qn()){return n.length===0?e:`${e} ${n.join(" ")}`}async function el(n){Mo(_o(process.argv.slice(2)),{commName:"hydra-shim"});let e=await xe(),t=n.target??await Dt(e);t.isLocal&&!n.target&&await cr(e);let s=new Qc,r=Rd(process.stdin,process.stdout),i=t.isLocal?async()=>(await Dt(await xe())).wsUrl:t.wsUrl,o=["acp.v1",`hydra-acp-token.${t.token}`],a=new Po({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await FR(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
442
+ `);for(let l of d)await OR(a,l,s.lastMessageId(l.sessionId))}}});ER({opts:n,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
443
+ `),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 ER({opts:n,upstream:e,downstream:t,tracker:s}){e.onMessage(i=>{if(Yw("daemon\u2192client",i),s.observeFromServer(i),n.dangerouslySkipPermissions===!0&&DR(i)){e.send({jsonrpc:"2.0",id:i.id,result:ni(i.params)});return}PR(i,s,t),t.send(i)});let r={name:n.name,used:!1};t.onMessage(i=>{if(Yw("client\u2192daemon",i),s.observeFromClient(i),BR(i)){e.send(NR(i));return}if(LR(i)){if(n.sessionId){e.send(HR(i,n.sessionId));return}let o=i;n.agentId&&(o=Zc(o,{agentId:n.agentId})),n.agentArgs&&n.agentArgs.length>0&&(o=Zc(o,{agentArgs:n.agentArgs})),r.name&&!r.used&&(o=Zc(o,{title:r.name}),r.used=!0),n.model&&(o=Zc(o,{model:n.model})),e.send(o);return}e.send(i)})}function PR(n,e,t){let s=MR(n);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=$R(s);t.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function MR(n){if(!_R(n))return;let t=(n.params??{}).update;if(!(!t||typeof t!="object"||t.sessionUpdate!=="permission_resolved"))return t}function _R(n){return"method"in n&&n.method==="session/update"&&!("id"in n&&n.id!==void 0)}function $R(n){if(n.outcome&&typeof n.outcome=="object")return n.outcome;if(typeof n.chosenOptionId=="string")return{kind:"selected",optionId:n.chosenOptionId}}async function FR(n,e){let t=n.takePendingPermissions();if(t.length!==0){process.stderr.write(`hydra-acp: cancelling ${t.length} pending permission request(s)
444
+ `);for(let s of t){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 OR(n,e,t){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}}};t?(r.historyPolicy="after_message",r.afterMessageId=t):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await n.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
445
445
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
446
- `)}}function MR(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function _R(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function $R(n){let e=n.params??{},t=e.clientInfo,s=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?n:{...n,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:ye}}}}function FR(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function OR(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var LR=25*1024*1024,qw=!1,ei=null;function Ww(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!qw){qw=!0;try{ei=L.shimWireLogFile(),fr.mkdirSync(L.home(),{recursive:!0});let t=fr.statSync(ei,{throwIfNoEntry:!1});t&&t.size>LR&&fr.renameSync(ei,`${ei}.1`)}catch{ei=null}}if(ei)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
447
- `;fr.appendFile(ei,t,()=>{})}catch{}}}function Xc(n,e){let t=n.params??{},s=t._meta??{},r=s["hydra-acp"]??{};return{...n,params:{...t,_meta:{...s,"hydra-acp":{...r,...e}}}}}Br();io();xa();Qe();Fr();qr();rr();Ft();an();Gc();import{mkdtempSync as JR,rmSync as YR}from"fs";import{tmpdir as VR}from"os";import{join as QR}from"path";function zw(n){let e="",t=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",n.onChunk(a)},o=()=>{s||(s=!0,t=!1,n.scheduleFlushCheck(()=>{if(s=!1,t){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?t=!0:o())},eof(){r||(r=!0,i())}}}So();import BR from"chalk";import NR from"strip-ansi";var el=new BR.Instance({level:3});function Kw(n,e){if(n.length===0)return"";let t=ur(n);if(t.length===0)return"";let s=[];for(let i of t)s.push(DR(i,e));let r=s.join(`
446
+ `)}}function LR(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/new"}function BR(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="initialize"}function NR(n){let e=n.params??{},t=e.clientInfo,s=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?n:{...n,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:ye}}}}function DR(n){return"method"in n&&"id"in n&&n.id!==void 0&&n.method==="session/request_permission"}function HR(n,e){return{jsonrpc:"2.0",id:n.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var UR=25*1024*1024,Jw=!1,si=null;function Yw(n,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!Jw){Jw=!0;try{si=L.shimWireLogFile(),hr.mkdirSync(L.home(),{recursive:!0});let t=hr.statSync(si,{throwIfNoEntry:!1});t&&t.size>UR&&hr.renameSync(si,`${si}.1`)}catch{si=null}}if(si)try{let t=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:n,msg:e})+`
447
+ `;hr.appendFile(si,t,()=>{})}catch{}}}function Zc(n,e){let t=n.params??{},s=t._meta??{},r=s["hydra-acp"]??{};return{...n,params:{...t,_meta:{...s,"hydra-acp":{...r,...e}}}}}Hr();ao();Aa();Qe();Br();Kr();or();Ft();an();Xc();import{mkdtempSync as XR,rmSync as ZR}from"fs";import{tmpdir as e0}from"os";import{join as t0}from"path";function Vw(n){let e="",t=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",n.onChunk(a)},o=()=>{s||(s=!0,t=!1,n.scheduleFlushCheck(()=>{if(s=!1,t){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?t=!0:o())},eof(){r||(r=!0,i())}}}Io();import jR from"chalk";import qR from"strip-ansi";var tl=new jR.Instance({level:3});function Qw(n,e){if(n.length===0)return"";let t=pr(n);if(t.length===0)return"";let s=[];for(let i of t)s.push(WR(i,e));let r=s.join(`
448
448
  `);return r.endsWith(`
449
449
  `)||(r+=`
450
- `),r}function DR(n,e){let t=zR(n.body,e);return e==="ansi"?t=KR(t,n.bodyStyle):t=NR(t),t}var HR="\x1B[1m",UR="\x1B[96m",jR="\x1B[93m",qR="\x1B[0m",WR="\0";function zR(n,e){let t=n.replace(/\^\^/g,WR);return e==="ansi"&&(t=t.replace(/\^\+/g,HR).replace(/\^C/g,UR).replace(/\^Y/g,jR).replace(/\^:/g,qR)),t=t.replace(/\^[+\-:CcKY]/g,""),t=t.replace(/\x00/g,"^"),t}function KR(n,e){if(n.length===0||e===void 0)return n;switch(e){case"heading-1":return el.bold.yellowBright(n);case"heading-2":return el.bold.cyanBright(n);case"heading-3":return el.bold(n);case"dim":return el.dim(n);default:return n}}var GR=1*1024*1024,Jw="mcp__hydra-acp-stdin__";function Yw(n,e){return{sessionId:n,prompt:e,_meta:{[$t]:{ancillary:!0}}}}function XR(n){if(n)for(let e of n.split(/\r?\n/)){let t=e.trim();if(t)return t.length>80?`${t.slice(0,80)}\u2026`:t}}function ZR(n){if(!n||typeof n!="object")return!1;let e=n.toolCall;if(!e||typeof e!="object")return!1;let t=e.title;if(typeof t=="string"&&t.startsWith(Jw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Jw))}async function Vw(n){if(Eo(Po(process.argv.slice(2))),process.stdin.isTTY&&!n.prompt&&!n.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.
451
- `),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let c=JR(QR(VR(),"hydra-cat-"));n.cwd=c,n.detach||process.once("exit",()=>{try{YR(c,{recursive:!0,force:!0})}catch{}})}let e=await xe(),t=n.target??await Dt(e);t.isLocal&&!n.target&&await ar(e);let s=["acp.v1",`hydra-acp-token.${t.token}`],r=await Wr(t.wsUrl,s),i=ns(r),o=new Kt(i),a=await t0({conn:o,opts:n,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:e0(t.baseUrl,t.token)});process.exit(a.exitCode)}function e0(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${n}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:t,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:t,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function t0(n){let{conn:e,opts:t,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=n,c=i?"ansi":"plain",d=t.raw===!0,l=!r&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async Q=>t.dangerouslySkipPermissions?Zr(Q):ZR(Q)?Zr(Q):Hw(Q));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Nr,version:ye}})}catch{}let u=await r0(e,t,l),f=!1,p=!0,h="",m=0,y=Q=>{Q.length!==0&&(o(Q),p=Q.charCodeAt(Q.length-1)===10,f=!0)},b=()=>{if(d||h.length===0)return;let Q=Kw(h,c);if(h="",Q.length===0)return;let fe=m>0?`
452
- `:"";y(fe+Q),m+=1},v=()=>{b(),f&&!p&&y(`
453
- `),f=!1};e.onNotification("session/update",Q=>{let fe=Q?.update,Me=ts(fe,{cwd:t.cwd});if(Me){if(Me.kind==="agent-text"){d?y(Me.text):h+=Me.text;return}if(Me.kind==="turn-complete"){v();return}switch(Me.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 Q=>{let fe=[];if(t.prompt&&!S&&fe.push({type:"text",text:t.prompt}),Q.length>0&&fe.push({type:"text",text:Q}),fe.length!==0){try{await e.request("session/prompt",Yw(u,fe)),S=!0}catch(Me){a(`hydra-acp cat: prompt failed: ${Me.message}
450
+ `),r}function WR(n,e){let t=QR(n.body,e);return e==="ansi"?t=GR(t,n.bodyStyle):t=qR(t),t}var zR="\x1B[1m",KR="\x1B[96m",JR="\x1B[93m",YR="\x1B[0m",VR="\0";function QR(n,e){let t=n.replace(/\^\^/g,VR);return e==="ansi"&&(t=t.replace(/\^\+/g,zR).replace(/\^C/g,KR).replace(/\^Y/g,JR).replace(/\^:/g,YR)),t=t.replace(/\^[+\-:CcKY]/g,""),t=t.replace(/\x00/g,"^"),t}function GR(n,e){if(n.length===0||e===void 0)return n;switch(e){case"heading-1":return tl.bold.yellowBright(n);case"heading-2":return tl.bold.cyanBright(n);case"heading-3":return tl.bold(n);case"dim":return tl.dim(n);default:return n}}var n0=1*1024*1024,Gw="mcp__hydra-acp-stdin__";function Xw(n,e){return{sessionId:n,prompt:e,_meta:{[$t]:{ancillary:!0}}}}function s0(n){if(n)for(let e of n.split(/\r?\n/)){let t=e.trim();if(t)return t.length>80?`${t.slice(0,80)}\u2026`:t}}function r0(n){if(!n||typeof n!="object")return!1;let e=n.toolCall;if(!e||typeof e!="object")return!1;let t=e.title;if(typeof t=="string"&&t.startsWith(Gw))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Gw))}async function Zw(n){if(Mo(_o(process.argv.slice(2))),process.stdin.isTTY&&!n.prompt&&!n.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.
451
+ `),process.exit(2);return}if(!n.sessionId&&n.cwd===void 0&&process.stdin.isTTY!==!0){let c=XR(t0(e0(),"hydra-cat-"));n.cwd=c,n.detach||process.once("exit",()=>{try{ZR(c,{recursive:!0,force:!0})}catch{}})}let e=await xe(),t=n.target??await Dt(e);t.isLocal&&!n.target&&await cr(e);let s=["acp.v1",`hydra-acp-token.${t.token}`],r=await Jr(t.wsUrl,s),i=ss(r),o=new Kt(i),a=await o0({conn:o,opts:n,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:i0(t.baseUrl,t.token)});process.exit(a.exitCode)}function i0(n,e){let t={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${n}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:t,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:t,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function o0(n){let{conn:e,opts:t,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=n,c=i?"ansi":"plain",d=t.raw===!0,l=!r&&t.sessionId===void 0&&t.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async Q=>t.dangerouslySkipPermissions?ni(Q):r0(Q)?ni(Q):Ww(Q));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:Ur,version:ye}})}catch{}let u=await c0(e,t,l),f=!1,p=!0,h="",m=0,y=Q=>{Q.length!==0&&(o(Q),p=Q.charCodeAt(Q.length-1)===10,f=!0)},w=()=>{if(d||h.length===0)return;let Q=Qw(h,c);if(h="",Q.length===0)return;let fe=m>0?`
452
+ `:"";y(fe+Q),m+=1},v=()=>{w(),f&&!p&&y(`
453
+ `),f=!1};e.onNotification("session/update",Q=>{let fe=Q?.update,Me=ns(fe,{cwd:t.cwd});if(Me){if(Me.kind==="agent-text"){d?y(Me.text):h+=Me.text;return}if(Me.kind==="turn-complete"){v();return}switch(Me.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":w();return;default:return}}});let S=!1,x=async Q=>{let fe=[];if(t.prompt&&!S&&fe.push({type:"text",text:t.prompt}),Q.length>0&&fe.push({type:"text",text:Q}),fe.length!==0){try{await e.request("session/prompt",Xw(u,fe)),S=!0}catch(Me){a(`hydra-acp cat: prompt failed: ${Me.message}
454
454
  `);return}v()}},T=0,E,$=new Promise(Q=>{E=Q}),N=!1,M=async Q=>{N||(N=!0,v(),t.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Me=>setTimeout(Me,500))]),await e.close().catch(()=>{}),E({exitCode:Q}))};e.onClose(Q=>{Q&&(a(`hydra-acp cat: ${Q.message}
455
- `),T=1),N||(N=!0,v(),E({exitCode:T}))});let D=[],B=!1,O=!1,K=async()=>{if(!B){B=!0;try{for(;D.length>0;){let Q=D.shift();if(Q===void 0)break;await x(Q)}}finally{B=!1,O&&D.length===0&&await M(T)}}};if(r&&!t.sessionId)return t.prompt&&await x(""),await M(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n0({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:s,stderr:a,sendInline:x,onEof:()=>{O=!0,!B&&D.length===0&&M(T)},onError:Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
455
+ `),T=1),N||(N=!0,v(),E({exitCode:T}))});let D=[],B=!1,O=!1,K=async()=>{if(!B){B=!0;try{for(;D.length>0;){let Q=D.shift();if(Q===void 0)break;await x(Q)}}finally{B=!1,O&&D.length===0&&await M(T)}}};if(r&&!t.sessionId)return t.prompt&&await x(""),await M(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),a0({conn:e,streamClient:n.streamClient,sessionId:u,opts:t,stdin:s,stderr:a,sendInline:x,onEof:()=>{O=!0,!B&&D.length===0&&M(T)},onError:Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
456
456
  `),T=1,O=!0,!B&&D.length===0&&M(T)},onPromptFailed:Q=>{a(`hydra-acp cat: ${Q.message}
457
- `),T=1,O=!0,!B&&D.length===0&&M(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),t.follow===!0||r&&!!t.sessionId){let Q=zw({scheduleFlushCheck:fe=>{let Me=setImmediate(fe);return()=>clearImmediate(Me)},onChunk:fe=>{D.push(fe),K()}});return s.on("data",fe=>{Q.feed(typeof fe=="string"?fe:fe.toString("utf8"))}),s.on("end",()=>{Q.eof(),O=!0,!B&&D.length===0&&M(T)}),s.on("error",fe=>{a(`hydra-acp cat: stdin error: ${fe.message}
457
+ `),T=1,O=!0,!B&&D.length===0&&M(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),t.follow===!0||r&&!!t.sessionId){let Q=Vw({scheduleFlushCheck:fe=>{let Me=setImmediate(fe);return()=>clearImmediate(Me)},onChunk:fe=>{D.push(fe),K()}});return s.on("data",fe=>{Q.feed(typeof fe=="string"?fe:fe.toString("utf8"))}),s.on("end",()=>{Q.eof(),O=!0,!B&&D.length===0&&M(T)}),s.on("error",fe=>{a(`hydra-acp cat: stdin error: ${fe.message}
458
458
  `),T=1,O=!0,!B&&D.length===0&&M(T)}),$}let Z="";return s.on("data",Q=>{Z+=typeof Q=="string"?Q:Q.toString("utf8")}),s.on("end",()=>{O=!0,Z.length>0&&D.push(Z),K()}),s.on("error",Q=>{a(`hydra-acp cat: stdin error: ${Q.message}
459
- `),T=1,O=!0,!B&&D.length===0&&M(T)}),$}function n0(n){let{conn:e,streamClient:t,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=n,c=r.streamThreshold??GR,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let x=v.toString("base64");h=h.then(()=>t.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
460
- `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){n.onPromptFailed(S);return}n.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await t.open(s,T)}catch(T){n.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=s0(r.prompt,v.capacityBytes);e.request("session/prompt",Yw(s,[{type:"text",text:S}])).catch(T=>{n.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),n.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",n.onError)}function s0(n,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:
459
+ `),T=1,O=!0,!B&&D.length===0&&M(T)}),$}function a0(n){let{conn:e,streamClient:t,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=n,c=r.streamThreshold??n0,d="undecided",l=!1,u=[],f=0,p=!1,h=Promise.resolve(),m=(v,S)=>{let x=v.toString("base64");h=h.then(()=>t.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
460
+ `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){n.onPromptFailed(S);return}n.onEof()},w=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await t.open(s,T)}catch(T){n.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(m(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,m(Buffer.alloc(0),!0)),await h.catch(()=>{});let S=d0(r.prompt,v.capacityBytes);e.request("session/prompt",Xw(s,[{type:"text",text:S}])).catch(T=>{n.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||m(Buffer.alloc(0),!0),n.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&w();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){m(S,!1);return}u.push(S),f+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){y();return}if(d==="pivoting"){l=!0;return}d==="file"&&m(Buffer.alloc(0),!0)}),i.on("error",n.onError)}function d0(n,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:
461
461
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
462
462
  - \`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.
463
463
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -472,50 +472,50 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
472
472
  User's question:
473
473
  ${n}`:`${s}
474
474
 
475
- 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 r0(n,e,t){if(e.sessionId)return(await n.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Nr,version:ye}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=XR(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),t&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[$t]:s});let o=await n.request("session/new",i);return rn(o._meta),o.sessionId}Qe();ve();function tl(n){let e=n.split(".").filter(t=>t.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function Qw(n,e){let t=n;for(let s of e){if(t===null||typeof t!="object"||Array.isArray(t))return;t=t[s]}return t}function i0(n){try{return JSON.parse(n)}catch{return n}}function Gw(n){return n===void 0?"":typeof n=="string"?n:JSON.stringify(n,null,2)}async function Xw(n){n||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
476
- `),process.exit(2));let e=tl(n),t=await xe(),s=Qw(t,e);s===void 0&&(process.stderr.write(`config: key '${n}' is unset
477
- `),process.exit(1)),process.stdout.write(`${Gw(s)}
478
- `)}async function Zw(n,e){(!n||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
479
- `),process.exit(2));let t=tl(n),s=i0(e);try{await Is(r=>{let i=r;for(let o=0;o<t.length-1;o++){let a=t[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 '${t.slice(0,o+1).join(".")}' (not an object)`);i=c}i[t[t.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
480
- `),process.exit(1)}process.stdout.write(`set ${n} = ${Gw(s)}
481
- `)}async function eb(n){n||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
482
- `),process.exit(2));let e=tl(n);try{await Is(t=>{let s=t;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(t){process.stderr.write(`${t.message}
475
+ 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 c0(n,e,t){if(e.sessionId)return(await n.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:Ur,version:ye}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=s0(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),t&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[$t]:s});let o=await n.request("session/new",i);return rn(o._meta),o.sessionId}Qe();ve();function nl(n){let e=n.split(".").filter(t=>t.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function eb(n,e){let t=n;for(let s of e){if(t===null||typeof t!="object"||Array.isArray(t))return;t=t[s]}return t}function l0(n){try{return JSON.parse(n)}catch{return n}}function tb(n){return n===void 0?"":typeof n=="string"?n:JSON.stringify(n,null,2)}async function nb(n){n||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
476
+ `),process.exit(2));let e=nl(n),t=await xe(),s=eb(t,e);s===void 0&&(process.stderr.write(`config: key '${n}' is unset
477
+ `),process.exit(1)),process.stdout.write(`${tb(s)}
478
+ `)}async function sb(n,e){(!n||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
479
+ `),process.exit(2));let t=nl(n),s=l0(e);try{await As(r=>{let i=r;for(let o=0;o<t.length-1;o++){let a=t[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 '${t.slice(0,o+1).join(".")}' (not an object)`);i=c}i[t[t.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
480
+ `),process.exit(1)}process.stdout.write(`set ${n} = ${tb(s)}
481
+ `)}async function rb(n){n||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
482
+ `),process.exit(2));let e=nl(n);try{await As(t=>{let s=t;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(t){process.stderr.write(`${t.message}
483
483
  `),process.exit(1)}process.stdout.write(`unset ${n}
484
- `)}async function tb(n){let e=await xe(),t=n?Qw(e,tl(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
484
+ `)}async function ib(n){let e=await xe(),t=n?eb(e,nl(n)):e;t===void 0&&(process.stderr.write(`config: key '${n}' is unset
485
485
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(t,null,2)}
486
- `)}function nb(){process.stdout.write(`${L.config()}
487
- `)}Qe();ks();qr();an();dr();async function ib(n={}){let{report:e,configLoaded:t}=await o0();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
486
+ `)}function ob(){process.stdout.write(`${L.config()}
487
+ `)}Qe();xs();Kr();an();lr();async function cb(n={}){let{report:e,configLoaded:t}=await u0();if(n.json){process.stdout.write(JSON.stringify(e,null,2)+`
488
488
  `);return}process.stdout.write(`CLI: ${e.cli}
489
489
  `),t&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
490
- `),e.daemonReachable&&(sb("Extensions",e.extensions),sb("Transformers",e.transformers)))}function sb(n,e){if(process.stdout.write(`
490
+ `),e.daemonReachable&&(ab("Extensions",e.extensions),ab("Transformers",e.transformers)))}function ab(n,e){if(process.stdout.write(`
491
491
  ${n}:
492
492
  `),e.length===0){process.stdout.write(` (none)
493
493
  `);return}let t=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(t)} ${i.padEnd(s)} ${r.status}
494
- `)}}async function o0(){let n={cli:ye,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await xe()}catch{return{report:n,configLoaded:!1}}let t=await jr(e);if(t!==void 0&&(n.daemonReachable=!0,n.daemon=t.version??null),!n.daemonReachable)return{report:n,configLoaded:!0};let s;try{s=await Er()}catch{return{report:n,configLoaded:!0}}let r=await fo(),i={Authorization:`Bearer ${s}`};return n.extensions=await rb(`${r}/v1/extensions`,i,"extensions"),n.transformers=await rb(`${r}/v1/transformers`,i,"transformers"),{report:n,configLoaded:!0}}async function rb(n,e,t){try{let s=await fetch(n,{headers:e});if(!s.ok)return[];let i=(await s.json())[t];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as a0}from"child_process";import{accessSync as d0,constants as c0,statSync as l0}from"fs";import{delimiter as u0,join as f0}from"path";var p0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function h0(n){return p0.has(n)}function m0(n){for(let e of n)if(e!==void 0&&!e.startsWith("-"))return e}function g0(n){let e=[],t=!1;for(let s of n){if(!t&&s!==void 0&&!s.startsWith("-")){t=!0;continue}s!==void 0&&e.push(s)}return e}function y0(n){try{if(!l0(n).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return d0(n,c0.X_OK),!0}catch{return!1}}function w0(n,e=process.env){let t=e.PATH??e.Path??"";if(t.length===0)return;let s=t.split(u0).filter(o=>o.length>0),r=`hydra-acp-${n}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=f0(o,r+a);if(y0(c))return c}}function b0(n,e){let t=a0(n,e,{stdio:"inherit",env:process.env});t.error&&(process.stderr.write(`hydra-acp: failed to exec ${n}: ${t.error.message}
495
- `),process.exit(1)),typeof t.status=="number"&&process.exit(t.status),t.signal&&process.kill(process.pid,t.signal),process.exit(1)}function ob(n){let e=m0(n);if(e===void 0||h0(e))return!1;let t=w0(e);if(t===void 0)return!1;b0(t,g0(n))}zf();var mr=!1,Ev=!1;function Pv(n){!n||Ev||(Ev=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
496
- `))}async function vE(){let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(Xo(),rh));n();let e=process.argv.slice(2),t=e.indexOf("launch");if(t!==-1){let b=e.slice(0,t),v=e.slice(t+1),S=v[0],x=v.slice(1),{flags:T}=Ml(b);if(_v(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
494
+ `)}}async function u0(){let n={cli:ye,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await xe()}catch{return{report:n,configLoaded:!1}}let t=await zr(e);if(t!==void 0&&(n.daemonReachable=!0,n.daemon=t.version??null),!n.daemonReachable)return{report:n,configLoaded:!0};let s;try{s=await _r()}catch{return{report:n,configLoaded:!0}}let r=await ho(),i={Authorization:`Bearer ${s}`};return n.extensions=await db(`${r}/v1/extensions`,i,"extensions"),n.transformers=await db(`${r}/v1/transformers`,i,"transformers"),{report:n,configLoaded:!0}}async function db(n,e,t){try{let s=await fetch(n,{headers:e});if(!s.ok)return[];let i=(await s.json())[t];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as f0}from"child_process";import{accessSync as p0,constants as h0,statSync as m0}from"fs";import{delimiter as g0,join as y0}from"path";var w0=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","acp","shim","transformer","transformers","tui"]);function b0(n){return w0.has(n)}function v0(n){for(let e of n)if(e!==void 0&&!e.startsWith("-"))return e}function S0(n){let e=[],t=!1;for(let s of n){if(!t&&s!==void 0&&!s.startsWith("-")){t=!0;continue}s!==void 0&&e.push(s)}return e}function k0(n){try{if(!m0(n).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return p0(n,h0.X_OK),!0}catch{return!1}}function I0(n,e=process.env){let t=e.PATH??e.Path??"";if(t.length===0)return;let s=t.split(g0).filter(o=>o.length>0),r=`hydra-acp-${n}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=y0(o,r+a);if(k0(c))return c}}function x0(n,e){let t=f0(n,e,{stdio:"inherit",env:process.env});t.error&&(process.stderr.write(`hydra-acp: failed to exec ${n}: ${t.error.message}
495
+ `),process.exit(1)),typeof t.status=="number"&&process.exit(t.status),t.signal&&process.kill(process.pid,t.signal),process.exit(1)}function lb(n){let e=v0(n);if(e===void 0||b0(e))return!1;let t=I0(e);if(t===void 0)return!1;x0(t,S0(n))}Kf();var wr=!1,$v=!1;function Fv(n){!n||$v||($v=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
496
+ `))}async function AE(){let{installGlobalTlsTrust:n}=await Promise.resolve().then(()=>(Zo(),ah));n();let e=process.argv.slice(2),t=e.indexOf("launch");if(t!==-1){let w=e.slice(0,t),v=e.slice(t+1),S=v[0],x=v.slice(1),{flags:T}=_l(w);if(Lv(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.
497
497
  `),process.exit(2);return}let E=S??kt(T,"agent");if(!E){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
498
- `),process.exit(2);return}let $=await $v(Yl(T),{allowPrompt:!1}),N=kt(T,"name"),M=kt(T,"model");mr=!0;let D=T["dangerously-skip-permissions"]===!0;Pv(D);let B={agentId:E,agentArgs:x,name:N,model:M,dangerouslySkipPermissions:D};$?.sessionId!==void 0&&(B.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(B.target=$.target),await Zc(B);return}Ep(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&ob(e);let{positional:s,flags:r}=Ml(e);if(_v(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${SE()}
499
- `);return}if(r.help===!0){$p(s[0]);return}let i=Ep(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=kt(r,"name"),d=kt(r,"agent"),l=kt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Pv(u);let f=Yl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await $v(f,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
500
- `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){mr=!0,await Mv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}mr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Zc(b);return}switch(a){case"acp":case"shim":{mr=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(b.sessionId=m),y!==void 0&&(b.target=y),await Zc(b);return}case"cat":{let b=Ep(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=kt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let E=_p(r,"stream-threshold");E!==void 0&&(T.streamThreshold=E);let $=_p(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await Dc(d),mr=!0,await Vw(T);return}case"version":{mr=!0,await ib({json:r.json===!0});return}case"init":await mh(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await hy();return}if(S==="start"){await ly(r);return}if(S==="stop"){await uy();return}if(S==="restart"){await fy();return}if(S==="log"||S==="logs"){await py(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
501
- `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=kt(r,"columns"),S;if(v!==void 0)try{S=Ay(v)}catch(x){process.stderr.write(`${x.message}
502
- `),process.exit(2);return}await Ty({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 Qy(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 Vy(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 Ey(s[2]);return}if(b==="remove"){await Py(s[2]);return}if(b==="collect"){let v=kt(r,"max-age-days"),S=kt(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
498
+ `),process.exit(2);return}let $=await Bv(Vl(T),{allowPrompt:!1}),N=kt(T,"name"),M=kt(T,"model");wr=!0;let D=T["dangerously-skip-permissions"]===!0;Fv(D);let B={agentId:E,agentArgs:x,name:N,model:M,dangerouslySkipPermissions:D};$?.sessionId!==void 0&&(B.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(B.target=$.target),await el(B);return}_p(e)===void 0&&!e.some(w=>w==="--prompt"||w.startsWith("--prompt="))&&lb(e);let{positional:s,flags:r}=_l(e);if(Lv(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${CE()}
499
+ `);return}if(r.help===!0){Lp(s[0]);return}let i=_p(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=kt(r,"name"),d=kt(r,"agent"),l=kt(r,"model"),u=r["dangerously-skip-permissions"]===!0;Fv(u);let f=Vl(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,h=await Bv(f,{allowPrompt:p});h!==void 0&&h.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
500
+ `),process.exit(2));let m=h?.sessionId,y=h?.fromUrl?h.target:void 0;if(!a){if(process.stdout.isTTY){wr=!0,await Ov(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}wr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await el(w);return}switch(a){case"acp":case"shim":{wr=!0;let w={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};m!==void 0&&(w.sessionId=m),y!==void 0&&(w.target=y),await el(w);return}case"cat":{let w=_p(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=w??v,x=kt(r,"cwd"),T={prompt:S,sessionId:m,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let E=Op(r,"stream-threshold");E!==void 0&&(T.streamThreshold=E);let $=Op(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await Hc(d),wr=!0,await Zw(T);return}case"version":{wr=!0,await cb({json:r.json===!0});return}case"init":await wh(r);return;case"daemon":{let w=e.indexOf("daemon"),v=e.slice(w+1),S=v[0];if(S===void 0||S==="status"){await wy();return}if(S==="start"){await hy(r);return}if(S==="stop"){await my();return}if(S==="restart"){await gy();return}if(S==="log"||S==="logs"){await yy(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
501
+ `),process.exit(2);return}case"session":case"sessions":{let w=s[1];if(w===void 0||w==="list"){let v=kt(r,"columns"),S;if(v!==void 0)try{S=Ey(v)}catch(x){process.stderr.write(`${x.message}
502
+ `),process.exit(2);return}await _y({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(w==="info"){await ew(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(w==="diff"){await Zy(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(w==="kill"){await $y(s[2]);return}if(w==="remove"){await Fy(s[2]);return}if(w==="collect"){let v=kt(r,"max-age-days"),S=kt(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
503
503
  `),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
504
- `),process.exit(2);return}x.limit=T}await My(x);return}if(b==="export"){let v=kt(r,"out"),S=kt(r,"tools");await _y(s[2],v,S);return}if(b==="transcript"){let v=kt(r,"out"),S=r.tools===!0;await $y(s[2],v,{includeTools:S});return}if(b==="import"){let v=kt(r,"cwd");await Fy(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=kt(r,"host"),S=kt(r,"cwd");await Oy(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
505
- `),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 Xy();return}if(S==="add"){await Zy(x,T);return}if(S==="remove"){await ew(x);return}if(S==="start"){await tw(x);return}if(S==="stop"){await nw(x);return}if(S==="restart"){await sw(x);return}if(S==="log"||S==="logs"){await rw(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
506
- `),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 iw();return}if(S==="add"){await ow(x,T);return}if(S==="remove"){await aw(x);return}if(S==="start"){await dw(x);return}if(S==="stop"){await cw(x);return}if(S==="restart"){await lw(x);return}if(S==="log"||S==="logs"){await uw(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
507
- `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await Ef();return}if(b==="refresh"){await Uc();return}if(b==="install"){await Pf(s[2]);return}if(b==="sync"){await Mf(s[2]);return}if(b==="set"){await $f(s[2],s[3]);return}if(b==="pin"){await Ff(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await Of(S[1],S.slice(2));return}if(b==="remove"){await Lf(s[2]);return}if(b==="uninstall"){await Bf(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=Ic(S);await _f(x,T);return}if(b==="auth"){await Fw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
508
- `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await Uc();return}if(b==="pin"){await jc(!0);return}if(b==="unpin"){await jc(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
509
- `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await Ow(r);return}process.stderr.write(`Unknown auth password action: ${v}
510
- `),process.exit(2);return}if(b===void 0||b==="list"){await Lw();return}if(b==="revoke"){await Bw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
511
- `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await tb(s[2]);return}if(b==="get"){await Xw(s[2]);return}if(b==="set"){await Zw(s[2],s[3]);return}if(b==="unset"){await eb(s[2]);return}if(b==="path"){nb();return}process.stderr.write(`Unknown config subcommand: ${b}
512
- `),process.exit(2);return}case"tui":mr=!0,await Mv(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
513
- `),$p(),process.exit(2)}}async function Mv(n,e){let t=kt(n,"cwd"),s=n.reattach===!0,r=n.new===!0,i=n.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 Dc(e.agentId),Eo(Po(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(Tv(),Rv)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),t!==void 0&&(a.cwd=t),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),n.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
514
- `),process.exit(2)),a.drip=!0;let c=_p(n,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function _p(n,e){let t=n[e];if(t!==void 0){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s}}}function _v(n){let e=Np(n);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
504
+ `),process.exit(2);return}x.limit=T}await Oy(x);return}if(w==="export"){let v=kt(r,"out"),S=kt(r,"tools");await Ly(s[2],v,S);return}if(w==="transcript"){let v=kt(r,"out"),S=r.tools===!0;await By(s[2],v,{includeTools:S});return}if(w==="import"){let v=kt(r,"cwd");await Ny(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(w==="share"){let v=kt(r,"host"),S=kt(r,"cwd");await Dy(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${w}
505
+ `),process.exit(2);return}case"extension":case"extensions":{let w=e.indexOf(a),v=e.slice(w+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await nw();return}if(S==="add"){await sw(x,T);return}if(S==="remove"){await rw(x);return}if(S==="start"){await iw(x);return}if(S==="stop"){await ow(x);return}if(S==="restart"){await aw(x);return}if(S==="log"||S==="logs"){await dw(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
506
+ `),process.exit(2);return}case"transformer":case"transformers":{let w=e.indexOf(a),v=e.slice(w+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await cw();return}if(S==="add"){await lw(x,T);return}if(S==="remove"){await uw(x);return}if(S==="start"){await fw(x);return}if(S==="stop"){await pw(x);return}if(S==="restart"){await hw(x);return}if(S==="log"||S==="logs"){await mw(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
507
+ `),process.exit(2);return}case"agent":case"agents":{let w=s[1];if(w===void 0||w==="list"){await Pf();return}if(w==="refresh"){await jc();return}if(w==="install"){await Mf(s[2]);return}if(w==="sync"){await _f(s[2]);return}if(w==="set"){await Ff(s[2],s[3]);return}if(w==="pin"){await Of(s[2],s[3]);return}if(w==="add"){let v=e.indexOf(a),S=e.slice(v+1);await Lf(S[1],S.slice(2));return}if(w==="remove"){await Bf(s[2]);return}if(w==="uninstall"){await Nf(s[2]);return}if(w==="log"||w==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=xc(S);await $f(x,T);return}if(w==="auth"){await Nw(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${w}
508
+ `),process.exit(2);return}case"registry":{let w=s[1];if(w==="refresh"){await jc();return}if(w==="pin"){await qc(!0);return}if(w==="unpin"){await qc(!1);return}process.stderr.write(`Unknown registry subcommand: ${w}
509
+ `),process.exit(2);return}case"auth":{let w=s[1];if(w==="password"){let v=s[2];if(v===void 0||v==="set"){await Dw(r);return}process.stderr.write(`Unknown auth password action: ${v}
510
+ `),process.exit(2);return}if(w===void 0||w==="list"){await Hw();return}if(w==="revoke"){await Uw(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${w}
511
+ `),process.exit(2);return}case"config":{let w=s[1];if(w===void 0||w==="list"){await ib(s[2]);return}if(w==="get"){await nb(s[2]);return}if(w==="set"){await sb(s[2],s[3]);return}if(w==="unset"){await rb(s[2]);return}if(w==="path"){ob();return}process.stderr.write(`Unknown config subcommand: ${w}
512
+ `),process.exit(2);return}case"tui":wr=!0,await Ov(r,{sessionId:m,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
513
+ `),Lp(),process.exit(2)}}async function Ov(n,e){let t=kt(n,"cwd"),s=n.reattach===!0,r=n.new===!0,i=n.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 Hc(e.agentId),Mo(_o(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(_v(),Mv)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),t!==void 0&&(a.cwd=t),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),n.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
514
+ `),process.exit(2)),a.drip=!0;let c=Op(n,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Op(n,e){let t=n[e];if(t!==void 0){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let s=Number(t);if(Number.isFinite(s))return s}}}function Lv(n){let e=Up(n);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
515
515
 
516
- `),$p(),process.exit(2))}function Ep(n){for(let e=0;e<n.length;e+=1){let t=n[e];if(t!==void 0){if(t==="-p")return n[e+1];if(t.startsWith("-p")&&!t.startsWith("--"))return t.slice(2)}}}async function $v(n,e){try{return await uh(n,e)}catch(t){oe({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`${t.message}
517
- `),process.exit(1)}}function SE(){try{let n=wE(yE(import.meta.url));return JSON.parse(gE(bE(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var Pp=["tui"],Fv=["shim","acp"],xt=["cat"],kl=["launch"],kE=["init"],Il=["daemon"],IE=["version"],pt=["session","sessions"],Va=["extension","extensions"],Qa=["transformer","transformers"],Nn=["agent","agents"],xE=["registry"],Ga=["config"],Mp=["auth"];function $p(n){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[Pp," hydra-acp tui [same flags] Force TUI explicitly."],[Fv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Fv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[xt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[xt," Pipe-friendly headless mode. Reads stdin and sends it"],[xt," as a prompt to a fresh session, streams the agent's"],[xt," response to stdout, exits when stdin closes. A bounded"],[xt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[xt," as one turn; a streaming input (e.g. `tail -f`) is"],[xt," chunked by the natural pauses in the writer. -p is an"],[xt," optional standing instruction prepended to every chunk;"],[xt," if stdin already contains the question, -p is not needed."],[xt," By default, agent markdown is post-processed: ANSI-styled"],[xt," on a TTY, stripped to plain text on a pipe, tables laid"],[xt," out in both modes. Tool calls / thoughts split paragraphs"],[xt," but otherwise stay hidden. --raw bypasses the renderer"],[xt," and emits chunks immediately, the way cat used to behave."],[xt," With --session, attach to an existing session instead"],[xt," of creating a new one. With --detach, the session"],[xt," survives in the daemon for slack/browser/notifier"],[xt," extensions."],[kl," hydra-acp launch <agent> [agent-args...]"],[kl," Shim mode, force daemon to spawn <agent>"],[kl," from the registry. Args after <agent>"],[kl," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[kE," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[Il," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[Il," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[Il," hydra-acp daemon stop|restart"],[Il," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[IE," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[pt," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[pt," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[pt," --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."],[pt," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[pt," --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."],[pt," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[pt," 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)."],[pt," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[pt," 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."],[pt," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[pt," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[pt," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[pt," 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."],[pt," hydra-acp session export <id> [--out <file>|.]"],[pt," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[pt," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[pt," 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"],[pt," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[pt," 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"],[pt," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[pt," 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)."],[Va," hydra-acp extension list List configured extensions and live state"],[Va," hydra-acp extension add <name> [opts] Add an extension to config"],[Va," hydra-acp extension remove <name> Remove an extension from config"],[Va," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[Va," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Qa," hydra-acp transformer list List configured transformers and live state"],[Qa," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Qa," hydra-acp transformer remove <name> Remove a transformer from config"],[Qa," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Qa," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Nn," hydra-acp agent [list] List agents in the cached registry"],[Nn," hydra-acp agent refresh Force a registry re-fetch"],[Nn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Nn," 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>])."],[Nn," 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."],[Nn," 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)."],[Nn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Nn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[xE," 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."],[Nn," 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`"],[Nn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Nn," hydra-acp agent auth <id> Run the auth flow for <id>"],[Ga," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Ga," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Ga," 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."],[Ga," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Ga," hydra-acp config path Print the config file path"],[Mp," hydra-acp auth password [--force] Set the daemon's master password"],[Mp," hydra-acp auth [list] List active session tokens"],[Mp," hydra-acp auth revoke <id> Revoke a session token"],[Pp," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[Pp," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],t=[];for(let s of e){if(typeof s=="string"){t.push(s);continue}if("globalOnly"in s){n===void 0&&t.push(s.globalOnly);continue}let[r,i]=s;(n===void 0||r.includes(n))&&t.push(i)}process.stdout.write(t.join(`
516
+ `),Lp(),process.exit(2))}function _p(n){for(let e=0;e<n.length;e+=1){let t=n[e];if(t!==void 0){if(t==="-p")return n[e+1];if(t.startsWith("-p")&&!t.startsWith("--"))return t.slice(2)}}}async function Bv(n,e){try{return await hh(n,e)}catch(t){oe({src:"cli-fatal",stack:t instanceof Error?t.stack??t.message:String(t)}),process.stderr.write(`${t.message}
517
+ `),process.exit(1)}}function CE(){try{let n=IE(kE(import.meta.url));return JSON.parse(SE(xE(n,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}var $p=["tui"],Nv=["shim","acp"],xt=["cat"],Il=["launch"],RE=["init"],xl=["daemon"],TE=["version"],pt=["session","sessions"],Qa=["extension","extensions"],Ga=["transformer","transformers"],Dn=["agent","agents"],EE=["registry"],Xa=["config"],Fp=["auth"];function Lp(n){let e=["hydra-acp \u2014 multi-client ACP session daemon","","Usage:",{globalOnly:" hydra-acp [--session <id-or-url>] [--reattach] [opts]"},{globalOnly:" Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."},{globalOnly:" With -p / --prompt and no subcommand, auto-dispatch to cat."},[$p," hydra-acp tui [same flags] Force TUI explicitly."],[Nv," hydra-acp acp [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."],[Nv," hydra-acp shim [same flags] Alias for `acp` (kept for backward compatibility)."],[xt," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"],[xt," Pipe-friendly headless mode. Reads stdin and sends it"],[xt," as a prompt to a fresh session, streams the agent's"],[xt," response to stdout, exits when stdin closes. A bounded"],[xt,' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'],[xt," as one turn; a streaming input (e.g. `tail -f`) is"],[xt," chunked by the natural pauses in the writer. -p is an"],[xt," optional standing instruction prepended to every chunk;"],[xt," if stdin already contains the question, -p is not needed."],[xt," By default, agent markdown is post-processed: ANSI-styled"],[xt," on a TTY, stripped to plain text on a pipe, tables laid"],[xt," out in both modes. Tool calls / thoughts split paragraphs"],[xt," but otherwise stay hidden. --raw bypasses the renderer"],[xt," and emits chunks immediately, the way cat used to behave."],[xt," With --session, attach to an existing session instead"],[xt," of creating a new one. With --detach, the session"],[xt," survives in the daemon for slack/browser/notifier"],[xt," extensions."],[Il," hydra-acp launch <agent> [agent-args...]"],[Il," Shim mode, force daemon to spawn <agent>"],[Il," from the registry. Args after <agent>"],[Il," are forwarded to the agent's command."],"",...(()=>{let s=["tui","shim","acp","cat","launch"];return[[s,"Session selection (any entry point):"],[s," --session <id> Attach to a local session by id."],[s," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"],[s," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"],[s," falling back to a password prompt \u2014 but only on the TUI path)."],[s," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."],[s," --reattach Pick the most-recent session for the current cwd."],[s," --new Force a fresh session."],[s," --readonly Open a session as a transcript viewer (requires --session)."],[s," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."],[s," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."]]})(),[RE," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"],[xl," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"],[xl," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"],[xl," hydra-acp daemon stop|restart"],[xl," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"],[TE," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"],[pt," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"],[pt," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."],[pt," --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."],[pt," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."],[pt," --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."],[pt," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"],[pt," 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)."],[pt," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"],[pt," 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."],[pt," hydra-acp session kill <id> Demote a warm session to cold (keeps the on-disk record)"],[pt," hydra-acp session remove <id> Remove a session entirely (live or cold)"],[pt," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"],[pt," 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."],[pt," hydra-acp session export <id> [--out <file>|.]"],[pt," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"],[pt," hydra-acp session transcript <id>|<file> [--out <file>|.]"],[pt," 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"],[pt," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"],[pt," 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"],[pt," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"],[pt," 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)."],[Qa," hydra-acp extension list List configured extensions and live state"],[Qa," hydra-acp extension add <name> [opts] Add an extension to config"],[Qa," hydra-acp extension remove <name> Remove an extension from config"],[Qa," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"],[Qa," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"],[Ga," hydra-acp transformer list List configured transformers and live state"],[Ga," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"],[Ga," hydra-acp transformer remove <name> Remove a transformer from config"],[Ga," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"],[Ga," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"],[Dn," hydra-acp agent [list] List agents in the cached registry"],[Dn," hydra-acp agent refresh Force a registry re-fetch"],[Dn," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"],[Dn," 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>])."],[Dn," 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."],[Dn," 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)."],[Dn," hydra-acp agent remove <id> Remove a local agent (config only; leaves the on-disk install cache)"],[Dn," hydra-acp agent uninstall <id> Delete <id>'s cached install (~/.hydra-acp/agents/<platform>/<id>/) so the next session re-downloads"],[EE," 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."],[Dn," 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`"],[Dn," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"],[Dn," hydra-acp agent auth <id> Run the auth flow for <id>"],[Xa," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"],[Xa," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"],[Xa," 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."],[Xa," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"],[Xa," hydra-acp config path Print the config file path"],[Fp," hydra-acp auth password [--force] Set the daemon's master password"],[Fp," hydra-acp auth [list] List active session tokens"],[Fp," hydra-acp auth revoke <id> Revoke a session token"],[$p," hydra-acp tui [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"],[$p," Interactive terminal UI. Smart default (no flags): shows a picker when sessions exist, else new."],{globalOnly:" hydra-acp --version Print version"},{globalOnly:" hydra-acp --help Show this help"},{globalOnly:""},{globalOnly:"External subcommands:"},{globalOnly:" Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"},{globalOnly:" `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"},{globalOnly:" @hydra-acp/planner expose themselves through this mechanism."},{globalOnly:""},{globalOnly:"Config knob flags accept env-var equivalents (flag wins):"},{globalOnly:" --agent HYDRA_ACP_AGENT"},{globalOnly:" --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"},{globalOnly:" --session HYDRA_ACP_SESSION (session id or hydra:// URL)"},{globalOnly:" --name HYDRA_ACP_NAME"},""],t=[];for(let s of e){if(typeof s=="string"){t.push(s);continue}if("globalOnly"in s){n===void 0&&t.push(s.globalOnly);continue}let[r,i]=s;(n===void 0||r.includes(n))&&t.push(i)}process.stdout.write(t.join(`
518
518
  `)+`
519
- `)}async function Ov(){if(!mr)try{let n=await La();n&&process.stderr.write(`\u2728 ${Ba(n)}
520
- `)}catch{}}vE().then(Ov).catch(async n=>{oe({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`hydra-acp: ${n.message}
521
- `),await Ov(),process.exit(1)});
519
+ `)}async function Dv(){if(!wr)try{let n=await Ba();n&&process.stderr.write(`\u2728 ${Na(n)}
520
+ `)}catch{}}AE().then(Dv).catch(async n=>{oe({src:"cli-fatal",stack:n instanceof Error?n.stack??n.message:String(n)}),process.stderr.write(`hydra-acp: ${n.message}
521
+ `),await Dv(),process.exit(1)});