@hydra-acp/cli 0.1.91 → 0.1.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- var pb=Object.defineProperty;var K=(t,e)=>()=>(t&&(e=t(t=0)),e);var cf=(t,e)=>{for(var n in e)pb(t,n,{get:e[n],enumerable:!0})};import*as he from"path";import*as cc from"os";function Ue(t){let e=cc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function bb(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function ke(){let t=process.env[wb];if(t&&t.length>0)return he.resolve(t);let e=bb();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return he.join(cc.homedir(),".hydra-acp")}var wb,_,pe=K(()=>{"use strict";wb="HYDRA_ACP_HOME";_={home:ke,config:()=>he.join(ke(),"config.json"),authToken:()=>he.join(ke(),"auth-token"),remotes:()=>he.join(ke(),"remotes.json"),pidFile:()=>he.join(ke(),"daemon.pid"),logFile:()=>he.join(ke(),"daemon.log"),currentLogFile:()=>he.join(ke(),"current.log"),registryCache:()=>he.join(ke(),"registry.json"),agentsDir:()=>he.join(ke(),"agents"),agentLogFile:t=>he.join(ke(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>he.join(ke(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>he.join(ke(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>he.join(ke(),"sessions"),sessionDir:t=>he.join(ke(),"sessions",t),sessionFile:t=>he.join(ke(),"sessions",t,"meta.json"),historyFile:t=>he.join(ke(),"sessions",t,"history.jsonl"),toolsDir:t=>he.join(ke(),"sessions",t,"tools"),toolBlobFile:(t,e)=>he.join(ke(),"sessions",t,"tools",e),queueFile:t=>he.join(ke(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>he.join(ke(),"sessions",".tombstones"),tombstoneAgentDir:t=>he.join(ke(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>he.join(ke(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>he.join(ke(),"extensions"),extensionLogFile:t=>he.join(ke(),"extensions",`${t}.log`),extensionPidFile:t=>he.join(ke(),"extensions",`${t}.pid`),transformersDir:()=>he.join(ke(),"transformers"),transformerLogFile:t=>he.join(ke(),"transformers",`${t}.log`),transformerPidFile:t=>he.join(ke(),"transformers",`${t}.pid`),transformerState:(t,e)=>he.join(ke(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>he.join(ke(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>he.join(ke(),"prompt-history"),tuiLogFile:()=>he.join(ke(),"tui.log"),shimWireLogFile:()=>he.join(ke(),"shim-wire.log")}});import*as Nr from"fs/promises";function Dr(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Hr(){try{let e=(await Nr.readFile(_.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function Gs(){let t=await Hr();if(!t)throw new Error(`No service token found at ${_.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Ur(t){await Nr.mkdir(_.home(),{recursive:!0}),await Nr.writeFile(_.authToken(),t+`
3
- `,{encoding:"utf8",mode:384})}async function Xi(){let t=await Hr();if(t)return t;let e=Dr();return await Ur(e),process.stderr.write(`hydra-acp: initialized ${_.authToken()} with a fresh service token.
4
- `),e}var qn=K(()=>{"use strict";pe()});import*as ft from"fs/promises";import*as ff from"fs";import*as on from"path";import{randomBytes as vb}from"crypto";async function Ft(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
- `;await Sb(t,r,n)}async function Sb(t,e,n={}){let s=await kb(t),r=Ib(s);await ft.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${xb()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await ft.writeFile(i,e,o),await ft.rename(i,s)}catch(o){throw await ft.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{ff.chmodSync(s,n.mode)}catch{}}async function kb(t){let e;try{e=await ft.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await ft.readlink(t),s=on.isAbsolute(n)?n:on.resolve(on.dirname(t),n);try{let r=await ft.realpath(on.dirname(s));return on.join(r,on.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function zt(t){let e;try{e=await ft.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Ib(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function xb(){return vb(4).toString("hex")}var Qs=K(()=>{"use strict"});import*as ls from"fs/promises";import{homedir as lc}from"os";import{z as D}from"zod";function hf(t){return t.tui.inAppSelection??t.tui.mouse}function gf(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function yf(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function oa(){return await $b(),await zt(_.config())??{}}async function $b(){let t;try{t=await ls.lstat(_.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await ls.stat(_.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await ls.readlink(_.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${_.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function aa(){let t=await oa(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await ls.access(_.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${_.authToken()} and ${_.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Ur(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Ft(_.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${_.config()} to ${_.authToken()}.
6
- `)}async function ye(){return await aa(),uc.parse(await oa())}async function Wn(t){await aa();let e=await oa();t(e),uc.parse(e),await Ft(_.config(),e,{mode:384})}async function Zi(t,e){await Wn(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function da(t){await Wn(e=>{e.defaultAgent=t})}async function wf(t,e){await Wn(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function bf(t,e){await Wn(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function fc(t,e){await Wn(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function vf(t){await Wn(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Sf(){let t=await oa();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function je(t){return t==="~"||t==="$HOME"?lc():t.startsWith("~/")?lc()+t.slice(1):t.startsWith("$HOME/")?lc()+t.slice(5):t}var mf,Cb,an,Ab,Rb,Tb,Eb,Pb,pf,Mb,_b,uc,Ne=K(()=>{"use strict";pe();qn();Qs();mf="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Cb=D.object({cert:D.string(),key:D.string()}),an=55514,Ab=D.object({host:D.string().default("127.0.0.1"),port:D.number().int().positive().default(an),logLevel:D.enum(["debug","info","warn","error"]).default("info"),tls:Cb.optional(),sessionIdleTimeoutSeconds:D.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:D.number().int().positive().default(1e4),agentStderrTailBytes:D.number().int().positive().default(4096),publicHost:D.string().optional(),agentSyncIntervalMinutes:D.number().nonnegative().default(60),sessionGcIntervalMinutes:D.number().nonnegative().default(60),sessionGcMaxAgeDays:D.number().positive().default(2)}),Rb=D.object({url:D.string().url().default(mf),ttlHours:D.number().positive().default(24),pinned:D.boolean().default(!1)}),Tb=D.object({name:D.string().optional(),description:D.string().optional(),command:D.string().optional(),args:D.array(D.string()).optional(),env:D.record(D.string()).optional()}),Eb=D.object({packageSpec:D.string().optional()}),Pb=D.object({repaintThrottleMs:D.number().int().nonnegative().default(1e3),maxScrollbackLines:D.number().int().positive().default(1e4),mouse:D.boolean().default(!0),inAppSelection:D.boolean().optional(),selectionClipboard:D.enum(["primary","clipboard","both"]).default("both"),openFileCommand:D.union([D.string(),D.array(D.string())]).optional(),logMaxBytes:D.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:D.number().int().positive().default(32),progressIndicator:D.boolean().default(!0),defaultEnterAction:D.enum(["enqueue","amend"]).default("amend"),showThoughts:D.boolean().default(!0),ambiguousWidth:D.enum(["auto","narrow","wide"]).default("auto"),toolContent:D.enum(["inline","references"]).default("references"),diffContextLines:D.number().int().min(0).default(3),promptHistoryMaxEntries:D.number().int().positive().default(2e3),maxToolItems:D.number().int().nonnegative().default(5),maxPlanItems:D.number().int().nonnegative().default(5),showFileUpdates:D.enum(["none","edit","diff"]).default("edit"),sessionColumns:D.array(D.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),pf=D.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Mb=D.object({command:D.array(D.string()).default([]),args:D.array(D.string()).default([]),env:D.record(D.string()).default({}),enabled:D.boolean().default(!0)}),_b=D.object({command:D.array(D.string()).default([]),args:D.array(D.string()).default([]),env:D.record(D.string()).default({}),enabled:D.boolean().default(!0)}),uc=D.object({daemon:Ab.default({}),registry:Rb.default({url:mf,ttlHours:24,pinned:!1}),agents:D.record(D.string(),Tb).default({}),agentOverrides:D.record(D.string(),Eb).default({}),defaultAgent:D.string().default("opencode"),defaultModels:D.record(D.string(),D.string()).default({}),synopsisAgent:D.string().optional(),synopsisModel:D.string().optional(),compaction:D.object({agent:D.string().optional(),model:D.string().optional(),tailK:D.number().int().nonnegative().default(20),maxIterations:D.number().int().positive().default(3),contextFraction:D.number().min(0).max(1).default(.5),hardCeilingFraction:D.number().min(0).max(1).default(.85),absoluteFallback:D.number().int().positive().default(12e4),idleBeforePromptMs:D.number().int().nonnegative().default(3e5),modelContextWindows:D.record(D.string(),D.number().int().positive()).default({})}).default({}),defaultCwd:D.string().default("~"),compressToolContent:D.boolean().default(!0),sessionListColdLimit:D.number().int().nonnegative().default(20),extensions:D.record(pf,Mb).default({}),transformers:D.record(pf,_b).default({}),defaultTransformers:D.array(D.string()).default([]),npmRegistry:D.string().url().optional(),tui:Pb.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})})});function Xs(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function pc(t){return{httpScheme:"https",wsScheme:"wss"}}function mc(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${ca(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${ca(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Ob(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${ca(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${ca(t)}`);let i=Xs(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=an;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function kf(t){let e=t.port!==void 0&&t.port!==an?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Ob(t){try{return new URL(t)}catch{return null}}function ca(t){return t.length>80?`${t.slice(0,77)}...`:t}var eo=K(()=>{"use strict";Ne()});function Zs(t,e){return`${t}:${e}`}function If(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function Fb(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function Lb(){let t=await zt(_.remotes());return t===void 0?{version:1,entries:{}}:Bb(t)}function Bb(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function hc(t){await Ft(_.remotes(),t,{mode:384})}var la,gc=K(()=>{"use strict";pe();Qs();la=class t{data;constructor(e){this.data=e}static async load(){let e=await Lb(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(If(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await hc(i),new t(i)}get(e,n){let s=this.data.entries[Zs(e,n)];if(s&&!If(s,Date.now()))return s}async set(e,n,s){this.data.entries[Zs(e,n)]=s,await hc(this.data)}async delete(e,n){let s=Zs(e,n);return s in this.data.entries?(delete this.data.entries[s],await hc(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=Fb(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function jr(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){if(l===10||l===13){process.stdout.write(`
7
- `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):Nb()}function Nb(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
- `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var yc=K(()=>{"use strict"});import*as xf from"path";function vn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=xf.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var to=K(()=>{"use strict"});import*as ua from"fs/promises";async function zn(){try{let t=await ua.readFile(_.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function Cf(t){await ua.writeFile(_.pidFile(),JSON.stringify(t)+`
9
- `,{encoding:"utf8",mode:384})}function dn(t){try{return process.kill(t,0),!0}catch{return!1}}var qr=K(()=>{"use strict";pe()});var Mf={};cf(Mf,{_resetForTests:()=>Kb,clearPin:()=>zb,fetchPeerFingerprint:()=>Sc,formatFingerprint:()=>fa,getPin:()=>bc,installGlobalTlsTrust:()=>Ic,loadPinsFromStore:()=>vc,setPin:()=>no,sha256Hex:()=>kc,wsTlsOptions:()=>so});import{createHash as Db}from"crypto";import*as Af from"tls";import{Agent as Hb,Dispatcher as Ub,buildConnector as jb,getGlobalDispatcher as qb,setGlobalDispatcher as Wb}from"undici";function no(t,e,n){er.set(Zs(t,e),Rf(n))}function zb(t,e){er.delete(Zs(t,e))}function bc(t,e){return er.get(Zs(t,e))}function vc(t){er.clear();for(let e of t.list())e.entry.pinnedFingerprint&&no(e.host,e.port,e.entry.pinnedFingerprint)}async function Sc(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Af.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,f)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):f&&r(f)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,kc(l.raw))}),o.once("error",l=>c(l))})}function kc(t){return Db("sha256").update(t).digest("hex")}function fa(t){let e=Rf(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Rf(t){return t.replace(/:/g,"").toLowerCase()}function Ic(){if(wc)return;wc=!0;let t=qb(),e=new Hb({connect:jb({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>Ef(s,r)})}),n=new Ub;n.dispatch=(s,r)=>{let i=Jb(s.origin);return(i&&Tf(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),Wb(n)}function Jb(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Tf(t){for(let e of er.keys())if(Pf(e)?.host===t)return!0;return!1}function Ef(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=kc(e.raw);for(let[s,r]of er.entries()){let i=Pf(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${fa(n)})`)}function Pf(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}function so(t){return Tf(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>Ef(e,n)}:{autoSelectFamily:!0}}function Kb(){er.clear(),wc=!1}var er,wc,ro=K(()=>{"use strict";gc();er=new Map,wc=!1});import*as Ff from"os";async function Et(t){let e=await Xi(),n=await zn();if(n&&dn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:Xs(r)}}function _f(t,e){let{httpScheme:n,wsScheme:s}=pc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Bf(t),isLocal:t.isLoopback}}async function Lf(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??jr,r=e.confirmImpl??Qb,i=e.tlsHandshakeImpl??Yb,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await Hr();if(b)return Gb(t,b)}let c=e.store??await la.load();vc(c),Ic();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&no(t.host,t.port,d.pinnedFingerprint),_f(t,d.token);if(!a)throw new xc(t.host,t.port);let l=Bf(t),{httpScheme:f}=pc(t.host),u;if(f==="https"&&bc(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
2
+ var _b=Object.defineProperty;var K=(t,e)=>()=>(t&&(e=t(t=0)),e);var kf=(t,e)=>{for(var n in e)_b(t,n,{get:e[n],enumerable:!0})};import*as ge from"path";import*as vc from"os";function ze(t){let e=vc.homedir();return e?t===e?"~":t.startsWith(e+"/")?"~"+t.slice(e.length):t:t}function Nb(){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 Ie(){let t=process.env[Bb];if(t&&t.length>0)return ge.resolve(t);let e=Nb();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return ge.join(vc.homedir(),".hydra-acp")}var Bb,$,he=K(()=>{"use strict";Bb="HYDRA_ACP_HOME";$={home:Ie,config:()=>ge.join(Ie(),"config.json"),authToken:()=>ge.join(Ie(),"auth-token"),remotes:()=>ge.join(Ie(),"remotes.json"),pidFile:()=>ge.join(Ie(),"daemon.pid"),logFile:()=>ge.join(Ie(),"daemon.log"),currentLogFile:()=>ge.join(Ie(),"current.log"),registryCache:()=>ge.join(Ie(),"registry.json"),agentsDir:()=>ge.join(Ie(),"agents"),agentLogFile:t=>ge.join(Ie(),"agents","logs",`${t}.log`),agentInstallDir:(t,e,n)=>ge.join(Ie(),"agents",e,t,n),agentNpmInstallDir:(t,e,n)=>ge.join(Ie(),"agents",e,t,n,`node${process.versions.modules}`),sessionsDir:()=>ge.join(Ie(),"sessions"),sessionDir:t=>ge.join(Ie(),"sessions",t),sessionFile:t=>ge.join(Ie(),"sessions",t,"meta.json"),historyFile:t=>ge.join(Ie(),"sessions",t,"history.jsonl"),toolsDir:t=>ge.join(Ie(),"sessions",t,"tools"),toolBlobFile:(t,e)=>ge.join(Ie(),"sessions",t,"tools",e),queueFile:t=>ge.join(Ie(),"sessions",t,"queue.ndjson"),tombstonesDir:()=>ge.join(Ie(),"sessions",".tombstones"),tombstoneAgentDir:t=>ge.join(Ie(),"sessions",".tombstones",encodeURIComponent(t)),tombstoneFile:(t,e)=>ge.join(Ie(),"sessions",".tombstones",encodeURIComponent(t),encodeURIComponent(e)),extensionsDir:()=>ge.join(Ie(),"extensions"),extensionLogFile:t=>ge.join(Ie(),"extensions",`${t}.log`),extensionPidFile:t=>ge.join(Ie(),"extensions",`${t}.pid`),transformersDir:()=>ge.join(Ie(),"transformers"),transformerLogFile:t=>ge.join(Ie(),"transformers",`${t}.log`),transformerPidFile:t=>ge.join(Ie(),"transformers",`${t}.pid`),transformerState:(t,e)=>ge.join(Ie(),"sessions",t,"transformer-state",e),tuiHistoryFile:t=>ge.join(Ie(),"sessions",t,"prompt-history"),globalTuiHistoryFile:()=>ge.join(Ie(),"prompt-history"),tuiLogFile:()=>ge.join(Ie(),"tui.log"),shimWireLogFile:()=>ge.join(Ie(),"shim-wire.log")}});import*as Yr from"fs/promises";function Qr(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e="";for(let n of t)e+=n.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Gr(){try{let e=(await Yr.readFile($.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}async function or(){let t=await Gr();if(!t)throw new Error(`No service token found at ${$.authToken()}. Run \`hydra-acp init\` to create one.`);return t}async function Xr(t){await Yr.mkdir($.home(),{recursive:!0}),await Yr.writeFile($.authToken(),t+`
3
+ `,{encoding:"utf8",mode:384})}async function co(){let t=await Gr();if(t)return t;let e=Qr();return await Xr(e),process.stderr.write(`hydra-acp: initialized ${$.authToken()} with a fresh service token.
4
+ `),e}var Gn=K(()=>{"use strict";he()});import*as pt from"fs/promises";import*as Cf from"fs";import*as fn from"path";import{randomBytes as Db}from"crypto";async function Ut(t,e,n={}){let r=(n.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
5
+ `;await Hb(t,r,n)}async function Hb(t,e,n={}){let s=await Ub(t),r=jb(s);await pt.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${qb()}`;try{let o={encoding:"utf8"};n.mode!==void 0&&(o.mode=n.mode),await pt.writeFile(i,e,o),await pt.rename(i,s)}catch(o){throw await pt.unlink(i).catch(()=>{}),o}if(n.mode!==void 0)try{Cf.chmodSync(s,n.mode)}catch{}}async function Ub(t){let e;try{e=await pt.lstat(t)}catch(r){if(r.code==="ENOENT")return t;throw r}if(!e.isSymbolicLink())return t;let n=await pt.readlink(t),s=fn.isAbsolute(n)?n:fn.resolve(fn.dirname(t),n);try{let r=await pt.realpath(fn.dirname(s));return fn.join(r,fn.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function Xt(t){let e;try{e=await pt.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function jb(t){let e=t.lastIndexOf("/");return e<=0?".":t.slice(0,e)}function qb(){return Db(4).toString("hex")}var ar=K(()=>{"use strict"});import*as ks from"fs/promises";import{homedir as Sc}from"os";import{z as H}from"zod";function Tf(t){return t.tui.inAppSelection??t.tui.mouse}function Ef(t){return Object.entries(t.extensions).map(([e,n])=>({name:e,...n}))}function Pf(t){return Object.entries(t.transformers).map(([e,n])=>({name:e,...n}))}async function ba(){return await Xb(),await Xt($.config())??{}}async function Xb(){let t;try{t=await ks.lstat($.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(t.isSymbolicLink())try{await ks.stat($.config())}catch(e){if(e.code!=="ENOENT")throw e;let n=await ks.readlink($.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${$.config()} is a broken symlink (-> ${n}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function va(){let t=await ba(),e=t.daemon,n=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!n)return;let s=!1;try{await ks.access($.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${$.authToken()} and ${$.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Xr(n),delete e.authToken,Object.keys(e).length===0&&delete t.daemon,await Ut($.config(),t,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${$.config()} to ${$.authToken()}.
6
+ `)}async function we(){return await va(),kc.parse(await ba())}async function Xn(t){await va();let e=await ba();t(e),kc.parse(e),await Ut($.config(),e,{mode:384})}async function lo(t,e){await Xn(n=>{let s=n.tui&&typeof n.tui=="object"&&!Array.isArray(n.tui)?n.tui:{};s[t]=e,n.tui=s})}async function Sa(t){await Xn(e=>{e.defaultAgent=t})}async function Mf(t,e){await Xn(n=>{let s=n.defaultModels&&typeof n.defaultModels=="object"?n.defaultModels:{};s[t]=e,n.defaultModels=s})}async function _f(t,e){await Xn(n=>{let s=n.agentOverrides&&typeof n.agentOverrides=="object"?n.agentOverrides:{};e===void 0?delete s[t]:s[t]={packageSpec:e},n.agentOverrides=s})}async function Ic(t,e){await Xn(n=>{let s=n.agents&&typeof n.agents=="object"?n.agents:{};e===void 0?delete s[t]:s[t]=e,n.agents=s})}async function $f(t){await Xn(e=>{let n=e.registry&&typeof e.registry=="object"?e.registry:{};n.pinned=t,e.registry=n})}async function Ff(){let t=await ba();return typeof t.defaultAgent=="string"&&t.defaultAgent.length>0}function Je(t){return t==="~"||t==="$HOME"?Sc():t.startsWith("~/")?Sc()+t.slice(1):t.startsWith("$HOME/")?Sc()+t.slice(5):t}var Rf,Wb,pn,zb,Jb,Kb,Vb,Yb,Af,Qb,Gb,kc,je=K(()=>{"use strict";he();Gn();ar();Rf="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Wb=H.object({cert:H.string(),key:H.string()}),pn=55514,zb=H.object({host:H.string().default("127.0.0.1"),port:H.number().int().positive().default(pn),logLevel:H.enum(["debug","info","warn","error"]).default("info"),tls:Wb.optional(),sessionIdleTimeoutSeconds:H.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:H.number().int().positive().default(1e4),agentStderrTailBytes:H.number().int().positive().default(4096),publicHost:H.string().optional(),agentSyncIntervalMinutes:H.number().nonnegative().default(60),sessionGcIntervalMinutes:H.number().nonnegative().default(60),sessionGcMaxAgeDays:H.number().positive().default(2)}),Jb=H.object({url:H.string().url().default(Rf),ttlHours:H.number().positive().default(24),pinned:H.boolean().default(!1)}),Kb=H.object({name:H.string().optional(),description:H.string().optional(),command:H.string().optional(),args:H.array(H.string()).optional(),env:H.record(H.string()).optional()}),Vb=H.object({packageSpec:H.string().optional()}),Yb=H.object({repaintThrottleMs:H.number().int().nonnegative().default(1e3),maxScrollbackLines:H.number().int().positive().default(1e4),mouse:H.boolean().default(!0),inAppSelection:H.boolean().optional(),selectionClipboard:H.enum(["primary","clipboard","both"]).default("both"),openFileCommand:H.union([H.string(),H.array(H.string())]).optional(),logMaxBytes:H.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:H.number().int().positive().default(32),progressIndicator:H.boolean().default(!0),defaultEnterAction:H.enum(["enqueue","amend"]).default("amend"),showThoughts:H.boolean().default(!0),ambiguousWidth:H.enum(["auto","narrow","wide"]).default("auto"),toolContent:H.enum(["inline","references"]).default("references"),diffContextLines:H.number().int().min(0).default(3),promptHistoryMaxEntries:H.number().int().positive().default(2e3),maxToolItems:H.number().int().nonnegative().default(5),maxPlanItems:H.number().int().nonnegative().default(5),showFileUpdates:H.enum(["none","edit","diff"]).default("edit"),sessionColumns:H.array(H.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Af=H.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Qb=H.object({command:H.array(H.string()).default([]),args:H.array(H.string()).default([]),env:H.record(H.string()).default({}),enabled:H.boolean().default(!0)}),Gb=H.object({command:H.array(H.string()).default([]),args:H.array(H.string()).default([]),env:H.record(H.string()).default({}),enabled:H.boolean().default(!0)}),kc=H.object({daemon:zb.default({}),registry:Jb.default({url:Rf,ttlHours:24,pinned:!1}),agents:H.record(H.string(),Kb).default({}),agentOverrides:H.record(H.string(),Vb).default({}),defaultAgent:H.string().default("opencode"),defaultModels:H.record(H.string(),H.string()).default({}),synopsisAgent:H.string().optional(),synopsisModel:H.string().optional(),compaction:H.object({agent:H.string().optional(),model:H.string().optional(),tailK:H.number().int().nonnegative().default(20),maxIterations:H.number().int().positive().default(3),contextFraction:H.number().min(0).max(1).default(.5),hardCeilingFraction:H.number().min(0).max(1).default(.85),absoluteFallback:H.number().int().positive().default(12e4),idleBeforePromptMs:H.number().int().nonnegative().default(3e5),modelContextWindows:H.record(H.string(),H.number().int().positive()).default({})}).default({}),defaultCwd:H.string().default("~"),compressToolContent:H.boolean().default(!0),sessionListColdLimit:H.number().int().nonnegative().default(20),extensions:H.record(Af,Qb).default({}),transformers:H.record(Af,Gb).default({}),defaultTransformers:H.array(H.string()).default([]),npmRegistry:H.string().url().optional(),tui:Yb.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 dr(t){return t==="127.0.0.1"||t==="::1"||t==="localhost"||t==="[::1]"}function xc(t){return{httpScheme:"https",wsScheme:"wss"}}function Cc(t){if(typeof t!="string"||t.length===0)throw new Error("expected a hydra:// URL");if(!t.startsWith("hydra://"))throw new Error(`expected hydra:// URL, got ${ka(t)}`);let e=t.slice(8);if(e.length===0||e.startsWith("/"))throw new Error(`hydra:// URL is missing a host: ${ka(t)}`);let n=e.match(/^[^/]*?:(\d+)(?:\/|$)/);if(n){let d=Number(n[1]);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${n[1]}`)}let s=Zb(`http://${e}`);if(!s)throw new Error(`invalid hydra:// URL: ${ka(t)}`);let r=s.hostname;if(!r)throw new Error(`hydra:// URL is missing a host: ${ka(t)}`);let i=dr(r),o;if(s.port){let d=Number(s.port);if(!Number.isInteger(d)||d<=0||d>65535)throw new Error(`hydra:// URL has invalid port: ${s.port}`);o=d}else o=pn;let a=s.pathname.replace(/^\/+/,"");return{host:r,port:o,sessionId:a===""?void 0:a,isLoopback:i}}function Of(t){let e=t.port!==void 0&&t.port!==pn?`:${t.port}`:"",n=t.sessionId?`/${t.sessionId}`:"/";return`hydra://${t.host}${e}${n}`}function Zb(t){try{return new URL(t)}catch{return null}}function ka(t){return t.length>80?`${t.slice(0,77)}...`:t}var uo=K(()=>{"use strict";je()});function cr(t,e){return`${t}:${e}`}function Lf(t,e){let n=Date.parse(t.expiresAt);return Number.isFinite(n)?n<=e:!0}function ev(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}async function tv(){let t=await Xt($.remotes());return t===void 0?{version:1,entries:{}}:nv(t)}function nv(t){if(!t||typeof t!="object")return{version:1,entries:{}};let e=t,n=e.entries&&typeof e.entries=="object"?e.entries:{},s={};for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let o=i;if(typeof o.token!="string"||typeof o.expiresAt!="string")continue;let a={token:o.token,expiresAt:o.expiresAt};typeof o.label=="string"&&(a.label=o.label),typeof o.pinnedFingerprint=="string"&&(a.pinnedFingerprint=o.pinnedFingerprint),typeof o.pinnedAt=="string"&&(a.pinnedAt=o.pinnedAt),s[r]=a}return{version:1,entries:s}}async function Ac(t){await Ut($.remotes(),t,{mode:384})}var Ia,Rc=K(()=>{"use strict";he();ar();Ia=class t{data;constructor(e){this.data=e}static async load(){let e=await tv(),n=Date.now(),s={},r=!1;for(let[o,a]of Object.entries(e.entries)){if(Lf(a,n)){r=!0;continue}s[o]=a}let i={version:1,entries:s};return r&&await Ac(i),new t(i)}get(e,n){let s=this.data.entries[cr(e,n)];if(s&&!Lf(s,Date.now()))return s}async set(e,n,s){this.data.entries[cr(e,n)]=s,await Ac(this.data)}async delete(e,n){let s=cr(e,n);return s in this.data.entries?(delete this.data.entries[s],await Ac(this.data),!0):!1}list(){let e=[];for(let[n,s]of Object.entries(this.data.entries)){let r=ev(n);r&&e.push({host:r.host,port:r.port,entry:s})}return e}}});async function Zr(t){return process.stdout.write(t),process.stdin.isTTY?new Promise((e,n)=>{let s=process.stdin,r=s.isRaw===!0,i="",o=()=>{s.removeListener("data",a),s.removeListener("error",c),r||s.setRawMode(!1),s.pause()},a=d=>{for(let l of d){if(l===10||l===13){process.stdout.write(`
7
+ `),o(),e(i);return}if(l===3){o(),n(new Error("password entry cancelled"));return}if(l===127||l===8){i=i.slice(0,-1);continue}i+=String.fromCharCode(l)}},c=d=>{o(),n(d)};s.setRawMode(!0),s.resume(),s.on("data",a),s.on("error",c)}):sv()}function sv(){return new Promise((t,e)=>{let n="";process.stdin.setEncoding("utf8");let s=i=>{n+=i;let o=n.indexOf(`
8
+ `);o!==-1&&(process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),t(n.slice(0,o).replace(/\r$/,"")))},r=i=>{process.stdin.removeListener("data",s),process.stdin.removeListener("error",r),e(i)};process.stdin.on("data",s),process.stdin.on("error",r)})}var Tc=K(()=>{"use strict"});import*as Bf from"path";function Cn(){let t=process.argv[1];if(!t)return"hydra-acp";let e=Bf.basename(t);return e==="cli.js"||e==="cli"?"hydra-acp":e}var fo=K(()=>{"use strict"});import*as xa from"fs/promises";async function Zn(){try{let t=await xa.readFile($.pidFile(),"utf8"),e=JSON.parse(t);return typeof e.pid!="number"||typeof e.host!="string"||typeof e.port!="number"?void 0:{pid:e.pid,host:e.host,port:e.port,loopbackPort:typeof e.loopbackPort=="number"?e.loopbackPort:e.port,startedAt:typeof e.startedAt=="string"?e.startedAt:""}}catch(t){if(t.code==="ENOENT")return;throw t}}async function Nf(t){await xa.writeFile($.pidFile(),JSON.stringify(t)+`
9
+ `,{encoding:"utf8",mode:384})}function mn(t){try{return process.kill(t,0),!0}catch{return!1}}var ei=K(()=>{"use strict";he()});var Wf={};kf(Wf,{_resetForTests:()=>fv,clearPin:()=>lv,fetchPeerFingerprint:()=>_c,formatFingerprint:()=>Ca,getPin:()=>Pc,installGlobalTlsTrust:()=>Fc,loadPinsFromStore:()=>Mc,setPin:()=>po,sha256Hex:()=>$c,wsTlsOptions:()=>mo});import{createHash as rv}from"crypto";import*as Df from"tls";import{Agent as iv,Dispatcher as ov,buildConnector as av,getGlobalDispatcher as dv,setGlobalDispatcher as cv}from"undici";function po(t,e,n){lr.set(cr(t,e),Hf(n))}function lv(t,e){lr.delete(cr(t,e))}function Pc(t,e){return lr.get(cr(t,e))}function Mc(t){lr.clear();for(let e of t.list())e.entry.pinnedFingerprint&&po(e.host,e.port,e.entry.pinnedFingerprint)}async function _c(t,e,n={}){let s=n.timeoutMs??1e4;return new Promise((r,i)=>{let o=Df.connect({host:t,port:e,servername:t,rejectUnauthorized:!1,autoSelectFamily:!0}),a=!1,c=(l,u)=>{if(!a){a=!0,clearTimeout(d);try{o.destroy()}catch{}l?i(l):u&&r(u)}},d=setTimeout(()=>{c(new Error(`TLS connect to ${t}:${e} timed out`))},s);o.once("secureConnect",()=>{let l=o.getPeerCertificate(!1);if(!l||!l.raw){c(new Error(`${t}:${e} did not present a TLS certificate`));return}c(null,$c(l.raw))}),o.once("error",l=>c(l))})}function $c(t){return rv("sha256").update(t).digest("hex")}function Ca(t){let e=Hf(t),n=e.match(/.{2}/g);return n?n.join(":"):e}function Hf(t){return t.replace(/:/g,"").toLowerCase()}function Fc(){if(Ec)return;Ec=!0;let t=dv(),e=new iv({connect:av({rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(s,r)=>jf(s,r)})}),n=new ov;n.dispatch=(s,r)=>{let i=uv(s.origin);return(i&&Uf(i)?e:t).dispatch(s,r)},n.close=(()=>Promise.all([e.close(),t.close()]).then(()=>{})),n.destroy=(s=>Promise.all([e.destroy(s??null),t.destroy(s??null)]).then(()=>{})),cv(n)}function uv(t){if(!t)return null;try{return new URL(String(t)).hostname}catch{return null}}function Uf(t){for(let e of lr.keys())if(qf(e)?.host===t)return!0;return!1}function jf(t,e){if(!e||!e.raw)return new Error(`TLS peer ${t} did not present a certificate`);let n=$c(e.raw);for(let[s,r]of lr.entries()){let i=qf(s);if(i&&i.host===t&&r===n)return}return new Error(`TLS pin mismatch for ${t} (cert sha256 ${Ca(n)})`)}function qf(t){let e=t.lastIndexOf(":");if(e<0)return null;let n=t.slice(0,e),s=Number(t.slice(e+1));return Number.isInteger(s)?{host:n,port:s}:null}function mo(t){return Uf(t)?{rejectUnauthorized:!1,autoSelectFamily:!0,checkServerIdentity:(e,n)=>jf(e,n)}:{autoSelectFamily:!0}}function fv(){lr.clear(),Ec=!1}var lr,Ec,ho=K(()=>{"use strict";Rc();lr=new Map,Ec=!1});import*as Vf from"os";async function Mt(t){let e=await co(),n=await Zn();if(n&&mn(n.pid))return{baseUrl:`http://127.0.0.1:${n.loopbackPort}`,wsUrl:`ws://127.0.0.1:${n.loopbackPort}/acp`,token:e,display:`${n.host}:${n.port}`,isLocal:!0};let s=t.daemon.host,r=s==="0.0.0.0"||s==="::"||s==="0.0.0.0/0"?"127.0.0.1":s,i=t.daemon.port;return{baseUrl:`http://${r}:${i}`,wsUrl:`ws://${r}:${i}/acp`,token:e,display:`${s}:${i}`,isLocal:dr(r)}}function zf(t,e){let{httpScheme:n,wsScheme:s}=xc(t.host);return{baseUrl:`${n}://${t.host}:${t.port}`,wsUrl:`${s}://${t.host}:${t.port}/acp`,token:e,display:Qf(t),isLocal:t.isLoopback}}async function Yf(t,e={}){let n=e.fetchImpl??fetch,s=e.promptImpl??Zr,r=e.confirmImpl??gv,i=e.tlsHandshakeImpl??pv,o=e.preferServiceToken??!0,a=e.allowPrompt??!0;if(t.isLoopback&&o){let b=await Gr();if(b)return hv(t,b)}let c=e.store??await Ia.load();Mc(c),Fc();let d=c.get(t.host,t.port);if(d)return d.pinnedFingerprint&&po(t.host,t.port,d.pinnedFingerprint),zf(t,d.token);if(!a)throw new Oc(t.host,t.port);let l=Qf(t),{httpScheme:u}=xc(t.host),f;if(u==="https"&&Pc(t.host,t.port)===void 0){let b=await i(t.host,t.port);if(b.kind==="untrusted"){let v=b.subject||b.issuer?`
10
10
  subject: ${b.subject??"(unknown)"}
11
11
  issuer: ${b.issuer??"(unknown)"}`:"";if(process.stderr.write(`The certificate presented by ${l} is not signed by a trusted CA.
12
- sha256: ${fa(b.fingerprint)}${v}
13
- `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);no(t.host,t.port,b.fingerprint),u=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let m=`${f}://${t.host}:${t.port}`,h=await n(`${m}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Of()})});if(h.status===401)throw new Error(`Wrong password for ${l}.`);if(h.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(h.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!h.ok)throw new Error(`Login to ${l} failed: HTTP ${h.status}`);let w=await h.json();if(!w.session_token||!w.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:w.session_token,expiresAt:w.expires_at,label:Of(),...u?{pinnedFingerprint:u,pinnedAt:new Date().toISOString()}:{}}),_f(t,w.session_token)}async function Yb(t,e){let n=await Vb(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await Sc(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function Vb(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?$f(p.subject):void 0,issuer:p?.issuer?$f(p.issuer):void 0});return}let u=[l,d.message].filter(p=>p&&p.length>0);o({kind:"error",message:u.join(": ")||"unknown TLS error"})}),a.once("close",()=>{o({kind:"error",message:"connection closed before TLS handshake completed"})})})}function $f(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function Gb(t,e){let n=await zn(),r=n&&dn(n.pid)?n.loopbackPort:t.port,i=t.port===an?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function Qb(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
- `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function Of(){try{let t=Ff.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Bf(t){return t.port===an?t.host:`${t.host}:${t.port}`}var xc,tr=K(()=>{"use strict";Ne();qn();eo();gc();yc();to();qr();ro();eo();xc=class extends Error{host;port;constructor(e,n){let s=n===an?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${vn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});var z,wa=K(()=>{"use strict";z={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as Re}from"zod";var ap,xv,dp,cp,lp,Bc=K(()=>{"use strict";ap=Re.object({protocolVersion:Re.number().optional(),clientCapabilities:Re.record(Re.unknown()).optional(),clientInfo:Re.object({name:Re.string(),version:Re.string().optional()}).optional()}),xv=Re.enum(["full","pending_only","none","after_message"]),dp=Re.object({cwd:Re.string(),mcpServers:Re.array(Re.unknown()).optional(),_meta:Re.record(Re.unknown()).optional()}),cp=Re.object({upstreamSessionId:Re.string(),agentId:Re.string(),cwd:Re.string(),title:Re.string().optional(),agentArgs:Re.array(Re.string()).optional()}),lp=Re.object({sessionId:Re.string(),historyPolicy:xv.default("full"),afterMessageId:Re.string().optional(),clientId:Re.string().optional(),clientInfo:Re.object({name:Re.string(),version:Re.string().optional()}).optional(),_meta:Re.record(Re.unknown()).optional()})});import{z as ae}from"zod";function ba(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),t.compactionState!==void 0&&(n.compactionState=t.compactionState),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue),e.resurrected===!0&&(n.resurrected=!0)),n}function pp(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:io(t._meta,ba(t))};return t.title!==void 0&&(e.title=t.title),e}var up,fp,Nc,PT,Cv,MT,Dc=K(()=>{"use strict";va();up=ae.object({sessionId:ae.string()}),fp=ae.object({cwd:ae.string().optional(),cursor:ae.string().optional()}),Nc=ae.object({used:ae.number().optional(),size:ae.number().optional(),costAmount:ae.number().optional(),costCurrency:ae.string().optional()}),PT=ae.object({sessionId:ae.string(),upstreamSessionId:ae.string().optional(),cwd:ae.string(),title:ae.string().optional(),agentId:ae.string().optional(),currentModel:ae.string().optional(),currentUsage:Nc.optional(),importedFromMachine:ae.string().optional(),importedFromUpstreamSessionId:ae.string().optional(),parentSessionId:ae.string().optional(),forkedFromSessionId:ae.string().optional(),forkedFromMessageId:ae.string().optional(),originatingClient:ae.object({name:ae.string(),version:ae.string().optional()}).optional(),interactive:ae.boolean().optional(),priority:ae.number().int().nonnegative().optional(),updatedAt:ae.string(),attachedClients:ae.number().int().nonnegative(),status:ae.enum(["live","cold"]).default("live"),busy:ae.boolean().default(!1),awaitingInput:ae.boolean().default(!1),compactionState:ae.any().optional(),_meta:ae.record(ae.unknown()).optional()}),Cv=ae.object({sessionId:ae.string(),cwd:ae.string(),title:ae.string().optional(),updatedAt:ae.string().optional(),_meta:ae.record(ae.unknown()).optional()}),MT=ae.object({sessions:ae.array(Cv),nextCursor:ae.string().optional()})});function Av(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function Bt(t){if(!t)return{};let e=t[mt];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=cp.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Nc.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.resurrected=="boolean"&&(s.resurrected=n.resurrected),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=Av(n.env);r!==void 0&&(s.env=r)}return s}function io(t,e){return{...t??{},[mt]:e}}var mt,va=K(()=>{"use strict";Bc();Dc();mt="hydra-acp"});import{z as Q}from"zod";var mp,Sa,hp,BT,NT,DT,gp,HT,yp,UT,wp,jT,qT,bp=K(()=>{"use strict";mp=Q.object({sessionId:Q.string(),prompt:Q.array(Q.unknown()),_meta:Q.record(Q.unknown()).optional()}),Sa=Q.object({sessionId:Q.string()}),hp=Q.object({clientId:Q.string(),name:Q.string().optional(),version:Q.string().optional()}),BT=Q.object({sessionId:Q.string(),messageId:Q.string(),originator:hp,prompt:Q.array(Q.unknown()),position:Q.number().int().nonnegative(),queueDepth:Q.number().int().positive(),enqueuedAt:Q.number()}),NT=Q.object({sessionId:Q.string(),messageId:Q.string(),prompt:Q.array(Q.unknown())}),DT=Q.object({sessionId:Q.string(),messageId:Q.string(),reason:Q.enum(["started","cancelled","abandoned"])}),gp=Q.object({sessionId:Q.string(),messageId:Q.string()}),HT=Q.object({cancelled:Q.boolean(),reason:Q.enum(["ok","not_found","already_running"])}),yp=Q.object({sessionId:Q.string(),messageId:Q.string(),prompt:Q.array(Q.unknown())}),UT=Q.object({updated:Q.boolean(),reason:Q.enum(["ok","not_found","already_running"])}),wp=Q.object({sessionId:Q.string(),targetMessageId:Q.string(),prompt:Q.array(Q.unknown()),replaceQueue:Q.boolean().optional(),onTargetCompleted:Q.enum(["reject","send_anyway"]).optional()}),jT=Q.object({amended:Q.boolean(),reason:Q.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:Q.string().optional()}),qT=Q.object({sessionId:Q.string(),cancelledMessageId:Q.string(),newMessageId:Q.string(),prompt:Q.array(Q.unknown()),originator:hp,amendedAt:Q.number()})});import{z as fs}from"zod";var vp,ka,Sp=K(()=>{"use strict";vp=fs.object({agentId:fs.string(),version:fs.string(),source:fs.enum(["binary","npm"]),phase:fs.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:fs.number().optional(),totalBytes:fs.number().optional(),packageSpec:fs.string().optional()}),ka="hydra-acp/agents/install_progress"});var It=K(()=>{"use strict";wa();Bc();va();Dc();bp();Sp()});import{nanoid as Rv}from"nanoid";var Hc,Pt,sr=K(()=>{"use strict";It();Hc=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Pt=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new Hc;let s=Rv(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:i}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:z.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??z.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0:this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});async function Yr(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(c=>c.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Vr(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var Uc=K(()=>{"use strict"});import*as xp from"fs/promises";function Dv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var _v,$v,Gr,Ov,Fv,Lv,Bv,Nv,Ip,Ca,Cp=K(()=>{"use strict";_v=64*1024*1024,$v=1*1024*1024,Gr=64*1024,Ov=6e4,Fv=100,Lv=1e3,Bv=64*1024,Nv=256*1024,Ip=20;Ca=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??_v,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min($v,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,n){let s=Math.max(0,Math.min(n,Gr));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(f.gap=i),this.closed&&(f.eof=!0),f}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,Gr)),s=this.oldestAvailable,r=this.writeCursor-n,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let n=Math.max(0,Math.min(e,Gr)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,Ov));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(Dv(e.pattern),c),l=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Fv,Lv)),u=Math.max(1,Math.min(e.maxBytes??Bv,Nv)),p=Math.max(0,Math.min(e.contextBefore??0,Ip)),m=Math.max(0,Math.min(e.contextAfter??0,Ip)),h=[],w=[],b=[],v=0,S=!1,x=0,T=0,F=(J,B)=>{for(let Y of b)Y.remaining>0&&(Y.match.after===void 0&&(Y.match.after=[]),Y.match.after.push({cursor:J,line:B}),Y.remaining--,v+=B.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(B)!==l&&h.length<f){let Y={cursor:J,line:B};if(p>0&&w.length>0){Y.before=w.slice();for(let be of Y.before)v+=be.line.length}v+=B.length,h.push(Y),m>0&&b.push({match:Y,remaining:m})}if(p>0)for(w.push({cursor:J,line:B});w.length>p;)w.shift();let j=h.length>=f&&b.length===0,X=v>=u;return j||X};for(let J=0;J<o.length;J++){if(o[J]!==10)continue;let B=o.subarray(x,J).toString("utf8"),N=r+x;if(x=J+1,T=x,F(N,B)){S=!0;break}}if(!S&&x<o.length&&this.closed){let J=o.subarray(x).toString("utf8"),B=r+x;F(B,J)&&(S=!0),T=o.length}let $=Math.min(r+T,this.writeCursor),H={matches:h,truncated:S,nextCursor:$,scannedBytes:T};return i>0&&(H.gap=i),this.closed&&$>=this.writeCursor&&(H.eof=!0),H}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>xp.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Aa,fE,Ap=K(()=>{"use strict";Aa=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],fE=new Map(Aa.map(t=>[t.verb,t]))});function Rp(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function Qr(t,e){return jc(t,e.map(n=>n.modelId))}function jc(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Rp(t),s=e.filter(i=>Rp(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var Ra=K(()=>{"use strict"});function Tp(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=qc(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let f=n.get(l);f?f.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=qc(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Uv(r,i.outIndex,Hv(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let f=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let u=f!==void 0&&n.has(f)?jv(c,n.get(f)??[]):c;f!==void 0&&s.has(f)&&!qv(u)&&(u=Wv(u,s.get(f))),r.push(u);continue}if(l==="plan"){o!==null?r[o]=c:(r.push(c),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(c)}return r}function qc(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function Hv(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function Uv(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function jv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function qv(t){let n=qc(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function Wv(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var Ep=K(()=>{"use strict"});function Xr(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=zc(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=Jc(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(Wc(c))):d==="turn_complete"&&i()}return i(),Vv(s.join(`
15
- `),n)}function Wc(t){let e=Jv(t),n=Kv(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function Jv(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function Kv(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of zv){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${Yv(r,200)}`)}return n}function zc(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function Jc(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function Yv(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function Vv(t,e){if(t.length<=e)return t;let n=t.split(`
16
- `);for(;n.length>0;){let s=Pp+n.join(`
17
- `);if(s.length<=e)return s;n.shift()}return Pp}var Pp,zv,Ta=K(()=>{"use strict";Pp=`[older history truncated]
18
- `,zv=["file_path","path","command","pattern","query"]});function _p(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??Gv}`),t.synopsis.goal!==void 0&&t.synopsis.goal.trim().length>0&&e.push(`[Goal] ${t.synopsis.goal}`),t.synopsis.outcome!==void 0&&t.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${t.synopsis.outcome}`);let n=oo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=oo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=oo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=oo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=oo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Mp(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Mp(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=Qv(t.tail,t.tailK);return e.push("--- begin recent turns (verbatim, last "+t.tailK+") ---"),d.length>0&&e.push(d),e.push("--- end recent turns ---"),e.push(""),e.push("(Hydra has compacted earlier conversation. Detail is retrievable via the hydra-recall tools if you need to look up specifics. Acknowledge briefly and wait for the next user message.)"),e.join(`
19
- `)}function oo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
20
- `)}`}function Mp(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function Qv(t,e){if(t.length===0||e<=0)return"";let n=Xv(t);if(n.length===0)return"";let s=n.slice(-e),r=[];for(let i of s)if(i.user.length>0&&r.push("User: "+i.user),i.agent.length>0&&r.push("Assistant: "+i.agent),i.tools.length>0)for(let o of i.tools)r.push(o);return r.join(`
21
- `)}function Xv(t){let e=[],n=null;for(let s of t){if(s.method!=="session/update")continue;let i=s.params?.update;if(!i||typeof i.sessionUpdate!="string")continue;let o=i.sessionUpdate;if(o==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:zc(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=Jc(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(Wc(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var Gv,$p=K(()=>{"use strict";Ta();Gv="(untitled)"});import*as In from"fs/promises";async function ao(t,e){let n=_.queueFile(t);if(e.length===0){await In.unlink(n).catch(()=>{});return}await In.mkdir(_.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
12
+ sha256: ${Ca(b.fingerprint)}${v}
13
+ `),!await r(`Trust this certificate for ${l}? [y/N]: `))throw new Error(`Aborted: certificate for ${l} not trusted.`);po(t.host,t.port,b.fingerprint),f=b.fingerprint}else if(b.kind==="error")throw new Error(`Could not connect to ${l} for TLS handshake: ${b.message}`)}let p=await s(`Password for ${l}: `);if(p.length===0)throw new Error("Password is required to attach to a remote daemon.");let m=`${u}://${t.host}:${t.port}`,h=await n(`${m}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:p,label:Kf()})});if(h.status===401)throw new Error(`Wrong password for ${l}.`);if(h.status===403)throw new Error(`No password is configured on ${l}. Run \`hydra-acp auth password\` on the daemon host first.`);if(h.status===429)throw new Error(`Too many failed login attempts on ${l}; try again later.`);if(!h.ok)throw new Error(`Login to ${l} failed: HTTP ${h.status}`);let y=await h.json();if(!y.session_token||!y.expires_at)throw new Error(`Login to ${l} returned a malformed response.`);return await c.set(t.host,t.port,{token:y.session_token,expiresAt:y.expires_at,label:Kf(),...f?{pinnedFingerprint:f,pinnedAt:new Date().toISOString()}:{}}),zf(t,y.session_token)}async function pv(t,e){let n=await mv(t,e);return n.kind!=="untrusted"?n:{kind:"untrusted",fingerprint:await _c(t,e),...n.subject!==void 0?{subject:n.subject}:{},...n.issuer!==void 0?{issuer:n.issuer}:{}}}async function mv(t,e,n=1e4){let s=await import("tls");return new Promise(r=>{let i=!1,o=d=>{if(!i){i=!0,clearTimeout(c);try{a.destroy()}catch{}r(d)}},a=s.connect({host:t,port:e,servername:t,autoSelectFamily:!0}),c=setTimeout(()=>o({kind:"error",message:`TLS connect timed out after ${n}ms`}),n);a.once("secureConnect",()=>o({kind:"trusted"})),a.once("error",d=>{let l=d.code??"";if(l==="DEPTH_ZERO_SELF_SIGNED_CERT"||l==="SELF_SIGNED_CERT_IN_CHAIN"||l==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||l==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||l==="UNABLE_TO_GET_ISSUER_CERT"||l==="CERT_HAS_EXPIRED"||l==="ERR_TLS_CERT_ALTNAME_INVALID"){let p=a.getPeerCertificate(!1);o({kind:"untrusted",subject:p?.subject?Jf(p.subject):void 0,issuer:p?.issuer?Jf(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 Jf(t){if(!t)return"";let e=[];for(let[n,s]of Object.entries(t)){let r=Array.isArray(s)?s.join(", "):s;e.push(`${n}=${r}`)}return e.join(", ")}async function hv(t,e){let n=await Zn(),r=n&&mn(n.pid)?n.loopbackPort:t.port,i=t.port===pn?t.host:`${t.host}:${t.port}`;return{baseUrl:`http://127.0.0.1:${r}`,wsUrl:`ws://127.0.0.1:${r}/acp`,token:e,display:i,isLocal:!0}}async function gv(t){return process.stdout.write(t),new Promise(e=>{let n="",s=r=>{n+=r.toString("utf8");let i=n.indexOf(`
14
+ `);if(i===-1)return;process.stdin.removeListener("data",s),process.stdin.pause();let o=n.slice(0,i).trim().toLowerCase();e(o==="y"||o==="yes")};process.stdin.resume(),process.stdin.on("data",s)})}function Kf(){try{let t=Vf.hostname();return t.length>0?t:"remote"}catch{return"remote"}}function Qf(t){return t.port===pn?t.host:`${t.host}:${t.port}`}var Oc,ur=K(()=>{"use strict";je();Gn();uo();Rc();Tc();fo();ei();ho();uo();Oc=class extends Error{host;port;constructor(e,n){let s=n===pn?"":`:${n}`;super(`No cached credentials for ${e}:${n}. Run \`${Cn()} --session hydra://${e}${s}/\` once in a terminal to log in.`),this.name="NoCachedCredentialError",this.host=e,this.port=n}}});var W,Ma=K(()=>{"use strict";W={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014}});import{z as _e}from"zod";var vp,qv,Sp,kp,Ip,Vc=K(()=>{"use strict";vp=_e.object({protocolVersion:_e.number().optional(),clientCapabilities:_e.record(_e.unknown()).optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional()}),qv=_e.enum(["full","pending_only","none","after_message"]),Sp=_e.object({cwd:_e.string(),mcpServers:_e.array(_e.unknown()).optional(),_meta:_e.record(_e.unknown()).optional()}),kp=_e.object({upstreamSessionId:_e.string(),agentId:_e.string(),cwd:_e.string(),title:_e.string().optional(),agentArgs:_e.array(_e.string()).optional()}),Ip=_e.object({sessionId:_e.string(),historyPolicy:qv.default("full"),afterMessageId:_e.string().optional(),clientId:_e.string().optional(),clientInfo:_e.object({name:_e.string(),version:_e.string().optional()}).optional(),_meta:_e.record(_e.unknown()).optional()})});import{z as oe}from"zod";function _a(t,e){let n={attachedClients:t.attachedClients,status:t.status,busy:t.busy,awaitingInput:t.awaitingInput};return t.cwd!==void 0&&(n.cwd=t.cwd),t.title!==void 0&&(n.title=t.title),t.agentId!==void 0&&(n.agentId=t.agentId),t.upstreamSessionId!==void 0&&(n.upstreamSessionId=t.upstreamSessionId),t.currentModel!==void 0&&(n.currentModel=t.currentModel),t.currentUsage!==void 0&&(n.currentUsage=t.currentUsage),t.importedFromMachine!==void 0&&(n.importedFromMachine=t.importedFromMachine),t.importedFromUpstreamSessionId!==void 0&&(n.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),t.parentSessionId!==void 0&&(n.parentSessionId=t.parentSessionId),t.forkedFromSessionId!==void 0&&(n.forkedFromSessionId=t.forkedFromSessionId),t.forkedFromMessageId!==void 0&&(n.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient!==void 0&&(n.originatingClient=t.originatingClient),t.interactive!==void 0&&(n.interactive=t.interactive),t.priority!==void 0&&t.priority>0&&(n.priority=t.priority),t.compactionState!==void 0&&(n.compactionState=t.compactionState),e&&(e.clientId!==void 0&&(n.clientId=e.clientId),e.currentMode!==void 0&&(n.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(n.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(n.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(n.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(n.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(n.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(n.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(n.queue=e.queue),e.resurrected===!0&&(n.resurrected=!0)),n}function Ap(t){let e={sessionId:t.sessionId,cwd:t.cwd,updatedAt:t.updatedAt,_meta:go(t._meta,_a(t))};return t.title!==void 0&&(e.title=t.title),e}var xp,Cp,Yc,oE,Wv,aE,Qc=K(()=>{"use strict";$a();xp=oe.object({sessionId:oe.string()}),Cp=oe.object({cwd:oe.string().optional(),cursor:oe.string().optional()}),Yc=oe.object({used:oe.number().optional(),size:oe.number().optional(),costAmount:oe.number().optional(),costCurrency:oe.string().optional()}),oE=oe.object({sessionId:oe.string(),upstreamSessionId:oe.string().optional(),cwd:oe.string(),title:oe.string().optional(),agentId:oe.string().optional(),currentModel:oe.string().optional(),currentUsage:Yc.optional(),importedFromMachine:oe.string().optional(),importedFromUpstreamSessionId:oe.string().optional(),parentSessionId:oe.string().optional(),forkedFromSessionId:oe.string().optional(),forkedFromMessageId:oe.string().optional(),originatingClient:oe.object({name:oe.string(),version:oe.string().optional()}).optional(),interactive:oe.boolean().optional(),priority:oe.number().int().nonnegative().optional(),updatedAt:oe.string(),attachedClients:oe.number().int().nonnegative(),status:oe.enum(["live","cold"]).default("live"),busy:oe.boolean().default(!1),awaitingInput:oe.boolean().default(!1),compactionState:oe.any().optional(),_meta:oe.record(oe.unknown()).optional()}),Wv=oe.object({sessionId:oe.string(),cwd:oe.string(),title:oe.string().optional(),updatedAt:oe.string().optional(),_meta:oe.record(oe.unknown()).optional()}),aE=oe.object({sessions:oe.array(Wv),nextCursor:oe.string().optional()})});function zv(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e={};for(let[n,s]of Object.entries(t)){if(typeof n!="string"||n.length===0||typeof s!="string")return;e[n]=s}return e}function qt(t){if(!t)return{};let e=t[ht];if(!e||typeof e!="object"||Array.isArray(e))return{};let n=e,s={};if(typeof n.upstreamSessionId=="string"&&(s.upstreamSessionId=n.upstreamSessionId),typeof n.agentId=="string"&&(s.agentId=n.agentId),typeof n.cwd=="string"&&(s.cwd=n.cwd),typeof n.clientId=="string"&&(s.clientId=n.clientId),typeof n.readonly=="boolean"&&(s.readonly=n.readonly),(n.replayMode==="instant"||n.replayMode==="drip")&&(s.replayMode=n.replayMode),typeof n.dripSpeed=="number"&&n.dripSpeed>0&&(s.dripSpeed=n.dripSpeed),(n.toolContent==="inline"||n.toolContent==="references")&&(s.toolContent=n.toolContent),n.detachStatus==="detached"&&(s.detachStatus=n.detachStatus),typeof n.title=="string"&&(s.title=n.title),Array.isArray(n.agentArgs)&&n.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=n.agentArgs),Array.isArray(n.transformers)&&n.transformers.every(r=>typeof r=="string")&&(s.transformers=n.transformers),n.resume){let r=kp.safeParse(n.resume);r.success&&(s.resume=r.data)}if(typeof n.model=="string"&&(s.model=n.model),typeof n.currentModel=="string"&&(s.currentModel=n.currentModel),typeof n.currentMode=="string"&&(s.currentMode=n.currentMode),n.currentUsage){let r=Yc.safeParse(n.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof n.turnStartedAt=="number"&&n.turnStartedAt>0&&(s.turnStartedAt=n.turnStartedAt),Array.isArray(n.availableCommands)){let r=[];for(let i of n.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(n.prompt&&typeof n.prompt=="object"&&!Array.isArray(n.prompt)){let r=n.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(n.agents&&typeof n.agents=="object"&&!Array.isArray(n.agents)){let r=n.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof n.mcpStdin=="boolean"&&(s.mcpStdin=n.mcpStdin),typeof n.interactive=="boolean"&&(s.interactive=n.interactive),typeof n.ancillary=="boolean"&&(s.ancillary=n.ancillary),Array.isArray(n.queue)){let r=[];for(let i of n.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:o.messageId,originator:c,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(n.availableModes)){let r=[];for(let i of n.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(n.availableModels)){let r=[];for(let i of n.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((n.status==="live"||n.status==="cold")&&(s.status=n.status),typeof n.busy=="boolean"&&(s.busy=n.busy),typeof n.awaitingInput=="boolean"&&(s.awaitingInput=n.awaitingInput),typeof n.attachedClients=="number"&&(s.attachedClients=n.attachedClients),typeof n.resurrected=="boolean"&&(s.resurrected=n.resurrected),typeof n.importedFromMachine=="string"&&(s.importedFromMachine=n.importedFromMachine),typeof n.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),typeof n.parentSessionId=="string"&&(s.parentSessionId=n.parentSessionId),typeof n.forkedFromSessionId=="string"&&(s.forkedFromSessionId=n.forkedFromSessionId),typeof n.forkedFromMessageId=="string"&&(s.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient&&typeof n.originatingClient=="object"&&!Array.isArray(n.originatingClient)&&typeof n.originatingClient.name=="string"){let r=n.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(n.agentCapabilities!==void 0&&(s.agentCapabilities=n.agentCapabilities),n.env!==void 0){let r=zv(n.env);r!==void 0&&(s.env=r)}return s}function go(t,e){return{...t??{},[ht]:e}}var ht,$a=K(()=>{"use strict";Vc();Qc();ht="hydra-acp"});import{z as X}from"zod";var Rp,Fa,Tp,pE,mE,hE,Ep,gE,Pp,yE,Mp,wE,bE,_p=K(()=>{"use strict";Rp=X.object({sessionId:X.string(),prompt:X.array(X.unknown()),_meta:X.record(X.unknown()).optional()}),Fa=X.object({sessionId:X.string()}),Tp=X.object({clientId:X.string(),name:X.string().optional(),version:X.string().optional()}),pE=X.object({sessionId:X.string(),messageId:X.string(),originator:Tp,prompt:X.array(X.unknown()),position:X.number().int().nonnegative(),queueDepth:X.number().int().positive(),enqueuedAt:X.number()}),mE=X.object({sessionId:X.string(),messageId:X.string(),prompt:X.array(X.unknown())}),hE=X.object({sessionId:X.string(),messageId:X.string(),reason:X.enum(["started","cancelled","abandoned"])}),Ep=X.object({sessionId:X.string(),messageId:X.string()}),gE=X.object({cancelled:X.boolean(),reason:X.enum(["ok","not_found","already_running"])}),Pp=X.object({sessionId:X.string(),messageId:X.string(),prompt:X.array(X.unknown())}),yE=X.object({updated:X.boolean(),reason:X.enum(["ok","not_found","already_running"])}),Mp=X.object({sessionId:X.string(),targetMessageId:X.string(),prompt:X.array(X.unknown()),replaceQueue:X.boolean().optional(),onTargetCompleted:X.enum(["reject","send_anyway"]).optional()}),wE=X.object({amended:X.boolean(),reason:X.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:X.string().optional()}),bE=X.object({sessionId:X.string(),cancelledMessageId:X.string(),newMessageId:X.string(),prompt:X.array(X.unknown()),originator:Tp,amendedAt:X.number()})});import{z as xs}from"zod";var $p,Oa,Fp=K(()=>{"use strict";$p=xs.object({agentId:xs.string(),version:xs.string(),source:xs.enum(["binary","npm"]),phase:xs.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:xs.number().optional(),totalBytes:xs.number().optional(),packageSpec:xs.string().optional()}),Oa="hydra-acp/agents/install_progress"});var xt=K(()=>{"use strict";Ma();Vc();$a();Qc();_p();Fp()});import{nanoid as Jv}from"nanoid";var Gc,_t,pr=K(()=>{"use strict";xt();Gc=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},_t=class t{constructor(e){this.stream=e;this.stream.onMessage(n=>this.handleIncoming(n)),this.stream.onClose(n=>this.handleClose(n))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,n){this.requestHandlers.set(e,n)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,n){this.notificationHandlers.set(e,n);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{n(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,n){return this.requestWithId(e,n).response}requestWithId(e,n){if(this.closed)throw new Gc;let s=Jv(),r={jsonrpc:"2.0",id:s,method:e,params:n},i=new Promise((o,a)=>{this.pending.set(s,{resolve:c=>o(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});return{id:s,response:i}}notify(e,n){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:n};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let n=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!n){await this.sendError(e.id,{code:W.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await n(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??W.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let n=this.notificationHandlers.get(e.method);if(n){n(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=t.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>t.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let n=e.id===null?void 0:this.pending.get(e.id);if(!n){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,n.reject(s)}else n.resolve(e.result)}async sendError(e,n){let s={jsonrpc:"2.0",id:e,error:n};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let n of this.pending.values())n.reject(e??new Error("connection closed"));this.pending.clear();for(let n of this.closeHandlers)n(e)}}}});async function ii(t){let{agent:e,upstreamSessionId:n,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=t;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(c=>c.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:n,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function oi(t){let{agent:e,upstreamSessionId:n,persistedModel:s,agentReportedModel:r,logger:i}=t;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:n,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}var Xc=K(()=>{"use strict"});import*as Bp from"fs/promises";function rS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Gv,Xv,ai,Zv,eS,tS,nS,sS,Lp,Na,Np=K(()=>{"use strict";Gv=64*1024*1024,Xv=1*1024*1024,ai=64*1024,Zv=6e4,eS=100,tS=1e3,nS=64*1024,sS=256*1024,Lp=20;Na=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??Gv,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Xv,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,n){let s=Math.max(0,Math.min(n,ai));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let c=Math.min(a,s),l={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return i>0&&(l.gap=i),this.closed&&r+c>=this.writeCursor&&(l.eof=!0),l}tail(e){let n=Math.max(0,Math.min(e,ai)),s=this.oldestAvailable,r=this.writeCursor-n,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let n=Math.max(0,Math.min(e,ai)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+n);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,n){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(n,Zv));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let n=this.oldestAvailable,s=e.cursor,r=s??n,i=0;s!==void 0&&s<n&&(i=n-s,r=n),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",d=a?new RegExp(e.pattern,c):new RegExp(rS(e.pattern),c),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??eS,tS)),f=Math.max(1,Math.min(e.maxBytes??nS,sS)),p=Math.max(0,Math.min(e.contextBefore??0,Lp)),m=Math.max(0,Math.min(e.contextAfter??0,Lp)),h=[],y=[],b=[],v=0,S=!1,x=0,T=0,_=(J,D)=>{for(let V of b)V.remaining>0&&(V.match.after===void 0&&(V.match.after=[]),V.match.after.push({cursor:J,line:D}),V.remaining--,v+=D.length);for(;b.length>0&&b[0].remaining===0;)b.shift();if(d.test(D)!==l&&h.length<u){let V={cursor:J,line:D};if(p>0&&y.length>0){V.before=y.slice();for(let be of V.before)v+=be.line.length}v+=D.length,h.push(V),m>0&&b.push({match:V,remaining:m})}if(p>0)for(y.push({cursor:J,line:D});y.length>p;)y.shift();let U=h.length>=u&&b.length===0,Q=v>=f;return U||Q};for(let J=0;J<o.length;J++){if(o[J]!==10)continue;let D=o.subarray(x,J).toString("utf8"),L=r+x;if(x=J+1,T=x,_(L,D)){S=!0;break}}if(!S&&x<o.length&&this.closed){let J=o.subarray(x).toString("utf8"),D=r+x;_(D,J)&&(S=!0),T=o.length}let F=Math.min(r+T,this.writeCursor),j={matches:h,truncated:S,nextCursor:F,scannedBytes:T};return i>0&&(j.gap=i),this.closed&&F>=this.writeCursor&&(j.eof=!0),j}wakeWaiters(e){if(this.waiters.length===0)return;let n=this.waiters;this.waiters=[];for(let s of n)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let n=this.writeCursor+e;if(n<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<n&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let n=e.length;if(this.growIfNeeded(n),n>=this.currentCapacityBytes){let i=n-this.currentCapacityBytes;e.copy(this.storage,0,i,n);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;n<=r?e.copy(this.storage,s,0,n):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,n))}sliceFromRing(e,n){if(n<=0)return Buffer.alloc(0);let s=Buffer.alloc(n),r=e%this.currentCapacityBytes,i=Math.min(n,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<n&&this.storage.copy(s,i,0,n-i),s}scheduleFileWrite(e){let n=this.filePath;if(n===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Bp.appendFile(n,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}}});var Da,jE,Dp=K(()=>{"use strict";Da=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],jE=new Map(Da.map(t=>[t.verb,t]))});function Hp(t){let e=t.lastIndexOf("/");return(e===-1?t:t.slice(e+1)).toLowerCase()}function di(t,e){return Zc(t,e.map(n=>n.modelId))}function Zc(t,e){if(e.length===0)return{kind:"none",requested:t};if(e.includes(t))return{kind:"exact",modelId:t};let n=Hp(t),s=e.filter(i=>Hp(i)===n);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:t};if(s.length>1)return{kind:"ambiguous",requested:t,candidates:s};let r=t.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:t};if(i.length>1)return{kind:"ambiguous",requested:t,candidates:i}}return{kind:"unknown",requested:t}}var Ha=K(()=>{"use strict"});function Up(t){if(t.length===0)return t;let e=new Map,n=new Map,s=new Map;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=el(c);if(d?.sessionUpdate!=="tool_call_update")continue;let l=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),d.rawInput&&typeof d.rawInput=="object"&&!Array.isArray(d.rawInput)&&Object.keys(d.rawInput).length>0&&s.set(l,d.rawInput),Array.isArray(d.content)&&d.content.length>0)){let u=n.get(l);u?u.push(...d.content):n.set(l,[...d.content])}}let r=[],i=null,o=null;for(let a=0;a<t.length;a++){let c=t[a];if(c===void 0)continue;let d=el(c);if(!d||typeof d.sessionUpdate!="string"){r.push(c),i=null;continue}let l=d.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?oS(r,i.outIndex,iS(d.content)):(r.push(c),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof d.toolCallId=="string"?d.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&n.has(u)?aS(c,n.get(u)??[]):c;u!==void 0&&s.has(u)&&!dS(f)&&(f=cS(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 el(t){if(t.method!=="session/update")return;let n=t.params?.update;if(!(!n||typeof n!="object"||Array.isArray(n)))return n}function iS(t){if(!t||typeof t!="object")return"";let e=t;return typeof e.text=="string"?e.text:""}function oS(t,e,n){if(n.length===0)return;let s=t[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";t[e]={...s,params:{...r,update:{...i,content:{...o,text:a+n}}}}}function aS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,content:e}}}}function dS(t){let n=el(t)?.rawInput;return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0}function cS(t,e){let n=t.params??{},s=n.update??{};return{...t,params:{...n,update:{...s,rawInput:e}}}}var jp=K(()=>{"use strict"});function ci(t,e={}){let n=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of t){if(o.method!=="session/update")continue;let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate;if(d==="prompt_received"){i();let l=nl(c.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(d==="agent_message_chunk"){let l=sl(c.content);l.length>0&&(r+=l)}else d==="tool_call"?(i(),s.push(tl(c))):d==="turn_complete"&&i()}return i(),mS(s.join(`
15
+ `),n)}function tl(t){let e=uS(t),n=fS(t.rawInput);return n.length===0?`Tool: ${e}`:`Tool: ${e}(${n.join(", ")})`}function uS(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function fS(t){if(!t||typeof t!="object"||Array.isArray(t))return[];let e=t,n=[];for(let s of lS){let r=e[s];typeof r=="string"&&r.length>0&&n.push(`${s}=${pS(r,200)}`)}return n}function nl(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(e&&typeof e=="object"){let n=e.text;if(typeof n=="string")return n}return""}).join(""):""}function sl(t){if(!t||typeof t!="object")return"";let e=t.text;return typeof e=="string"?e:""}function pS(t,e){return t.length<=e?t:t.slice(0,e-1)+"\u2026"}function mS(t,e){if(t.length<=e)return t;let n=t.split(`
16
+ `);for(;n.length>0;){let s=qp+n.join(`
17
+ `);if(s.length<=e)return s;n.shift()}return qp}var qp,lS,Ua=K(()=>{"use strict";qp=`[older history truncated]
18
+ `,lS=["file_path","path","command","pattern","query"]});function zp(t){let e=[];e.push("--- begin prior session compaction ---"),e.push(`[Title] ${t.title??hS}`),t.synopsis.goal!==void 0&&t.synopsis.goal.trim().length>0&&e.push(`[Goal] ${t.synopsis.goal}`),t.synopsis.outcome!==void 0&&t.synopsis.outcome.trim().length>0&&e.push(`[Outcome] ${t.synopsis.outcome}`);let n=yo("Open threads",t.synopsis.open_threads);n.length>0&&e.push(n);let s=yo("Decisions",t.synopsis.decisions);s.length>0&&e.push(s);let r=yo("File edit intentions",t.synopsis.file_edit_intentions);r.length>0&&e.push(r);let i=yo("Unresolved errors",t.synopsis.unresolved_errors);i.length>0&&e.push(i);let o=yo("Tool state",t.synopsis.tool_state);o.length>0&&e.push(o);let a=Wp(t.synopsis.files_touched);a.length>0&&e.push(`[Files previously touched] ${a}`);let c=Wp(t.synopsis.tools_used);c.length>0&&e.push(`[Tools previously used] ${c}`),e.push("--- end prior session compaction ---");let d=gS(t.tail,t.tailK);return e.push("--- begin recent turns (verbatim, last "+t.tailK+") ---"),d.length>0&&e.push(d),e.push("--- end recent turns ---"),e.push(""),e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"),e.join(`
19
+ `)}function yo(t,e){if(!e||!Array.isArray(e))return"";let n=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(n.length===0)return"";let s=n.map(r=>"- "+r.trim());return`[${t}] ${s.join(`
20
+ `)}`}function Wp(t){if(!t||!Array.isArray(t))return"";let e=t.filter(n=>typeof n=="string"&&n.trim().length>0);return e.length===0?"":e.map(n=>n.trim()).join(", ")}function gS(t,e){if(t.length===0||e<=0)return"";let n=yS(t);if(n.length===0)return"";let s=n.slice(-e),r=[];for(let i of s)if(i.user.length>0&&r.push("User: "+i.user),i.agent.length>0&&r.push("Assistant: "+i.agent),i.tools.length>0)for(let o of i.tools)r.push(o);return r.join(`
21
+ `)}function yS(t){let e=[],n=null;for(let s of t){if(s.method!=="session/update")continue;let i=s.params?.update;if(!i||typeof i.sessionUpdate!="string")continue;let o=i.sessionUpdate;if(o==="prompt_received")n!==null&&n.user.length>0&&e.push(n),n={user:nl(i.prompt).trim(),agent:"",tools:[]};else if(o==="agent_message_chunk"&&n!==null){let a=sl(i.content);a.length>0&&(n.agent+=a)}else o==="tool_call"&&n!==null?n.tools.push(tl(i)):o==="turn_complete"&&n!==null&&(e.push(n),n=null)}return n!==null&&n.user.length>0&&e.push(n),e}var hS,Jp=K(()=>{"use strict";Ua();hS="(untitled)"});import*as Tn from"fs/promises";async function wo(t,e){let n=$.queueFile(t);if(e.length===0){await Tn.unlink(n).catch(()=>{});return}await Tn.mkdir($.sessionDir(t),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
22
22
  `)+`
23
- `;await In.writeFile(n,s,"utf8")}async function Op(t){let e=_.queueFile(t),n;try{n=await In.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
24
- `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Fp(t){let e=_.queueFile(t);await In.unlink(e).catch(()=>{})}var Kc=K(()=>{"use strict";pe()});import{customAlphabet as Dp}from"nanoid";import*as jp from"fs/promises";function Zr(){return`m_${Up()}`}function Ve(t){return t.startsWith(Jt)?t.slice(Jt.length):t}function Mt(t,e){return t.code=e,t}function Bp(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&nS.has(s)}function sS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function rS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function iS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ti(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function co(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function oS(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function aS(t,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&t.chunks.push(r.text)}function dS(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function cS(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:Zr()}}}function Gc(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function lS(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function uS(t){let e=fS(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=pS(t.resolver),n}function fS(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function pS(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function ei(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Vc(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Np(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
23
+ `;await Tn.writeFile(n,s,"utf8")}async function Kp(t){let e=$.queueFile(t),n;try{n=await Tn.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n.split(`
24
+ `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Vp(t){let e=$.queueFile(t);await Tn.unlink(e).catch(()=>{})}var rl=K(()=>{"use strict";he()});import{customAlphabet as Xp}from"nanoid";import*as tm from"fs/promises";function mr(){return`m_${em()}`}function et(t){return t.startsWith(Zt)?t.slice(Zt.length):t}function $t(t,e){return t.code=e,t}function Qp(t,e){if(t!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&SS.has(s)}function kS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function IS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.id!==e[n]?.id||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function xS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]?.modelId!==e[n]?.modelId||t[n]?.name!==e[n]?.name||t[n]?.description!==e[n]?.description)return!1;return!0}function ui(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function bo(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function CS(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_modes_update")return null;let s=n.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function AS(t,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.chunks.push(i.text),t.messageChars+=i.text.length);return}if(r==="agent_thought_chunk"){let i=s.content??{};typeof i.text=="string"&&(t.thinkingChars+=i.text.length);return}if(r==="tool_call"){t.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(t.lastUsed=s.used),typeof s.size=="number"&&(t.lastSize=s.size);return}}function RS(t){let n=(t??{}).update??{};if(n.sessionUpdate!=="available_commands_update")return null;let s=n.availableCommands??n.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function TS(t,e){if(t!=="session/update"||!e||typeof e!="object")return e;let n=e;return!n.update||typeof n.update!="object"||Array.isArray(n.update)||typeof n.update.messageId=="string"?e:{...e,update:{...n.update,messageId:mr()}}}function al(t,e){for(let n=0;n<t.length;n++){let s=t[n];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return n}return-1}function ES(t){if(!t||typeof t!="object")return;let e=t.toolCall;if(!e||typeof e!="object")return;let n=e.toolCallId;return typeof n=="string"?n:void 0}function PS(t){let e=MS(t.result),n={sessionUpdate:"permission_resolved"};return t.toolCallId!==void 0&&(n.toolCallId=t.toolCallId),e&&(n.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(n.chosenOptionId=e.optionId)),n.resolvedBy=_S(t.resolver),n}function MS(t){if(!t||typeof t!="object")return;let e=t.outcome;if(!e||typeof e!="object")return;let n=e.kind;if(typeof n!="string")return;let s={kind:n},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function _S(t){let e={clientId:t.clientId};return t.clientInfo?.name&&(e.name=t.clientInfo.name),t.clientInfo?.version&&(e.version=t.clientInfo.version),e}function li(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function ol(t){return t==="session/prompt"?{stopReason:"stopped"}:{}}function Gp(t){let e=t.name&&t.name!==t.id?`${t.id} (${t.name}) \u2014 \u25B6 ${t.currentValue}`:`${t.id} \u2014 \u25B6 ${t.currentValue}`;if(t.options.length===0)return e;let n=Math.max(...t.options.map(r=>r.value.length)),s=t.options.map(r=>{let i=r.value===t.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(n):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
25
25
  ${s.join(`
26
- `)}`}function Qc(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Hp,Up,Lp,Zv,Jt,eS,Yc,tS,ni,nS,xn=K(()=>{"use strict";Uc();Cp();Ap();Ra();Ep();$p();Kc();It();Hp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Up=Dp(Hp,16),Lp=Dp(Hp,16),Zv=20,Jt="hydra_session_";eS=1e3,Yc=300*1e3,tS=64,ni=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Jt}${Up()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.getCompactionStateHook=e.getCompactionState,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??eS,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){aS(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,n=new Set,s=0){let r=e,i=this.injectCumulativeCost(e);for(let c=s;c<this.transformChain.length;c++){let d=this.transformChain[c];if(n.has(d.name)||!d.intercepts.has("response:session/update"))continue;let l=`t_${Lp()}`,f;try{f=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on response:session/update: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return;if(u==="processing"){let p=c,m=i,h=new Set(n);await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.runResponseChain(m,new Set([...h,d.name]),p+1).then(()=>w()).catch(()=>w()))},Yc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:()=>w(),timer:b,transformerName:d.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(d.name)}let o=dS(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=oS(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.inFlightPermissions.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");let s=this.agentId,r=this.cwd,i=this.agentArgs,o=this.forwardedEnv,a=this.currentModel,c=this.currentMode,d=this.spawnReplacementAgent;if(!d)throw new Error("agent spawning not configured for this session");let l=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],f=await d({agentId:s,cwd:r,agentArgs:i,...o?{forwardedEnv:o}:{},mcpServers:l});this.accumulateAndResetCost(),this.wireAgent(f.agent),await Vr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedModel:a,agentReportedModel:f.initialModel,logger:this.logger}),await Yr({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedMode:c,agentReportedMode:f.initialMode,logger:this.logger}),f.agent.connection.drainBuffered("session/update");let u=[];if(this.historyStore)try{u=await this.historyStore.load(this.sessionId)}catch(v){this.logger?.warn(`swapUpstream: historyStore.load failed: ${v.message}`)}let p=_p({synopsis:e.artifact,title:e.title,tail:u,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[]};try{await f.agent.connection.request("session/prompt",{sessionId:f.upstreamSessionId,prompt:[{type:"text",text:p}]})}finally{this.internalPromptCapture=void 0}let m=this.upstreamSessionId,h=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let w=this.agent;this.agent=f.agent,this.upstreamSessionId=f.upstreamSessionId,this.agentMeta=f.agentMeta,this.agentCapabilities=f.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let v of this.agentChangeHandlers)try{v({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(S){this.logger?.warn(`swapUpstream: agentChange handler failed: ${S.message}`)}if(this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:m,...h!==void 0?{previousSummarizedThroughEntry:h}:{}})}catch(v){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${v.message}`)}await w.kill().catch(()=>{}),this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0});let b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
26
+ `)}`}function dl(t,e){for(let n of t.split(/\r?\n/)){let s=n.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}var Zp,em,Yp,wS,Zt,bS,il,vS,fi,SS,En=K(()=>{"use strict";Xc();Np();Dp();Ha();jp();Jp();rl();xt();Zp="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",em=Xp(Zp,16),Yp=Xp(Zp,16),wS=20,Zt="hydra_session_";bS=1e3,il=300*1e3,vS=64,fi=class t{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;getCompactionStateHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},n=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:n||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${Zt}${em()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.getCompactionStateHook=e.getCompactionState,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let n=e.compactionState;(n.status==="requested"||n.status==="running"||n.status==="swap_pending"||n.status==="swap_deferred")&&(n.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:n.attempts}:this._liveCompactionPhase={phase:n.status==="requested"?"started":"iteration",iter:n.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let n of e.attentionFlags)this.attentionFlags.set(`${n.source}::${n.reason}`,n);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??bS,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",n=>{if(this.internalPromptCapture){AS(this.internalPromptCapture,n);return}this.runResponseChain(n)}),e.connection.onRequest("session/request_permission",async n=>this.handlePermissionRequest(n)),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(n=>{this.handleOrphanError(n)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let n=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||n>t.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,n=new Set,s=0){let r=e,i=this.injectCumulativeCost(e);for(let c=s;c<this.transformChain.length;c++){let d=this.transformChain[c];if(n.has(d.name)||!d.intercepts.has("response:session/update"))continue;let l=`t_${Yp()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${d.name} error on response:session/update: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return;if(f==="processing"){let p=c,m=i,h=new Set(n);await new Promise(y=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.runResponseChain(m,new Set([...h,d.name]),p+1).then(()=>y()).catch(()=>y()))},il);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:()=>y(),timer:b,transformerName:d.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:h,side:"response"})});return}n.add(d.name)}let o=RS(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=CS(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let n=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),n.push(r)}return n}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");let s=this.agentId,r=this.cwd,i=this.agentArgs,o=this.forwardedEnv,a=this.currentModel,c=this.currentMode,d=this.spawnReplacementAgent;if(!d)throw new Error("agent spawning not configured for this session");let l=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],u=await d({agentId:s,cwd:r,agentArgs:i,...o?{forwardedEnv:o}:{},mcpServers:l});this.accumulateAndResetCost(),this.wireAgent(u.agent),await oi({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedModel:a,agentReportedModel:u.initialModel,logger:this.logger}),await ii({agent:u.agent,upstreamSessionId:u.upstreamSessionId,persistedMode:c,agentReportedMode:u.initialMode,logger:this.logger}),u.agent.connection.drainBuffered("session/update");let f=[];if(this.historyStore)try{f=await this.historyStore.load(this.sessionId)}catch(v){this.logger?.warn(`swapUpstream: historyStore.load failed: ${v.message}`)}let p=zp({synopsis:e.artifact,title:e.title,tail:f,tailK:e.tailK});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await u.agent.connection.request("session/prompt",{sessionId:u.upstreamSessionId,prompt:[{type:"text",text:p}]});let v=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${p.length} toolCalls=${v.toolCalls} thinkingChars=${v.thinkingChars} messageChars=${v.messageChars} used=${v.lastUsed??"?"} size=${v.lastSize??"?"} reply=${JSON.stringify(v.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let m=this.upstreamSessionId,h=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=u.agent,this.upstreamSessionId=u.upstreamSessionId,this.agentMeta=u.agentMeta,this.agentCapabilities=u.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let v of this.agentChangeHandlers)try{v({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(S){this.logger?.warn(`swapUpstream: agentChange handler failed: ${S.message}`)}if(this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:m,...h!==void 0?{previousSummarizedThroughEntry:h}:{}})}catch(v){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${v.message}`)}await y.kill().catch(()=>{}),this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0});let b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
27
27
  Compaction completed.
28
- `},_meta:{"hydra-acp":{synthetic:!0}}}});for(let v of this.clients.values())v.connection.notify("session/update",b).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await Vr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Yr({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger}),l.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let u of this.agentChangeHandlers)try{u({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(p){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${p.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Zv){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let f=c.status;(f==="completed"||f==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{})}attach(e,n,s={}){if(this.closed)throw Mt(new Error("session is closed"),z.SessionNotFound);if(this.clients.has(e.clientId))throw Mt(new Error(`client ${e.clientId} is already attached`),z.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=a=>n.raw?a:Tp(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Bp(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?Gc(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.inFlightPermissions)n.addClient(e)}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw Mt(new Error("client not attached"),z.SessionNotFound);if(this.closing)throw Mt(new Error("session is closing; new prompts cannot be accepted"),z.SessionClosing);let r=Zr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(Bt((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=ei(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Zr()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>tS;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw Mt(new Error("client not attached"),z.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=Zr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,n){let s=Zr(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw Mt(new Error("client not attached"),z.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Lp()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${d}: ${p.message}`);continue}let u=f?.action??"continue";if(u==="stop")return i==="notification"?void 0:f?.payload??Vc(e);if(u==="processing"){let p=a,m=o,h=new Set(s);return new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.forwardRequest(e,m,new Set([...h,c.name]),p+1,i).then(w).catch(()=>w(i==="notification"?void 0:Vc(e))))},Yc);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:w,timer:b,transformerName:c.name,method:e,envelope:m,chainIdx:p,originatedBy:h,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):Yc,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:Vc(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=ei((e??{}).prompt),r=Qc(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=ti(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=ti(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=co(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=ti(o.options);if(c.length>0){let d=co(o.options),l=d.length>0?d.map(w=>({value:w.id,name:w.name??w.id})):c.map(w=>({value:w.modelId,name:w.name??w.modelId})),f=o.name,u=typeof f=="string"&&f.trim()?f.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(w=>w.id===a);if(h>=0){let w={...this.agentAdvertisedConfigOptions[h]};w.options=l,typeof p=="string"&&p.trim()&&(w.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=w}else this.agentAdvertisedConfigOptions.push({id:a,name:u,category:"other",type:"select",currentValue:m,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(sS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(rS(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),iS(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(n){this.modelChangeInFlight=!0;try{if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...n,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let c=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=n!==void 0;if(Aa.some(f=>f.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(o):this.runCompactCommand(o);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${i}`);throw f.code=z.InternalError,f}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=Aa.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:u}of this.extensionCommands.list())f.has(u)||(d.push(u),f.add(u))}let l=new Error(`unknown /hydra verb: ${i} (known: ${d.join(", ")})`);throw l.code=z.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(m=>m.verb===o)){let m=r.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(m=>{d=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>d({stopReason:"cancelled",reason:m})});let f,u=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return u=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=h}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!u&&this.inFlightExtensionDispatches.delete(s)}let p=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
28
+ `},_meta:{"hydra-acp":{synthetic:!0}}}});for(let v of this.clients.values())v.connection.notify("session/update",b).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,i=this.cwd,o=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=await s(e.previousUpstreamSessionId,{agentId:r,cwd:i,agentArgs:o,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(l.agent),await oi({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await ii({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=wS){if(!this.historyStore)return!1;let n=await this.historyStore.load(this.sessionId),s=n.length>e?n.slice(-e):n,r=new Set,i=new Set;for(let o of s){let c=o.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let d=c.sessionUpdate,l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l){if(d==="tool_call")r.add(l);else if(d==="tool_call_update"){let u=c.status;(u==="completed"||u==="failed")&&i.add(l)}}}for(let o of r)if(!i.has(o))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let n=this.broadcastHandlers.indexOf(e);n>=0&&this.broadcastHandlers.splice(n,1)}}broadcastClientUpdate(e){let n=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",n).catch(()=>{})}broadcastCompactionPhase(e){let n=e.phase;n==="swapped"||n==="failed"||n==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{})}attach(e,n,s={}){if(this.closed)throw $t(new Error("session is closed"),W.SessionNotFound);if(this.clients.has(e.clientId))throw $t(new Error(`client ${e.clientId} is already attached`),W.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),n==="none"?Promise.resolve({entries:[],appliedPolicy:n}):n==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:n}):this.loadReplay(n,s)}async loadReplay(e,n){let s=a=>n.raw?a:Up(a),i=(await this.getHistorySnapshot(n.toolContent??"inline")).filter(a=>!Qp(a.method,a.params)),o=this.buildStateSnapshotReplay();if(e==="after_message"){let a=n.afterMessageId?al(i,n.afterMessageId):-1;return a<0?{entries:[...o,...s(i)],appliedPolicy:"full"}:{entries:[...o,...s(i.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...o,...s(i)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],n=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:n,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:n,update:o},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:n,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let n of this.attentionFlags.values()){if(n.source!=="daemon"||!n.reason.startsWith("permission:"))continue;let s=n.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let n=this.clients.get(e);n&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(n))}broadcastClientDisconnected(e){let n={clientId:e.clientId};e.clientInfo?.name&&(n.name=e.clientInfo.name),e.clientInfo?.version&&(n.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:n,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,n){let s=this.clients.get(e);if(!s)throw $t(new Error("client not attached"),W.SessionNotFound);if(this.closing)throw $t(new Error("session is closing; new prompts cannot be accepted"),W.SessionClosing);let r=mr();if(this.maybeSeedTitleFromPrompt(n),this._firstPromptSeeded=!0,!(qt((n??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,n,r)}broadcastPromptReceived(e){let n={clientId:e.originator.clientId};e.originator.name&&(n.name=e.originator.name),e.originator.version&&(n.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:n}},e.clientId);let s=li(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let n={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(n.used=e.used),typeof e.size=="number"&&(n.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),n.cost=r}if(Object.keys(n).length<=1)return;let s={sessionId:this.sessionId,update:n};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,n,s,r){let i=n&&typeof n=="object"&&"stopReason"in n&&typeof n.stopReason=="string"?n.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:mr()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,n){for(this.recentlyTerminal.set(e,{stopReason:n,terminatedAt:Date.now()});this.recentlyTerminal.size>vS;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let n=this.findUserEntry(e.newMessageId);if(!n)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:n.prompt,originator:n.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let n=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return n?.kind==="user"?n:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let n of this.promptQueue)n.kind==="user"&&!n.cancelled&&(e+=1);return e}broadcastQueueAdded(e,n){let s=this.visibleQueueDepth(),r=n?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};n?.amending!==void 0&&(i._meta={"hydra-acp":{amending:n.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:n})}broadcastQueueRemoved(e,n){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:n})}broadcastQueueNotification(e,n){for(let s of this.clients.values())s.connection.notify(e,n).catch(()=>{})}queueSnapshot(){let e=[],n=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:n++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:n++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let n of e){let s={clientId:`hydra-resurrected_${n.messageId}`};n.originator.clientInfo.name!==void 0&&(s.name=n.originator.clientInfo.name),n.originator.clientInfo.version!==void 0&&(s.version=n.originator.clientInfo.version);let r={kind:"user",messageId:n.messageId,originator:s,clientId:s.clientId,prompt:n.prompt,enqueuedAt:n.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let n=this.promptQueue.findIndex(r=>r.messageId===e);if(n<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[n];return s.cancelled=!0,this.promptQueue.splice(n,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,n){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=n,this.broadcastQueueUpdated(e,n),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,n){let s=this.clients.get(e);if(!s)throw $t(new Error("client not attached"),W.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=n;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let c=this.promptQueue.find(l=>l.messageId===r&&l.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=i,this.broadcastQueueUpdated(r,i),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let d=this.recentlyTerminal.get(r);return d?d.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,n,s,r){let i=mr(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let c=[];for(let d of this.promptQueue){if(d.kind==="user"&&!d.cancelled){d.cancelled=!0,this.broadcastQueueRemoved(d.messageId,"cancelled"),d.resolve({stopReason:"cancelled"});continue}c.push(d)}this.promptQueue=c}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,n){let s=mr(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:n,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw $t(new Error("client not attached"),W.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let n=this.transformChain.findIndex(s=>s.name===e.name);n>=0?this.transformChain[n]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,n,s=new Set,r=0,i="request"){let o=this.rewriteForAgent(n);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let d=`request:${e}`;if(!c.intercepts.has(d))continue;let l=`t_${Yp()}`,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??ol(e);if(f==="continue"){u?.payload&&typeof u.payload=="object"&&(o=u.payload),s.add(c.name);continue}if(f==="processing"){let p=a,m=o,h=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,m,new Set([...h,c.name]),p+1,i).then(y).catch(()=>y(i==="notification"?void 0:ol(e))))},il);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(l,{resolve:y,timer:b,transformerName:c.name,method:e,envelope:m,chainIdx:p,originatedBy:h,side:"request",tailKind:i})})}s.add(c.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,o)}dischargeClaim(e,n){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(n),!0):!1}keepAliveClaim(e,n){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof n=="number"&&n>0?Math.min(n*1.5,1800*1e3):il,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:ol(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,n,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(n==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(n,s,o,i)}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.sessionId)return{...n,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let n of this.pendingClaims.values())clearTimeout(n.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let n=this.closeHandlers.indexOf(e);n>=0&&this.closeHandlers.splice(n,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let n=e.trim();if(!(!n||n===this.title)){this.title=n,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:n,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(n)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=li((e??{}).prompt),r=dl(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=ui(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=ui(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(d)}`),this.applyModelChange(d))}}else if(o.id==="mode"){let a=bo(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=o.currentValue;if(typeof c=="string"){let d=c.trim();d&&d!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(d)}`),this.applyModeChange(d))}}else if(typeof o.id=="string"&&o.id.trim()){let a=o.id.trim(),c=ui(o.options);if(c.length>0){let d=bo(o.options),l=d.length>0?d.map(y=>({value:y.id,name:y.name??y.id})):c.map(y=>({value:y.modelId,name:y.name??y.modelId})),u=o.name,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",h=this.agentAdvertisedConfigOptions.findIndex(y=>y.id===a);if(h>=0){let y={...this.agentAdvertisedConfigOptions[h]};y.options=l,typeof p=="string"&&p.trim()&&(y.currentValue=p.trim()),this.agentAdvertisedConfigOptions[h]=y}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:m,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let n={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=n;for(let r of this.usageHandlers)try{r(n)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let i={};typeof s.costAmount=="number"&&(i.amount=s.costAmount),typeof s.costCurrency=="string"&&(i.currency=s.costCurrency),r.cost=i}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...n,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(kS(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let n of this.agentCommandsHandlers)try{n(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(IS(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let n of this.agentModesHandlers)try{n(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(n=>n.modelId).join(",")}]`),xS(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let n of this.agentModelsHandlers)try{n(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let n=e===void 0||e<=0?void 0:Math.floor(e);if(n!==this._priority){this._priority=n,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(n)}catch{}}}applyModelChange(e){let n=e.trim();if(n){this.modelChangeInFlight=!0;try{if(n!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(n)}`),this.currentModel=n;for(let r of this.modelHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:n};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let n=e.trim();if(n){this.modeChangeInFlight=!0;try{if(n!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(n)}`),this.currentMode=n;for(let r of this.modeHandlers)try{r(n)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:n};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let n=e;if(!n.update||typeof n.update!="object")return e;let s=n.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...n,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:n,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${n} ${s.verb}`:`hydra ${n}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),n.startsWith("hydra-acp-")){let a=n.slice(10);if(a.length>0){let c=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,l={name:s.argsHint?`${c} ${s.argsHint}`:c};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,n){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=n!==void 0;if(Da.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=W.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,n):this.runExtensionCommand(i,o);let c=`hydra-acp-${i}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,o,n):this.runExtensionCommand(c,o);let d=Da.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=W.InvalidParams,l}runExtensionCommand(e,n){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,n,void 0))}async runExtensionCommandInline(e,n,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=n.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(m=>m.verb===o)){let m=r.commands.map(h=>h.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(c.messageId=s);let d=()=>{},l=new Promise(m=>{d=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>d({stopReason:"cancelled",reason:m})});let u,f=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),h=await Promise.race([m,l]);if(h&&typeof h=="object"&&h.stopReason==="cancelled"&&"reason"in h)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=h}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,n){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:n})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(n),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
29
29
  ${e}
30
30
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let n=await this.listSessions();if(n.length===0)e="_(no sessions)_";else{let s=n.map(r=>{let i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",c=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${c}`});e=`Sessions (${n.length}):
31
31
  ${s.join(`
@@ -35,39 +35,39 @@ ${e}
35
35
  ${n.join(`
36
36
  `)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
37
37
  ${s}
38
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let n=e.slice(6).trim();if(n===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let c=o?i.some(l=>l.modelId===o):!0,d=i.map(l=>{let f=l.modelId===o?"\u25B6 ":" ",u=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${f}${l.modelId}${u}`});!c&&o&&d.unshift(`\u25B6 ${o}`),a=d.join(`
38
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let n=e.slice(6).trim();if(n===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let c=o?i.some(l=>l.modelId===o):!0,d=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!c&&o&&d.unshift(`\u25B6 ${o}`),a=d.join(`
39
39
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
40
40
  ${a}
41
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Qr(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(f=>f.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(f=>f.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${n}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${n}" is not an available model. Did you mean`:`"${n}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
41
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=di(n,this.agentAdvertisedModels),r=n;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=n.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),c=a.length>0?a:i,d=s.kind==="ambiguous"?`"${n}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${n}" is not an available model. Did you mean`:`"${n}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
42
42
  ${d}.
43
43
  ${l}:
44
44
  ${c.join(`
45
45
  `)}
46
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(d=>d.id===i):!0,c=r.map(d=>{let l=d.id===i?"\u25B6 ":" ",f=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${f}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
46
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let n=e.slice(5).trim();if(n===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(d=>d.id===i):!0,c=r.map(d=>{let l=d.id===i?"\u25B6 ":" ",u=d.name&&d.name!==d.id?` ${d.name}`:"";return`${l}${d.id}${u}`});!a&&i&&c.unshift(`\u25B6 ${i}`),o=c.join(`
47
47
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
48
48
  ${o}
49
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw Mt(new Error(`unknown mode: ${n} (known: ${r})`),z.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
49
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===n)){let r=s.map(i=>i.id).join(", ");throw $t(new Error(`unknown mode: ${n} (known: ${r})`),W.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:n}),this.applyModeChange(n),{stopReason:"end_turn"}}async handleConfigCommand(e){let n=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=n?.[1],r=n?.[2]??"";if(!s){let l=this.buildConfigOptions();if(l.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
50
50
  _(no config options advertised yet)_
51
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=l.map(u=>Np(u));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
52
- ${f.join(`
51
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let u=l.map(f=>Gp(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
52
+ ${u.join(`
53
53
 
54
54
  `)}
55
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(l=>l.id===s);if(!o){let l=i.map(f=>f.id).join(`
55
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(l=>l.id===s);if(!o){let l=i.map(u=>u.id).join(`
56
56
  `);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
57
  "${s}" is not a known config option.
58
58
  Available options:
59
59
  ${l}
60
60
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
61
- ${Np(o)}
62
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=jc(r,a),d=r;if(c.kind==="resolved")d=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let l=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(h=>h.toLowerCase().includes(l)),u=f.length>0?f:a,p=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
61
+ ${Gp(o)}
62
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),c=Zc(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(h=>h.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}"`,m=c.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
63
63
  ${p}.
64
64
  ${m}:
65
- ${u.join(`
65
+ ${f.join(`
66
66
  `)}
67
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[]};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(!e)throw Mt(new Error("/hydra agent requires an agent id"),z.InvalidParams);if(e===this.agentId)throw Mt(new Error(`already on agent ${e}`),z.InvalidParams);if(!this.spawnReplacementAgent)throw Mt(new Error("agent switching not configured for this session"),z.InternalError);let n=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await n({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let c of this.agentChangeHandlers)try{c(a)}catch{}return{stopReason:"end_turn"}}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw Mt(new Error("agent restart not configured for this session"),z.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),n=this._summarizedThroughEntry;if(e==null&&n==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${n}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${n??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
68
- `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw Mt(new Error("session is closing"),z.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let f=(d.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let p=f.sessionUpdate;if(p==="prompt_received"){let m=ei(f.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let h=f.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let m=f.status,h=f.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${m}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=n?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
69
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new Ca(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??Gr,Gr)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=z.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let r of n){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Fp(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>jp.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Bp(e,r),o=i?cS(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let n=[...this.clients.values()];if(n.length===0)throw Mt(new Error("no clients attached to handle permission request"),z.PermissionDenied);let s=this.rewriteForClient(e),r=lS(s);return new Promise((i,o)=>{let a=!1,c=[],d=0,l,f={addClient:h};this.inFlightPermissions.add(f);let u=this.sessionId,p=w=>{a||(a=!0,this.inFlightPermissions.delete(f),w())},m=w=>w?.code===z.MethodNotFound;function h(w){if(a)return;let b=w.connection.request("session/request_permission",s);c.push({client:w}),d++,b.then(v=>{d--,p(()=>{let S=uS({toolCallId:r,result:v,resolver:w});for(let x of c)x.client.clientId!==w.clientId&&x.client.connection.notify("session/update",{sessionId:u,update:S}).catch(()=>{});i(v)})}).catch(v=>{if(d--,m(v)||(l=v),d===0&&!a){let S=l??Mt(new Error("no client handled permission request"),z.PermissionDenied);p(()=>o(S))}})}for(let w of n)h(w)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:Zr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ao(n,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=ei(e.prompt).replace(/\s+$/,""),s=!n.includes(`
70
- `)&&n.startsWith("/")?n.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(n):s==="/model"?i=await this.handleModelCommand(n):i=await this.handleSlashCommand(n,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};nS=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"])});import{z as Te}from"zod";function zp(t){let e=t.trim();if(e.length===0)return;let n=si(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=si(e.slice(i,o+1)))}if(n===void 0){let i=Kp(e);i!==void 0&&(n=si(i))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Wp))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=lo.safeParse(s.synopsis);i.success&&mS(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Jp(t){let e=t.trim();if(e.length===0)return;let n=si(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=si(e.slice(d,l+1)))}if(n===void 0){let d=Kp(e);d!==void 0&&(n=si(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,Wp))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],f=Te.array(Te.string()).safeParse(l);f.success&&l.length>0&&(i[d]=f.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function si(t){try{return JSON.parse(t)}catch{return}}function Kp(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function mS(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var qp,lo,Wp,Xc,Zc,Ea=K(()=>{"use strict";qp=Te.object({status:Te.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:Te.number(),iter:Te.number().int().nonnegative().optional(),attempts:Te.number().int().nonnegative().optional(),lastError:Te.string().optional(),worker:Te.object({upstreamSessionId:Te.string(),pid:Te.number().int().nonnegative()}).optional()}),lo=Te.object({goal:Te.string().optional(),outcome:Te.string().optional(),files_touched:Te.array(Te.string()).optional(),tools_used:Te.array(Te.string()).optional(),rejected_approaches:Te.array(Te.string()).optional(),open_threads:Te.array(Te.string()).optional(),decisions:Te.array(Te.string()).optional(),file_edit_intentions:Te.array(Te.string()).optional(),unresolved_errors:Te.array(Te.string()).optional(),tool_state:Te.array(Te.string()).optional()}),Wp=200,Xc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
67
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(d!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:d}),this.applyModelChange(d),{stopReason:"end_turn"}):s==="mode"?(d!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:d}),this.applyModeChange(d),{stopReason:"end_turn"}):s==="agent"?(d!==this.agentId&&await this.runAgentCommandInline(d),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:d}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let n={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=n;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),n.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(!e)throw $t(new Error("/hydra agent requires an agent id"),W.InvalidParams);if(e===this.agentId)throw $t(new Error(`already on agent ${e}`),W.InvalidParams);if(!this.spawnReplacementAgent)throw $t(new Error("agent switching not configured for this session"),W.InternalError);let n=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await n({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let c of this.agentChangeHandlers)try{c(a)}catch{}return{stopReason:"end_turn"}}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw $t(new Error("agent restart not configured for this session"),W.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),n=this._summarizedThroughEntry;if(e==null&&n==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${n}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${n??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
68
+ `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw $t(new Error("session is closing"),W.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,n=this.agentId,s=await this.buildSwitchTranscript(n),r=await e({agentId:n,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(n,n);let o={agentId:n,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,n){let s=[],r=await this.getHistorySnapshot();for(let d of r){if(d.method!=="session/update")continue;let u=(d.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let m=li(u.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let h=u.content?.text;h&&s.push({speaker:`agent: ${e}`,text:h})}else if(p==="tool_call"||p==="tool_call_update"){let m=u.status,h=u.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${h??"?"} ${m}`})}}if(s.length===0)return"";let i=[],o;for(let d of s)o&&o.speaker===d.speaker?o.text+=d.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:d.speaker,text:d.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=n?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,c=n?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
69
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,n){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:n}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new Na(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,n){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return n===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,n,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(n??ai,ai)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(o.nextCursor,s);(c==="data"||c==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,n){return this.requireStreamBuffer().waitForData(e,n)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=W.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let n=this.promptQueue;this.promptQueue=[];for(let r of n){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Vp(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>tm.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,n,s){this._setAttentionFlag(e,n,s,!0)}_setAttentionFlag(e,n,s,r){let i=`${e}::${n}`,o=this.attentionFlags.get(i);if(o){if(JSON.stringify(o.payload)===JSON.stringify(s))return;this.attentionFlags.set(i,{...o,payload:s,raisedAt:o.raisedAt})}else this.attentionFlags.set(i,{source:e,reason:n,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,n){this._clearAttentionFlag(e,n,!0)}_clearAttentionFlag(e,n,s){let r=`${e}::${n}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,n)=>e.raisedAt-n.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(n=>n.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let n of this.attentionFlagsChangeHandlers)try{n(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let n=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(n).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,n){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:n}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.sessionId===this.upstreamSessionId)return{...n,sessionId:this.sessionId}}return e}recordAndBroadcast(e,n,s){let r=this.rewriteForClient(n),i=!Qp(e,r),o=i?TS(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let n=[...this.clients.values()];if(n.length===0)throw $t(new Error("no clients attached to handle permission request"),W.PermissionDenied);let s=this.rewriteForClient(e),r=ES(s),i=mr(),{toolCall:o,options:a}=s??{};return new Promise((c,d)=>{let l=!1,u=[],f=0,p,m=this.sessionId,h=v=>{l||(l=!0,this.clearAttentionFlag("daemon",`permission:${i}`),this.permissionCallbacks.delete(i),v())},y=v=>v?.code===W.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--,h(()=>{let T=PS({toolCallId:r,result:x,resolver:v});for(let _ of u)_.client.clientId!==v.clientId&&_.client.connection.notify("session/update",{sessionId:m,update:T}).catch(()=>{});c(x)})}).catch(x=>{if(f--,y(x)||(p=x),f===0&&!l){let T=p??$t(new Error("no client handled permission request"),W.PermissionDenied);h(()=>d(T))}})}this.setAttentionFlag("daemon",`permission:${i}`,{kind:"permission",toolCall:o??null,options:a??null}),this.permissionCallbacks.set(i,b);for(let v of n)b(v)})}async enqueuePrompt(e){return new Promise((n,s)=>{let r={kind:"internal",messageId:mr(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:n,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,n,s){let r=(n??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(n);return new Promise((a,c)=>{let d={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},l=this.insertEntryAt(d,o);this.persistRewrite(),this.broadcastQueueAdded(d,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let n=e._meta;if(!n||typeof n!="object"||Array.isArray(n))return"tail";let s=n["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,n){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(n==="head")return this.promptQueue.unshift(e),s;if(typeof n=="object"){let r=n.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let n=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>wo(n,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let n=await this.runQueueEntry(e);e.resolve(n),await new Promise(s=>setImmediate(s))}catch(n){e.reject(n)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let n=li(e.prompt).replace(/\s+$/,""),s=!n.includes(`
70
+ `)&&n.startsWith("/")?n.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(n):s==="/model"?i=await this.handleModelCommand(n):i=await this.handleSlashCommand(n,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let r;try{r=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt})}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};SS=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 pi}from"zod";var $S,nm,sm=K(()=>{"use strict";$S=pi.object({source:pi.string(),reason:pi.string(),raisedAt:pi.number(),payload:pi.unknown()}),nm=pi.array($S)});import{z as $e}from"zod";function om(t){let e=t.trim();if(e.length===0)return;let n=mi(e);if(n===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");i>=0&&o>i&&(n=mi(e.slice(i,o+1)))}if(n===void 0){let i=dm(e);i!==void 0&&(n=mi(i))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,im))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=vo.safeParse(s.synopsis);i.success&&FS(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function am(t){let e=t.trim();if(e.length===0)return;let n=mi(e);if(n===void 0){let d=e.indexOf("{"),l=e.lastIndexOf("}");d>=0&&l>d&&(n=mi(e.slice(d,l+1)))}if(n===void 0){let d=dm(e);d!==void 0&&(n=mi(d))}if(n===void 0||n===null||typeof n!="object")return;let s=n,r={};if(typeof s.title=="string"){let d=s.title.trim();d.length>0&&(r.title=d.slice(0,im))}let i={},o=!1,a=["goal","outcome"];for(let d of a)if(typeof s[d]=="string"){let l=s[d].trim();l.length>0&&(i[d]=l,o=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let d of c)if(Array.isArray(s[d])){let l=s[d],u=$e.array($e.string()).safeParse(l);u.success&&l.length>0&&(i[d]=u.data,o=!0)}if(o&&(r.synopsis=i),!(r.title===void 0&&r.synopsis===void 0))return r}function mi(t){try{return JSON.parse(t)}catch{return}}function dm(t){let e=t.indexOf("{");if(e<0)return;let n=0,s=!1,r=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){r?r=!1:o==="\\"?r=!0:o==='"'&&(s=!1);continue}if(o==='"'){s=!0;continue}if(o==="{")n++;else if(o==="}"&&(n--,n===0))return t.slice(e,i+1)}}function FS(t){return t.goal!==void 0&&t.goal.trim().length>0||t.outcome!==void 0&&t.outcome.trim().length>0||t.files_touched!==void 0&&t.files_touched.length>0||t.tools_used!==void 0&&t.tools_used.length>0||t.rejected_approaches!==void 0&&t.rejected_approaches.length>0||t.open_threads!==void 0&&t.open_threads.length>0||t.decisions!==void 0&&t.decisions.length>0||t.file_edit_intentions!==void 0&&t.file_edit_intentions.length>0||t.unresolved_errors!==void 0&&t.unresolved_errors.length>0||t.tool_state!==void 0&&t.tool_state.length>0}var rm,vo,im,cl,ll,ja=K(()=>{"use strict";rm=$e.object({status:$e.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:$e.number(),iter:$e.number().int().nonnegative().optional(),attempts:$e.number().int().nonnegative().optional(),lastError:$e.string().optional(),worker:$e.object({upstreamSessionId:$e.string(),pid:$e.number().int().nonnegative()}).optional()}),vo=$e.object({goal:$e.string().optional(),outcome:$e.string().optional(),files_touched:$e.array($e.string()).optional(),tools_used:$e.array($e.string()).optional(),rejected_approaches:$e.array($e.string()).optional(),open_threads:$e.array($e.string()).optional(),decisions:$e.array($e.string()).optional(),file_edit_intentions:$e.array($e.string()).optional(),unresolved_errors:$e.array($e.string()).optional(),tool_state:$e.array($e.string()).optional()}),im=200,cl=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
71
71
  {
72
72
  "title": "short summary, max 80 chars",
73
73
  "synopsis": {
@@ -77,7 +77,7 @@ ${m}:
77
77
  "open_threads": ["work started but not finished"]
78
78
  }
79
79
  }
80
- Use empty arrays/strings where a field doesn't apply.`;Zc=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
80
+ Use empty arrays/strings where a field doesn't apply.`;ll=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
81
81
  {
82
82
  "title": "short summary, max 80 chars",
83
83
  "goal": "the user's original ask",
@@ -89,251 +89,251 @@ Use empty arrays/strings where a field doesn't apply.`;Zc=`Reply with ONLY a JSO
89
89
  "unresolved_errors": ["errors left open at session end"],
90
90
  "tool_state": ["runtime state relevant for recall"]
91
91
  }
92
- Use empty arrays/strings where a field doesn't apply.`});import*as ri from"fs/promises";import*as $E from"path";import{customAlphabet as hS}from"nanoid";import{z as te}from"zod";function uo(){return`${wS}${yS()}`}function kS(t){if(!el.test(t))throw new Error(`unsafe session id: ${t}`)}function il(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var gS,yS,wS,tl,nl,bS,sl,rl,vS,SS,el,Pa,ol=K(()=>{"use strict";pe();Qs();Ea();gS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",yS=hS(gS,16),wS="hydra_lineage_";tl=te.object({name:te.string(),description:te.string().optional()}),nl=te.object({id:te.string(),name:te.string().optional(),description:te.string().optional()}),bS=te.object({modelId:te.string(),name:te.string().optional(),description:te.string().optional()}),sl=te.object({used:te.number().optional(),size:te.number().optional(),costAmount:te.number().optional(),costCurrency:te.string().optional(),cumulativeCost:te.number().optional()}),rl=te.object({name:te.string(),version:te.string().optional()}),vS=te.object({previousUpstreamSessionId:te.string(),previousSummarizedThroughEntry:te.number().int().nonnegative().optional()}),SS=te.object({version:te.literal(1),sessionId:te.string(),lineageId:te.string().optional(),upstreamSessionId:te.string(),importedFromSessionId:te.string().optional(),importedFromUpstreamSessionId:te.string().optional(),importedFromMachine:te.string().optional(),agentId:te.string(),cwd:te.string(),title:te.string().optional(),synopsis:lo.optional(),compactionState:qp.optional(),rollbackBreadcrumb:vS.optional(),summarizedThroughEntry:te.number().int().nonnegative().optional(),agentArgs:te.array(te.string()).optional(),currentModel:te.string().optional(),currentMode:te.string().optional(),currentUsage:sl.optional(),agentCommands:te.array(tl).optional(),agentModes:te.array(nl).optional(),agentModels:te.array(bS).optional(),pendingHistorySync:te.boolean().optional(),parentSessionId:te.string().optional(),forkedFromSessionId:te.string().optional(),forkedFromMessageId:te.string().optional(),originatingClient:rl.optional(),interactive:te.boolean().optional(),priority:te.number().int().nonnegative().optional(),forwardedEnv:te.record(te.string(),te.string()).optional(),createdAt:te.string(),updatedAt:te.string()}),el=/^[A-Za-z0-9_-]+$/;Pa=class{async write(e){kS(e.sessionId);let n={version:1,...e};await Ft(_.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!el.test(e))return;let n=await zt(_.sessionFile(e));if(n!==void 0)try{return SS.parse(n)}catch{return}}async delete(e){if(el.test(e)){try{await ri.unlink(_.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await ri.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await ri.readdir(_.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as xS}from"url";import*as fo from"path";import*as _a from"fs";function CS(){try{let t=fo.dirname(xS(import.meta.url));for(let e=0;e<8;e+=1){let n=fo.join(t,"package.json");if(_a.existsSync(n)){let r=JSON.parse(_a.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=fo.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var fe,rr,Nt=K(()=>{"use strict";fe=CS(),rr="hydra-acp-cat"});function al(t){let e=new Map;for(let n of rm(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function tm(t){return al(t).map(e=>e.name)}function dl(t){let e=new Map;for(let n of rm(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function nm(t){return dl(t).map(e=>e.path)}function sm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function rm(t){let e=new Map,n=0;for(let s of t){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:Zp(i),paths:new Set},e.set(c,d)):d.toolName=Zp(i);for(let l of em(i.rawInput,i.locations))d.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let c of em(i.rawInput,i.locations))a.paths.add(c)}return e}function Zp(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function em(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var cl=K(()=>{"use strict"});import{promises as mo}from"fs";import*as hl from"path";async function ho(t){let e;try{e=await mo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return FS(e)}function FS(t){let e=[];for(let n of t.split(`
93
- `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function go(t,e,n=hm){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function ir(t,e){await mo.mkdir(hl.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await mo.writeFile(t,n.length>0?n.join(`
92
+ Use empty arrays/strings where a field doesn't apply.`});import*as hi from"fs/promises";import*as uP from"path";import{customAlphabet as OS}from"nanoid";import{z as ne}from"zod";function So(){return`${NS}${BS()}`}function jS(t){if(!ul.test(t))throw new Error(`unsafe session id: ${t}`)}function gl(t){let e=new Date().toISOString();return{sessionId:t.sessionId,lineageId:t.lineageId,upstreamSessionId:t.upstreamSessionId,importedFromSessionId:t.importedFromSessionId,importedFromUpstreamSessionId:t.importedFromUpstreamSessionId,importedFromMachine:t.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,compactionState:t.compactionState,rollbackBreadcrumb:t.rollbackBreadcrumb,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:t.currentUsage,agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,pendingHistorySync:t.pendingHistorySync,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forwardedEnv:t.forwardedEnv,attentionFlags:t.attentionFlags??[],createdAt:t.createdAt??e,updatedAt:t.updatedAt??e}}var LS,BS,NS,fl,pl,DS,ml,hl,HS,US,ul,qa,yl=K(()=>{"use strict";he();ar();sm();ja();LS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",BS=OS(LS,16),NS="hydra_lineage_";fl=ne.object({name:ne.string(),description:ne.string().optional()}),pl=ne.object({id:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),DS=ne.object({modelId:ne.string(),name:ne.string().optional(),description:ne.string().optional()}),ml=ne.object({used:ne.number().optional(),size:ne.number().optional(),costAmount:ne.number().optional(),costCurrency:ne.string().optional(),cumulativeCost:ne.number().optional()}),hl=ne.object({name:ne.string(),version:ne.string().optional()}),HS=ne.object({previousUpstreamSessionId:ne.string(),previousSummarizedThroughEntry:ne.number().int().nonnegative().optional()}),US=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:vo.optional(),compactionState:rm.optional(),rollbackBreadcrumb:HS.optional(),summarizedThroughEntry:ne.number().int().nonnegative().optional(),agentArgs:ne.array(ne.string()).optional(),currentModel:ne.string().optional(),currentMode:ne.string().optional(),currentUsage:ml.optional(),agentCommands:ne.array(fl).optional(),agentModes:ne.array(pl).optional(),agentModels:ne.array(DS).optional(),pendingHistorySync:ne.boolean().optional(),parentSessionId:ne.string().optional(),forkedFromSessionId:ne.string().optional(),forkedFromMessageId:ne.string().optional(),originatingClient:hl.optional(),interactive:ne.boolean().optional(),priority:ne.number().int().nonnegative().optional(),forwardedEnv:ne.record(ne.string(),ne.string()).optional(),attentionFlags:nm.default([]).optional(),createdAt:ne.string(),updatedAt:ne.string()}),ul=/^[A-Za-z0-9_-]+$/;qa=class{async write(e){jS(e.sessionId);let n={version:1,...e};await Ut($.sessionFile(e.sessionId),n,{mode:384})}async read(e){if(!ul.test(e))return;let n=await Xt($.sessionFile(e));if(n!==void 0)try{return US.parse(n)}catch{return}}async delete(e){if(ul.test(e)){try{await hi.unlink($.sessionFile(e))}catch(n){if(n.code!=="ENOENT")throw n}try{await hi.rmdir($.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}}}async findByLineageId(e){if(e.length===0)return;let n=await this.list().catch(()=>[]);for(let s of n)if(s.lineageId===e)return s}async list(){let e;try{e=await hi.readdir($.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let n=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of n)r&&s.push(r);return s}}});import{fileURLToPath as WS}from"url";import*as ko from"path";import*as za from"fs";function zS(){try{let t=ko.dirname(WS(import.meta.url));for(let e=0;e<8;e+=1){let n=ko.join(t,"package.json");if(za.existsSync(n)){let r=JSON.parse(za.readFileSync(n,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=ko.dirname(t);if(s===t)break;t=s}}catch{}return"0.0.0"}var pe,hr,Wt=K(()=>{"use strict";pe=zS(),hr="hydra-acp-cat"});function wl(t){let e=new Map;for(let n of bm(t).values())e.set(n.toolName,(e.get(n.toolName)??0)+1);return[...e.entries()].map(([n,s])=>({name:n,count:s})).sort((n,s)=>s.count-n.count||n.name.localeCompare(s.name))}function gm(t){return wl(t).map(e=>e.name)}function bl(t){let e=new Map;for(let n of bm(t).values())for(let s of n.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(n.toolName,(r.get(n.toolName)??0)+1)}return[...e.entries()].map(([n,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:n,count:i,byTool:r}}).sort((n,s)=>s.count-n.count||n.path.localeCompare(s.path))}function ym(t){return bl(t).map(e=>e.path)}function wm(t){let e=0;for(let n of t)n.params?.update?.sessionUpdate==="prompt_received"&&(e+=1);return e}function bm(t){let e=new Map,n=0;for(let s of t){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${n++}`,d=e.get(c);d===void 0?(d={toolName:mm(i),paths:new Set},e.set(c,d)):d.toolName=mm(i);for(let l of hm(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 hm(i.rawInput,i.locations))a.paths.add(c)}return e}function mm(t){return typeof t.name=="string"&&t.name.length>0?t.name:typeof t.title=="string"&&t.title.length>0?t.title:"(unnamed)"}function hm(t,e){let n=new Set;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t;typeof s.file_path=="string"?n.add(s.file_path):typeof s.path=="string"&&n.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&n.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&n.add(r)}}return n}var vl=K(()=>{"use strict"});import{promises as xo}from"fs";import*as Al from"path";async function Co(t){let e;try{e=await xo.readFile(t,"utf8")}catch(n){if(n.code==="ENOENT")return[];throw n}return tk(e)}function tk(t){let e=[];for(let n of t.split(`
93
+ `))if(n.length!==0)try{let s=JSON.parse(n);typeof s=="string"&&e.push(s)}catch{}return e}function Ao(t,e,n=Pm){let s=e.replace(/\n+$/,"");if(s.length===0||t.length>0&&t[t.length-1]===s)return t;let r=t.concat(s);return r.length>n?r.slice(r.length-n):r}async function gr(t,e){await xo.mkdir(Al.dirname(t),{recursive:!0});let n=e.map(s=>JSON.stringify(s));await xo.writeFile(t,n.length>0?n.join(`
94
94
  `)+`
95
- `:"")}async function gm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await mo.mkdir(hl.dirname(t),{recursive:!0}),await mo.appendFile(t,JSON.stringify(n)+`
96
- `,{encoding:"utf8"}))}function Fa(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function gl(t,e,n=hm){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=go(r,o,n)))}return r}var hm,La=K(()=>{"use strict";hm=500});import{z as xe}from"zod";function yo(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function ln(t){return NS.parse(t)}var LS,BS,NS,or=K(()=>{"use strict";ol();Ea();LS=xe.object({method:xe.string(),params:xe.unknown(),recordedAt:xe.number()}),BS=xe.object({sessionId:xe.string(),lineageId:xe.string(),upstreamSessionId:xe.string().optional(),agentId:xe.string(),cwd:xe.string(),title:xe.string().optional(),synopsis:lo.optional(),summarizedThroughEntry:xe.number().int().nonnegative().optional(),currentModel:xe.string().optional(),currentMode:xe.string().optional(),currentUsage:sl.optional(),agentCommands:xe.array(tl).optional(),agentModes:xe.array(nl).optional(),interactive:xe.boolean().optional(),originatingClient:rl.optional(),priority:xe.number().int().nonnegative().optional(),createdAt:xe.string(),updatedAt:xe.string()}),NS=xe.object({version:xe.literal(1),exportedAt:xe.string(),exportedFrom:xe.object({hydraVersion:xe.string(),machine:xe.string(),hydraHost:xe.string().optional()}),session:BS,history:xe.array(LS),promptHistory:xe.array(xe.string()).optional(),toolBlobs:xe.record(xe.string()).optional()})});import{createHash as XS}from"crypto";function Al(t){if(Array.isArray(t))return t.map(Al);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Al(t[n]);return e}return t}function gs(t){let{tui:e,...n}=t,s=JSON.stringify(Al(n));return XS("sha256").update(s).digest("hex").slice(0,16)}var xo=K(()=>{"use strict";Ne()});function Rl(t){return Math.floor(t/4)}function Fm(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=Rl(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function Lm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var Tl=K(()=>{"use strict"});function Co(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Bm=K(()=>{"use strict"});import{posix as lk}from"path";import uk from"strip-ansi";function tt(t){return uk(t).replace(fk,"")}function Ie(t){return tt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Rn(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return wk(n);case"agent_thought_chunk":case"agent_thought":return bk(n);case"user_message_chunk":return vk(n);case"prompt_received":return Sk(n);case"tool_call":return kk(n,e);case"tool_call_update":return Rk(n,e);case"plan":return Pk(n);case"current_mode_update":return Mk(n);case"current_model_update":return _k(n);case"turn_complete":return $k(n);case"usage_update":return yk(n);case"available_commands_update":return hk(n);case"available_modes_update":return gk(n);case"session_info_update":return mk(n);case"config_option_update":return pk(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function pk(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function mk(t){let e=qe(t,"title"),n=e!==void 0?Ie(e):void 0,s=t._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(n===void 0&&r===void 0)return null;let i={kind:"session-info"};return n!==void 0&&(i.title=n),r!==void 0&&(i.agentId=r),i}function Xa(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:Ie(r)};typeof s.description=="string"&&(i.description=Ie(s.description)),e.push(i)}return e}function hk(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:Xa(e)}:null}function gk(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:Ie(r.id)};typeof r.name=="string"&&(i.name=Ie(r.name)),typeof r.description=="string"&&(i.description=Ie(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function yk(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function wk(t){let e=Ao(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Co(t)}}function bk(t){let e=typeof t.text=="string"?tt(t.text):Ao(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Co(t)}}function vk(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=Ao(t.content);return n===null?null:{kind:"user-text",text:n}}function Sk(t){let e=Ok(t.prompt);return e===null?null:{kind:"user-text",text:e}}function Hm(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Nm(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function Za(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Nm(r.oldText),o=Nm(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Um(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:tt(n)}function kk(t,e={}){let n=qe(t,"toolCallId")??qe(t,"id");if(!n)return null;let s=qe(t,"title")??qe(t,"name")??qe(t,"label")??"tool call",r=qe(t,"name")??qe(t,"title");if(Hm(r)){let m=Um(t);if(m!==null){let h=qe(t,"status"),w={kind:"exit-plan-mode",toolCallId:n,plan:m};return h!==void 0&&(w.status=h),w}}let i=Wm(Ie(s),t,e),o=qe(t,"status"),a=qe(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=Za(t);d!==null&&(c.editDiff=d);let l=qm(t);l!==void 0&&(c.detail=l);let f=El(t);f!==void 0&&(c.detailFull=f);let u=jm(t);u!==void 0&&(c.locations=u);let p=Co(t);return p!==void 0&&(c.workerTaskId=p),c}function jm(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function qm(t){let e=El(t);if(e===void 0)return;let n=Ie(e),s=t.rawInput;return s&&typeof s.command=="string"?Ck(n,Dm):Ak(n,Dm)}function El(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return tt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return Ue(Ie(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return Ue(Ie(s))}}}function xk(t){for(let e of Ik)if(t.startsWith(e))return!0;return!1}function Wm(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return Ue(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${t}`||o.endsWith(`/${t}`)||o===t))return Ue(o)}return xk(t)?Ue(`/${t}`):n.cwd&&n.cwd.length>0?Ue(lk.resolve(n.cwd,t)):t}function Ck(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Ak(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function Rk(t,e={}){let n=qe(t,"toolCallId")??qe(t,"id");if(!n)return null;let s=qe(t,"title"),r=s!==void 0?Wm(Ie(s),t,e):void 0,i=qe(t,"status"),o=Za(t),a=qm(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=qe(t,"name")??s;if(Hm(d)){let m={kind:"exit-plan-mode",toolCallId:n},h=Um(t);return h!==null&&(m.plan=h),i!==void 0&&(m.status=i),m}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let f=El(t);f!==void 0&&(l.detailFull=f);let u=jm(t);if(u!==void 0&&(l.locations=u),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let m=Tk(t);m!==null&&(l.errorText=m),Ek(t,m)&&(l.upstreamInterrupted=!0)}let p=Co(t);return p!==void 0&&(l.workerTaskId=p),l}function Tk(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Ao(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return tt(s)}return null}function Ek(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Pk(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?Ie(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),n.push(o)}return{kind:"plan",entries:n}}function Mk(t){let e=qe(t,"currentModeId")??qe(t,"currentMode")??qe(t,"mode");return e?{kind:"mode-changed",mode:Ie(e)}:null}function _k(t){let e=qe(t,"currentModel")??qe(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:Ie(e),...s&&s.length>0?{availableModels:s}:{}}}function $k(t){let e=qe(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Ao(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?tt(e.text):null}function Ok(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Ao(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function qe(t,e){let n=t[e];return typeof n=="string"?n:void 0}var fk,Dm,Ik,ys=K(()=>{"use strict";pe();Bm();fk=/[\x00-\x08\x0b-\x1f\x7f]/g;Dm=64;Ik=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function di(t){let e=new Map,n=new Map;for(let r of t){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=Lk(o);if(d.length===0)continue;let l=d;if(c!==void 0){let f=e.get(c)??[],u=[];for(let p of d)f.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||u.push(p);if(u.length===0)continue;e.set(c,[...f,...u]),l=u}for(let f of l)Fk(n,f)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function ci(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function Fk(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function Lk(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,f=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||f===void 0||e.push({path:o,oldText:l,newText:f})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=Za(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var ed=K(()=>{"use strict";ys()});function Tn(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),t.on("close",()=>r()),t.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var fi=K(()=>{"use strict";It()});import{spawn as ZI}from"child_process";import{setTimeout as ex}from"timers/promises";async function Th(){let t=await zn();if(t&&dn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function tx(t){let e=await cr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===gs(t)?"match":"mismatch":"missing"}async function vs(t){let e=await tx(t);if(e!=="match"){if(e==="mismatch"){let n=vn();throw new Error(`unable to attach to running daemon \u2014 run \`${n} daemon stop\` and try again.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
97
- `),fd(),await pd(t)}}async function ud(t){let e=await Th();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function cr(t,e=1e3){let n=await Th();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function fd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");ZI(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function pd(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await ud(t))return;await ex(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var lr=K(()=>{"use strict";to();xo();qr()});import{WebSocket as ox}from"ws";async function ur(t,e,n=ax){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=so(r.hostname);i.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=i.rejectUnauthorized),i.autoSelectFamily!==void 0&&(s.autoSelectFamily=i.autoSelectFamily),i.checkServerIdentity!==void 0&&(s.checkServerIdentity=i.checkServerIdentity)}}catch{}return new Promise((r,i)=>{let o=new ox(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new Ul(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=f=>{clearTimeout(c),o.off("open",d),i(f)};o.once("open",d),o.once("error",l)})}var ax,Ul,Eo=K(()=>{"use strict";ro();ax=1e4,Ul=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as hd from"fs/promises";function dx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function wi(){let t=await zn();if(t&&dn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await ye();return Lh(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Lh(t,e,n){return`${n?"https":"http"}://${dx(t)}:${e}`}async function Ee(t,e={}){let n=await Gs(),s=await wi(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(f){if(e.rethrowNetworkError)throw f;process.stderr.write(`Could not reach daemon at ${s}: ${f.message}
98
- `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let f=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(f=p)}let u=e.errorPrefix??"Daemon returned";process.stderr.write(`${u} ${f}
99
- `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function bi(t){let e;t instanceof Date?e=t.getTime():typeof t=="string"?e=Date.parse(t):e=t;let n=Math.max(0,Date.now()-e),s=Math.floor(n/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function gd(t,e){let n=e!=="agent",s=n?[]:void 0,r=[],i={},o=!0,a=0;for(;a<t.length;){let c=t[a];if(c==="--command"){let d=t[a+1];d===void 0&&(process.stderr.write(`--command requires a value
100
- `),process.exit(2)),s=n?cx(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
95
+ `:"")}async function Mm(t,e){let n=e.replace(/\n+$/,"");n.length!==0&&(await xo.mkdir(Al.dirname(t),{recursive:!0}),await xo.appendFile(t,JSON.stringify(n)+`
96
+ `,{encoding:"utf8"}))}function Va(t,e){if(e.length===0)return[...t];let n=new Set(e);return[...t.filter(r=>!n.has(r)),...e]}function Rl(t,e,n=Pm){if(e.length===0)return t;let s=new Set(t),r=t;for(let i of e){let o=i.replace(/\n+$/,"");o.length!==0&&(s.has(o)||(s.add(o),r=Ao(r,o,n)))}return r}var Pm,Ya=K(()=>{"use strict";Pm=500});import{z as Re}from"zod";function Ro(t){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:t.hydraVersion,machine:t.machine,...t.hydraHost!==void 0&&t.hydraHost.length>0?{hydraHost:t.hydraHost}:{}},session:{sessionId:t.record.sessionId,lineageId:t.record.lineageId,...t.record.upstreamSessionId?{upstreamSessionId:t.record.upstreamSessionId}:{},agentId:t.record.agentId,cwd:t.record.cwd,...t.record.title!==void 0?{title:t.record.title}:{},...t.record.synopsis!==void 0?{synopsis:t.record.synopsis}:{},...t.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:t.record.summarizedThroughEntry}:{},...t.record.currentModel!==void 0?{currentModel:t.record.currentModel}:{},...t.record.currentMode!==void 0?{currentMode:t.record.currentMode}:{},...t.record.currentUsage!==void 0?{currentUsage:t.record.currentUsage}:{},...t.record.agentCommands!==void 0?{agentCommands:t.record.agentCommands}:{},...t.record.agentModes!==void 0?{agentModes:t.record.agentModes}:{},...t.record.interactive!==void 0?{interactive:t.record.interactive}:{},...t.record.originatingClient!==void 0?{originatingClient:t.record.originatingClient}:{},...t.record.priority!==void 0&&t.record.priority>0?{priority:t.record.priority}:{},createdAt:t.record.createdAt,updatedAt:t.record.updatedAt},history:t.history};return t.promptHistory!==void 0&&(e.promptHistory=t.promptHistory),t.toolBlobs!==void 0&&Object.keys(t.toolBlobs).length>0&&(e.toolBlobs=t.toolBlobs),e}function gn(t){return rk.parse(t)}var nk,sk,rk,yr=K(()=>{"use strict";yl();ja();nk=Re.object({method:Re.string(),params:Re.unknown(),recordedAt:Re.number()}),sk=Re.object({sessionId:Re.string(),lineageId:Re.string(),upstreamSessionId:Re.string().optional(),agentId:Re.string(),cwd:Re.string(),title:Re.string().optional(),synopsis:vo.optional(),summarizedThroughEntry:Re.number().int().nonnegative().optional(),currentModel:Re.string().optional(),currentMode:Re.string().optional(),currentUsage:ml.optional(),agentCommands:Re.array(fl).optional(),agentModes:Re.array(pl).optional(),interactive:Re.boolean().optional(),originatingClient:hl.optional(),priority:Re.number().int().nonnegative().optional(),createdAt:Re.string(),updatedAt:Re.string()}),rk=Re.object({version:Re.literal(1),exportedAt:Re.string(),exportedFrom:Re.object({hydraVersion:Re.string(),machine:Re.string(),hydraHost:Re.string().optional()}),session:sk,history:Re.array(nk),promptHistory:Re.array(Re.string()).optional(),toolBlobs:Re.record(Re.string()).optional()})});import{createHash as wk}from"crypto";function Bl(t){if(Array.isArray(t))return t.map(Bl);if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t).sort())e[n]=Bl(t[n]);return e}return t}function Ts(t){let{tui:e,...n}=t,s=JSON.stringify(Bl(n));return wk("sha256").update(s).digest("hex").slice(0,16)}var Fo=K(()=>{"use strict";je()});function Nl(t){return Math.floor(t/4)}function Qm(t){if(t.compactionInFlight||t.totalEntries===0)return!1;let e;if(typeof t.agentReportedUsed=="number"&&typeof t.agentReportedSize=="number"&&t.agentReportedSize>0)e=t.agentReportedUsed/t.agentReportedSize;else{let s=Nl(t.unsummarizedChars),r=t.currentModel!==void 0?t.config.modelContextWindows[t.currentModel]??t.config.absoluteFallback:t.config.absoluteFallback;e=s/r}if(e>=t.config.hardCeilingFraction)return!0;let n=t.nowMs-t.lastActivityMs;return e>=t.config.contextFraction&&n>=t.config.idleBeforePromptMs}function Gm(t){return t>=1e3?`${Math.round(t/1e3)}K`:`${t}`}var Dl=K(()=>{"use strict"});function Oo(t){if(!t||typeof t!="object")return;let e=t;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Xm=K(()=>{"use strict"});import{posix as Pk}from"path";import Mk from"strip-ansi";function tt(t){return Mk(t).replace(_k,"")}function xe(t){return tt(t).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function _n(t,e={}){if(!t||typeof t!="object")return null;let n=t,s=n.sessionUpdate??n.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Nk(n);case"agent_thought_chunk":case"agent_thought":return Dk(n);case"user_message_chunk":return Hk(n);case"prompt_received":return Uk(n);case"tool_call":return jk(n,e);case"tool_call_update":return Kk(n,e);case"plan":return Qk(n);case"current_mode_update":return Gk(n);case"current_model_update":return Xk(n);case"turn_complete":return Zk(n);case"usage_update":return Bk(n);case"available_commands_update":return Ok(n);case"available_modes_update":return Lk(n);case"session_info_update":return Fk(n);case"config_option_update":return $k(n);default:return{kind:"unknown",sessionUpdate:s,raw:t}}}function $k(t){let e=t.configOptions;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}n.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:n}}function Fk(t){let e=Ke(t,"title"),n=e!==void 0?xe(e):void 0,s=t._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(n===void 0&&r===void 0)return null;let i={kind:"session-info"};return n!==void 0&&(i.title=n),r!==void 0&&(i.agentId=r),i}function ud(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:xe(r)};typeof s.description=="string"&&(i.description=xe(s.description)),e.push(i)}return e}function Ok(t){let e=t.availableCommands??t.commands;return Array.isArray(e)?{kind:"available-commands",commands:ud(e)}:null}function Lk(t){let e=t.availableModes;if(!Array.isArray(e))return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:xe(r.id)};typeof r.name=="string"&&(i.name=xe(r.name)),typeof r.description=="string"&&(i.description=xe(r.description)),n.push(i)}return{kind:"available-modes",modes:n}}function Bk(t){let e={kind:"usage-update"};if(typeof t.used=="number"&&(e.used=t.used),typeof t.size=="number"&&(e.size=t.size),t.cost&&typeof t.cost=="object"){let n=t.cost;typeof n.amount=="number"&&(e.costAmount=n.amount),typeof n.currency=="string"&&(e.costCurrency=n.currency)}return e}function Nk(t){let e=Lo(t.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:Oo(t)}}function Dk(t){let e=typeof t.text=="string"?tt(t.text):Lo(t.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:Oo(t)}}function Hk(t){let e=t._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let n=Lo(t.content);return n===null?null:{kind:"user-text",text:n}}function Uk(t){let e=eI(t.prompt);return e===null?null:{kind:"user-text",text:e}}function th(t){return t?t.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Zm(t){if(typeof t=="string")return{text:t};if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function fd(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Zm(r.oldText),o=Zm(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function nh(t){let e=t.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e.plan;return typeof n!="string"||n.length===0?null:tt(n)}function jk(t,e={}){let n=Ke(t,"toolCallId")??Ke(t,"id");if(!n)return null;let s=Ke(t,"title")??Ke(t,"name")??Ke(t,"label")??"tool call",r=Ke(t,"name")??Ke(t,"title");if(th(r)){let m=nh(t);if(m!==null){let h=Ke(t,"status"),y={kind:"exit-plan-mode",toolCallId:n,plan:m};return h!==void 0&&(y.status=h),y}}let i=ih(xe(s),t,e),o=Ke(t,"status"),a=Ke(t,"kind"),c={kind:"tool-call",toolCallId:n,title:i};o!==void 0&&(c.status=o),a!==void 0&&(c.rawKind=a);let d=fd(t);d!==null&&(c.editDiff=d);let l=rh(t);l!==void 0&&(c.detail=l);let u=Hl(t);u!==void 0&&(c.detailFull=u);let f=sh(t);f!==void 0&&(c.locations=f);let p=Oo(t);return p!==void 0&&(c.workerTaskId=p),c}function sh(t){let e=t.locations;if(!Array.isArray(e))return;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),n.push(i)}return n.length>0?n:void 0}function rh(t){let e=Hl(t);if(e===void 0)return;let n=xe(e),s=t.rawInput;return s&&typeof s.command=="string"?zk(n,eh):Jk(n,eh)}function Hl(t){let e=t.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(typeof n.command=="string"&&n.command.trim().length>0)return tt(n.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof n.file_path=="string"?n.file_path:typeof n.filePath=="string"?n.filePath:typeof n.path=="string"?n.path:void 0;if(s!==void 0&&s.length>0)return ze(xe(s))}if(Array.isArray(t.locations)){for(let n of t.locations)if(n&&typeof n=="object"){let s=n.path;if(typeof s=="string"&&s.length>0)return ze(xe(s))}}}function Wk(t){for(let e of qk)if(t.startsWith(e))return!0;return!1}function ih(t,e,n={}){if(t.length===0)return t;if(t.startsWith("/"))return ze(t);if(t.startsWith("~")||!t.includes("/")||/\s/.test(t))return t;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${t}`||o.endsWith(`/${t}`)||o===t))return ze(o)}return Wk(t)?ze(`/${t}`):n.cwd&&n.cwd.length>0?ze(Pk.resolve(n.cwd,t)):t}function zk(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Jk(t,e){if(t.length<=e)return t;let n=t.slice(-(e-1)),s=n.indexOf("/");return s>=0&&s<e/2?`\u2026${n.slice(s)}`:`\u2026${n}`}function Kk(t,e={}){let n=Ke(t,"toolCallId")??Ke(t,"id");if(!n)return null;let s=Ke(t,"title"),r=s!==void 0?ih(xe(s),t,e):void 0,i=Ke(t,"status"),o=fd(t),a=rh(t);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let d=Ke(t,"name")??s;if(th(d)){let m={kind:"exit-plan-mode",toolCallId:n},h=nh(t);return h!==null&&(m.plan=h),i!==void 0&&(m.status=i),m}let l={kind:"tool-call-update",toolCallId:n};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=Hl(t);u!==void 0&&(l.detailFull=u);let f=sh(t);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let m=Vk(t);m!==null&&(l.errorText=m),Yk(t,m)&&(l.upstreamInterrupted=!0)}let p=Oo(t);return p!==void 0&&(l.workerTaskId=p),l}function Vk(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=Lo(s.content);if(i!==null&&i.length>0)return i}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"&&s.length>0)return tt(s)}return null}function Yk(t,e){let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Qk(t){let e=t.entries;if(!Array.isArray(e)||e.length===0)return null;let n=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?xe(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),n.push(o)}return{kind:"plan",entries:n}}function Gk(t){let e=Ke(t,"currentModeId")??Ke(t,"currentMode")??Ke(t,"mode");return e?{kind:"mode-changed",mode:xe(e)}:null}function Xk(t){let e=Ke(t,"currentModel")??Ke(t,"model");if(!e)return null;let n=t.availableModels,s=Array.isArray(n)?n.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:xe(e),...s&&s.length>0?{availableModels:s}:{}}}function Zk(t){let e=Ke(t,"stopReason"),n=t._meta,s=n?.["hydra-acp"]?.amended!==void 0&&n["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Lo(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object")return null;let e=t;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?tt(e.text):null}function eI(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){let s=Lo(n);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function Ke(t,e){let n=t[e];return typeof n=="string"?n:void 0}var _k,eh,qk,Es=K(()=>{"use strict";he();Xm();_k=/[\x00-\x08\x0b-\x1f\x7f]/g;eh=64;qk=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"]});function bi(t){let e=new Map,n=new Map;for(let r of t){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,d=nI(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(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(c,[...u,...f]),l=f}for(let u of l)tI(n,u)}let s=[];for(let[r,i]of n)s.push({path:r,hunks:i.hunks,created:i.created});return s}function vi(t){let e=[];for(let n of t){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===n.oldText){s=i;break}if(s===-1){e.push(n);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:n.newText})}return e}function tI(t,e){let n={oldText:e.oldText,newText:e.newText},s=t.get(e.path);if(s===void 0){t.set(e.path,{hunks:[n],created:e.oldText.length===0});return}s.hunks.push(n)}function nI(t){let e=[],n=t.rawInput;if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let d=c,l=typeof d.old_string=="string"?d.old_string:void 0,u=typeof d.new_string=="string"?d.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=t.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let c=typeof o.oldText=="string"?o.oldText:"",d=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:c,newText:d})}if(e.length>0)return e}let r=fd(t);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}var pd=K(()=>{"use strict";Es()});function $n(t){let e=[],n=[],s=!1,r=i=>{if(!s){s=!0;for(let o of n)o(i)}};return t.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let c=JSON.parse(a);for(let d of e)d(c)}catch(c){for(let d of e)d({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),t.on("close",()=>r()),t.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,c)=>{t.send(o,d=>{if(d){c(d);return}a()})})},onMessage(i){e.push(i)},onClose(i){n.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(c),i())},c=setTimeout(a,5e3);t.once("close",a);try{t.close()}catch{a()}}),r())}}}var Ii=K(()=>{"use strict";xt()});import{spawn as Sx}from"child_process";import{setTimeout as kx}from"timers/promises";async function qh(){let t=await Zn();if(t&&mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}/v1/health`}async function Ix(t){let e=await vr(t,500);return e?e.configDigest===void 0?"mismatch":e.configDigest===Ts(t)?"match":"mismatch":"missing"}async function _s(t){let e=await Ix(t);if(e!=="match"){if(e==="mismatch"){let n=Cn();throw new Error(`unable to attach to running daemon \u2014 run \`${n} daemon stop\` and try again.`)}process.stderr.write(`hydra-acp: daemon not running; starting it...
97
+ `),Cd(),await Ad(t)}}async function xd(t){let e=await qh();if(!e)return!1;try{return(await fetch(e,{signal:AbortSignal.timeout(500),headers:{Connection:"close"}})).ok}catch{return!1}}async function vr(t,e=1e3){let n=await qh();if(n)try{let s=await fetch(n,{signal:AbortSignal.timeout(e),headers:{Connection:"close"}});if(!s.ok)return;let r=await s.json();return{version:typeof r.version=="string"?r.version:void 0,configDigest:typeof r.configDigest=="string"?r.configDigest:void 0}}catch{return}}function Cd(){let t=process.argv[1];if(!t)throw new Error("Cannot determine hydra-acp binary path to spawn daemon");Sx(process.execPath,[t,"daemon","start","--foreground"],{detached:!0,stdio:"ignore",env:process.env}).unref()}async function Ad(t,e=15e3){let n=Date.now()+e;for(;Date.now()<n;){if(await xd(t))return;await kx(150)}throw new Error(`hydra-acp daemon did not become ready within ${e}ms`)}var Sr=K(()=>{"use strict";fo();Fo();ei()});import{WebSocket as Tx}from"ws";async function kr(t,e,n=Ex){let s={};try{let r=new URL(t);if(r.protocol==="wss:"){let i=mo(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 Tx(t,e,s),a=Date.now(),c=setTimeout(()=>{o.off("open",d),o.off("error",l),o.on("error",()=>{});try{o.terminate()}catch{}i(new Xl(t,Date.now()-a))},n),d=()=>{clearTimeout(c),o.off("error",l),r(o)},l=u=>{clearTimeout(c),o.off("open",d),i(u)};o.once("open",d),o.once("error",l)})}var Ex,Xl,Do=K(()=>{"use strict";ho();Ex=1e4,Xl=class extends Error{url;elapsedMs;constructor(e,n){super(`hydra-acp: websocket connect to ${e} timed out after ${n}ms`),this.name="WsConnectTimeoutError",this.url=e,this.elapsedMs=n}}});import*as Td from"fs/promises";function Px(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"?"127.0.0.1":t}async function Ei(){let t=await Zn();if(t&&mn(t.pid))return`http://127.0.0.1:${t.loopbackPort}`;let e=await we();return Gh(e.daemon.host,e.daemon.port,!!e.daemon.tls)}function Gh(t,e,n){return`${n?"https":"http"}://${Px(t)}:${e}`}async function Fe(t,e={}){let n=await or(),s=await Ei(),r=t.startsWith("http")?t:`${s}${t}`,i={Authorization:`Bearer ${n}`},o;e.body!==void 0&&(i["Content-Type"]="application/json",o=JSON.stringify(e.body));let a;try{a=await fetch(r,{method:e.method,headers:i,...o!==void 0?{body:o}:{}})}catch(u){if(e.rethrowNetworkError)throw u;process.stderr.write(`Could not reach daemon at ${s}: ${u.message}
98
+ `),process.exit(1)}let c=null;if(a.status!==204)try{c=await a.json()}catch{c=null}let d=e.expectStatus,l=d===void 0?a.ok:Array.isArray(d)?d.includes(a.status):d===a.status;if(d!==void 0&&!l){let u=`HTTP ${a.status}`;if(c&&typeof c=="object"&&"error"in c){let p=c.error;typeof p=="string"&&p.length>0&&(u=p)}let f=e.errorPrefix??"Daemon returned";process.stderr.write(`${f} ${u}
99
+ `),process.exit(1)}return{ok:a.ok,status:a.status,body:c}}function Pi(t){let e;t instanceof Date?e=t.getTime():typeof t=="string"?e=Date.parse(t):e=t;let n=Math.max(0,Date.now()-e),s=Math.floor(n/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Ed(t,e){let n=e!=="agent",s=n?[]:void 0,r=[],i={},o=!0,a=0;for(;a<t.length;){let c=t[a];if(c==="--command"){let d=t[a+1];d===void 0&&(process.stderr.write(`--command requires a value
100
+ `),process.exit(2)),s=n?Mx(d):d,a+=2;continue}if(c==="--args"){let d=t[a+1];d===void 0&&(process.stderr.write(`--args requires a value
101
101
  `),process.exit(2)),r=d.split(",").filter(l=>l.length>0),a+=2;continue}if(c==="--env"){let d=t[a+1];d===void 0&&(process.stderr.write(`--env requires KEY=VALUE
102
102
  `),process.exit(2));let l=d.indexOf("=");l<=0&&(process.stderr.write(`Invalid --env value '${d}': expected KEY=VALUE
103
103
  `),process.exit(2)),i[d.slice(0,l)]=d.slice(l+1),a+=2;continue}if(c==="--disabled"&&e!=="agent"){o=!1,a+=1;continue}process.stderr.write(`Unknown flag: ${c}
104
- `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function cx(t){return t.split(/\s+/).filter(e=>e.length>0)}async function vi(){let t=await hd.readFile(_.config(),"utf8");return JSON.parse(t)}async function jl(t){await hd.writeFile(_.config(),JSON.stringify(t,null,2)+`
105
- `,{encoding:"utf8",mode:384})}var Ss=K(()=>{"use strict";Ne();qn();pe();qr();Eo()});async function Ht(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new ql(t,n):c}finally{clearTimeout(a)}}async function En(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await Ht(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"live",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState})):[]}async function Bh(t,e=fetch){let n=await Ht(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await Ht(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function Wl(t,e=fetch){let n=await Ht(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function yd(t,e,n={},s=fetch){let r=await Ht(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},3e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function Pn(t,e,n=fetch){let s=await Ht(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function Nh(t,e,n,s=fetch){let r=await Ht(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Dh(t,e,n,s=fetch){let r=await Ht(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function Hh(t,e,n=fetch){let s=await Ht(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function Uh(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await Ht(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function jh(t,e,n=fetch){let s=await Ht(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function wd(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="live"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var ql,Po=K(()=>{"use strict";ql=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function zl(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function qh(t,e){let n=t??"?",s=zl(e);return s?`${n}${lx}${s}`:n}function Wh(t){return t??"?"}function zh(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:Jl(e,n)}function Jl(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var lx,Kl=K(()=>{"use strict";lx="\u2022"});function Jh(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!vd.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${vd.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Ii(t,e=Date.now()){return{session:Ve(t.sessionId),upstream:px(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:mx(t.status,t.busy,t.awaitingInput,fx(t.compactionState)),agent:Wh(t.agentId),model:zl(t.currentModel)??"-",age:hx(t.updatedAt,e),title:t.title??"-",cwd:Ue(t.cwd),cost:zh(t.currentUsage)}}function fx(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function px(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function mx(t,e,n,s){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":s?"LIVE\u27F3":"LIVE"}function xi(t,e={}){let n=e.columns??Si,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=gx(ki[r],t.map(i=>i[r]));return s}function hx(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function gx(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function ks(t,e,n,s={}){let r=s.columns??Si,i=s.cwdMaxWidth??ux,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(bd);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>Yl.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(bd);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!Yl.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),f=n-d-l*bd.length;f<0&&(f=0);let u=new Map,p=f;for(let{col:v,i:S}of a){if(S===c)continue;let x=v==="cwd"?Math.min(e[v],i):e[v],T=Math.min(x,Math.max(0,p-1));u.set(S,T),p=Math.max(0,p-T)}u.set(c,Math.max(0,p));let m=r.length-1,h=(v,S,x)=>{if(v==="cwd")return Mo(t[v],S).padEnd(S);let T=yx(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>Yl.has(v)?h(v,u.get(S)??0,S===m):o(v)).join(bd);return b.length>n?b.slice(0,n):b}function yx(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function Mo(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var vd,Si,Yl,ki,bd,ux,Sd=K(()=>{"use strict";Kl();pe();xn();vd=["session","upstream","host","state","agent","model","age","cwd","title","cost"],Si=["session","state","age","cwd","title","agent","cost"],Yl=new Set(["cwd","title"]),ki={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},bd=" ",ux=32});import{spawn as Rx}from"child_process";import{Writable as Tx}from"stream";function kd(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=Ex(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??Rx,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
106
- `)});let c=new Tx({write(l,f,u){if(!a.writable){u();return}a.write(l,m=>{if(m&&m.code!=="EPIPE"){u(m);return}u()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
107
- `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function Ex(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var Vl=K(()=>{"use strict"});import Px from"chalk";import{highlight as Mx,supportsLanguage as Id}from"cli-highlight";import Cd from"string-width";function Is(t,e={}){switch(t.kind){case"user-text":{let n=Gl(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return Gl(t.text," ","agent");case"agent-thought":return Gl(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return Zx(t,e.maxPlanItems??Qx);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function Ql(t,e){return Ci(t,e).styled}function Ci(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],f=0;for(;f<t.length;){let u=t[f];if(u==="^"){a+="^^",c+=1,f+=1;continue}if(u==="*"&&t[f+1]==="*"){let p=t.indexOf("**",f+2);if(p!==-1&&p>f+2){let m=t.slice(f+2,p),h=Ci(m,e),w=c;a+=`^+${h.styled}${r}`;for(let b of h.links)l.push({start:w+b.start,end:w+b.end,url:b.url});c+=h.cleanLength,h.ansi&&(d=!0),f=p+2;continue}}if(u==="`"){let p=t.indexOf("`",f+1);if(p!==-1&&p>f+1){let m=t.slice(f+1,p);a+=`${n}${m}${s}`,c+=m.length,f=p+1;continue}}if(u==="["){let p=t.indexOf("]",f+1);if(p!==-1&&t[p+1]==="("&&p>f+1){let m=-1;{let h=1,w=p+2;for(;w<t.length;){let b=t[w];if(b==="\\"&&w+1<t.length){w+=2;continue}if(b==="(")h+=1;else if(b===")"&&(h-=1,h===0)){m=w;break}w+=1}}if(m!==-1&&m>p+2){let h=t.slice(f+1,p),w=t.slice(p+2,m),b=Ci(h,e),v=c,S=w.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${w}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let x of b.links)l.push({start:v+x.start,end:v+x.end,url:x.url});c+=b.cleanLength,S&&l.push({start:v,end:c,url:w}),f=m+1;continue}}}a+=u,c+=1,f+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function _x(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function rg(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function ig(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
108
- `),l=!1,f="",u=[],p=i!==" ",m=(b,v,S=" ",x,T)=>{let F={prefix:S,body:b,bodyStyle:v};r!==void 0&&(F.prefixStyle=r),x&&x.length>0&&(F.links=x),T&&(F.ansi=!0),c.push(F)},h=()=>p?(p=!1,i):" ",w=()=>{if(u.length!==0){if(s){let b=ag(f,u);for(let v of b){let S={prefix:" ",body:v.body,bodyStyle:"code",fillRow:!0};r!==void 0&&(S.prefixStyle=r),v.ansi&&(S.ansi=!0),c.push(S)}}else for(let b of u)m(b.replace(/\^/g,"^^"),n);u=[],f=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(w(),l=!1):(l=!0,f=S[1]??"");continue}if(l){u.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let B=x[1].length,N=x[2]??"",j=s?B===1?"heading-1":B===2?"heading-2":"heading-3":n,X=s?rg(j):o;m(Ql(N,X),j,h());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&$x(T)&&_o(v).length===_o(T).length){let B=_o(v),N=[],j=b+2;for(;j<d.length&&d[j].includes("|");)N.push(_o(d[j])),j++;let X=Hx(B,N,a);for(let Y of X)r!==void 0&&(Y.prefixStyle=r),c.push(Y);b=j-1;continue}let F=v.match(/^(\s*)[-*+]\s+(.*)$/);if(F){let B=F[1]??"",N=F[2]??"",j=Ci(N,o),X=B.length+2,Y=j.links.map(be=>({start:be.start+X,end:be.end+X,url:be.url}));m(`${B}\u2022 ${j.styled}`,n,h(),Y,j.ansi);continue}let $=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if($){let B=$[1]??"",N=$[2]??"",j=$[3]??"",X=Ci(j,o),Y=B.length+N.length+2,be=X.links.map(V=>({start:V.start+Y,end:V.end+Y,url:V.url}));m(`${B}${N}. ${X.styled}`,n,h(),be,X.ansi);continue}let H=v.trim()==="",J=Ci(v,o);m(J.styled,n,H?" ":h(),J.links,J.ansi)}for(l&&w();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function xs(t,e){return ig(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Ai(t){return ig(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function _o(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function $x(t){if(!t.includes("|"))return!1;let e=_o(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function xd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Cd(e)}function Lx(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:Cd(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:xd(r)}),n=i}return e}function Bx(t,e){let n=[],s="",r=0;for(let i of t){let o=Cd(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function Nx(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=Bx(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=Cd(d)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function Dx(t,e){let n=t.length;if(t.reduce((l,f)=>l+f,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,og)),i=r.reduce((l,f)=>l+f,0);if(i>=e)return r;let o=e-i,a=t.map((l,f)=>({i:f,slack:Math.max(0,l-r[f])})).filter(l=>l.slack>0),c=a.reduce((l,f)=>l+f.slack,0);if(c===0)return r;for(let l of a){let f=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(f,l.slack)}i=r.reduce((l,f)=>l+f,0);let d=e-i;for(;d>0;){let l=-1,f=0;for(let u=0;u<n;u++){let p=t[u]-r[u];p>f&&(f=p,l=u)}if(l<0)break;r[l]=r[l]+1,d--}return r}function Hx(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=xd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let f=d[l]??"",u=xd(f);u>r[l]&&(r[l]=u)}let i=r.slice();if(n!==void 0){let d=Math.max(s*og,n-Ox-(s-1)*Fx);i=Dx(r,d)}let o=(d,l,f)=>{let u=[],p=1;for(let h=0;h<s;h++){let w=d[h]??"",b=i[h],v=Nx(Lx(w),b);u.push(v),v.length>p&&(p=v.length)}let m=[];for(let h=0;h<p;h++){let w=[];for(let b=0;b<s;b++){let v=u[b][h]??"",S=i[b],x=xd(v),T=Ql(v,f);w.push(T+" ".repeat(Math.max(0,S-x)))}m.push({prefix:" ",body:w.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...o(t,"heading-3",rg("heading-3")));let c=[];for(let d=0;d<s;d++)c.push("\u2500".repeat(i[d]));a.push({prefix:" ",body:c.join("\u2500\u253C\u2500"),bodyStyle:"dim"});for(let d of e)a.push(...o(d,"agent"));return a}function ag(t,e){if(t.length===0||!Id(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=Mx(e.join(`
109
- `),{language:t,theme:Ux,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
110
- `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function qx(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Id("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Id("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=jx[s];return r&&Id(r)?r:""}function Gl(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
111
- `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function Wx(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Mn(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function dg(t){if(t.length<=4096&&t.split(`
104
+ `),process.exit(2)}return{command:s,args:r,env:i,enabled:o}}function Mx(t){return t.split(/\s+/).filter(e=>e.length>0)}async function Mi(){let t=await Td.readFile($.config(),"utf8");return JSON.parse(t)}async function Zl(t){await Td.writeFile($.config(),JSON.stringify(t,null,2)+`
105
+ `,{encoding:"utf8",mode:384})}var $s=K(()=>{"use strict";je();Gn();he();ei();Do()});async function Kt(t,e={},n=8e3,s=fetch){let r=new AbortController,i=e.signal??void 0;i&&(i.aborted?r.abort(i.reason):i.addEventListener("abort",()=>r.abort(i.reason),{once:!0}));let o=!1,a=setTimeout(()=>{o=!0,r.abort()},n);try{return await s(t,{...e,signal:r.signal})}catch(c){throw o?new eu(t,n):c}finally{clearTimeout(a)}}async function Fn(t,e={},n=fetch){let s=new URL(`${t.baseUrl}/v1/sessions`);e.cwd&&s.searchParams.set("cwd",e.cwd),e.all&&s.searchParams.set("all","true"),e.includeNonInteractive&&s.searchParams.set("includeNonInteractive","true");let r=await Kt(s.toString(),{headers:{Authorization:`Bearer ${t.token}`},signal:e.signal},8e3,n);if(!r.ok)throw new Error(`daemon returned HTTP ${r.status}`);let i=await r.json();return Array.isArray(i.sessions)?i.sessions.map(o=>({sessionId:o.sessionId,cwd:o.cwd,updatedAt:o.updatedAt,attachedClients:o.attachedClients??0,status:o.status??"live",upstreamSessionId:o.upstreamSessionId,agentId:o.agentId,currentModel:o.currentModel,currentUsage:o.currentUsage,title:o.title,importedFromMachine:o.importedFromMachine,importedFromUpstreamSessionId:o.importedFromUpstreamSessionId,forkedFromSessionId:o.forkedFromSessionId,forkedFromMessageId:o.forkedFromMessageId,busy:o.busy,awaitingInput:o.awaitingInput,originatingClient:o.originatingClient,interactive:o.interactive,priority:o.priority,compactionState:o.compactionState})):[]}async function Xh(t,e=fetch){let n=await Kt(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json(),r=Array.isArray(s.agents)?s.agents.filter(c=>c.installed==="yes"):[],i=0,o=0,a=0;for(let c of r)try{let d=await Kt(`${t.baseUrl}/v1/agents/${c.id}/sync`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},3e4,e);if(!d.ok)continue;let l=await d.json();i+=Array.isArray(l.synced)?l.synced.length:0,o+=typeof l.skipped=="number"?l.skipped:0,a+=1}catch{}return{synced:i,skipped:o,agents:a}}async function tu(t,e=fetch){let n=await Kt(`${t.baseUrl}/v1/agents`,{headers:{Authorization:`Bearer ${t.token}`}},8e3,e);if(!n.ok)throw new Error(`daemon returned HTTP ${n.status}`);let s=await n.json();return Array.isArray(s.agents)?s.agents.map(r=>({id:r.id,name:r.name,description:r.description,...r.onboarding?{onboarding:r.onboarding}:{}})):[]}async function Pd(t,e,n={},s=fetch){let r=await Kt(`${t.baseUrl}/v1/sessions/${e}/fork`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(n)},3e4,s);if(!r.ok){let i="";try{let o=await r.json();typeof o.error=="string"&&(i=`: ${o.error}`)}catch{}throw new Error(`fork failed (HTTP ${r.status})${i}`)}return await r.json()}async function On(t,e,n=fetch){let s=await Kt(`${t.baseUrl}/v1/sessions/${e}/kill`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}async function Zh(t,e,n,s=fetch){let r=await Kt(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({title:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function eg(t,e,n,s=fetch){let r=await Kt(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({priority:n})},8e3,s);if(!r.ok&&r.status!==204&&r.status!==404)throw new Error(`daemon returned HTTP ${r.status}`)}async function tg(t,e,n=fetch){let s=await Kt(`${t.baseUrl}/v1/sessions/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({regen:!0})},8e3,n);if(!s.ok&&s.status!==202&&s.status!==204&&s.status!==404&&s.status!==409)throw new Error(`daemon returned HTTP ${s.status}`)}async function ng(t,e,n={},s=fetch){let r={q:e};n.sessionIds&&n.sessionIds.length>0&&(r.sessionIds=n.sessionIds);let i=await Kt(`${t.baseUrl}/v1/sessions/search`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)},2e4,s);if(!i.ok)throw new Error(`daemon returned HTTP ${i.status}`);return await i.json()}async function sg(t,e,n=fetch){let s=await Kt(`${t.baseUrl}/v1/sessions/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}},8e3,n);if(!s.ok&&s.status!==204&&s.status!==404)throw new Error(`daemon returned HTTP ${s.status}`)}function Md(t,e){let n=t.filter(i=>i.cwd===e);if(n.length===0)return null;let s=i=>i.status==="live"?1:0;return[...n].sort((i,o)=>{let a=s(o)-s(i);return a!==0?a:o.updatedAt.localeCompare(i.updatedAt)})[0]??null}var eu,Ho=K(()=>{"use strict";eu=class extends Error{constructor(n,s){super(`daemon did not respond within ${s}ms (${n})`);this.url=n;this.timeoutMs=s;this.name="DaemonTimeoutError"}url;timeoutMs}});function nu(t){if(!t)return;let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}function rg(t,e){let n=t??"?",s=nu(e);return s?`${n}${_x}${s}`:n}function ig(t){return t??"?"}function og(t){if(!t||typeof t.costAmount!="number")return"";let{costAmount:e,costCurrency:n}=t;return n===void 0||n==="USD"?`$${Math.round(e)}`:su(e,n)}function su(t,e){return`${e==="USD"||e===void 0?"$":""}${t.toFixed(2)}${e&&e!=="USD"?` ${e}`:""}`}var _x,ru=K(()=>{"use strict";_x="\u2022"});function ag(t){let e=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(e.length===0)throw new Error("--columns: no column names given");let n=new Set,s=[];for(let r of e){if(!$d.includes(r))throw new Error(`--columns: unknown column "${r}" (valid: ${$d.join(", ")})`);if(n.has(r))throw new Error(`--columns: duplicate column "${r}"`);n.add(r),s.push(r)}return s}function Fi(t,e=Date.now()){return{session:et(t.sessionId),upstream:Ox(t.upstreamSessionId,t.importedFromMachine),host:t.importedFromMachine??"-",state:Lx(t.status,t.busy,t.awaitingInput,Fx(t.compactionState)),agent:ig(t.agentId),model:nu(t.currentModel)??"-",age:Bx(t.updatedAt,e),title:t.title??"-",cwd:ze(t.cwd),cost:og(t.currentUsage)}}function Fx(t){if(t==null||typeof t!="object")return!1;let e=t.status;return e==="requested"||e==="running"||e==="swap_pending"||e==="swap_deferred"}function Ox(t,e){return t&&t.length>0?t:e&&e.length>0?`\u2190 ${e}`:"-"}function Lx(t,e,n,s){return t==="cold"?"COLD":n?"LIVE\u25E6":e?"LIVE\u2022":s?"LIVE\u27F3":"LIVE"}function Oi(t,e={}){let n=e.columns??_i,s={session:0,upstream:0,host:0,state:0,agent:0,model:0,age:0,cwd:0,title:0,cost:0};for(let r of n)s[r]=Nx($i[r],t.map(i=>i[r]));return s}function Bx(t,e){if(!t)return"?";let n=Date.parse(t);if(Number.isNaN(n))return"?";let s=Math.max(0,e-n),r=Math.floor(s/1e3);if(r<60)return"<1m";let i=Math.floor(r/60);if(i<60)return`${i}m`;let o=Math.floor(i/60);if(o<24)return`${o}h`;let a=Math.floor(o/24);if(a<14)return`${a}d`;let c=Math.floor(a/7);if(c<9)return`${c}w`;let d=Math.floor(a/30);return d<12?`${d}mo`:`${Math.floor(a/365)}y`}function Nx(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Fs(t,e,n,s={}){let r=s.columns??_i,i=s.cwdMaxWidth??$x,o=v=>v==="age"?t[v].padStart(e[v]):t[v].padEnd(e[v]);if(n===void 0)return r.map((S,x)=>x===r.length-1?t[S]:o(S)).join(_d);let a=r.map((v,S)=>({col:v,i:S})).filter(({col:v})=>iu.has(v)),c=a.length>0?a[a.length-1].i:-1;if(c===-1){let v=r.map(o).join(_d);return v.length>n?v.slice(0,n):v}let d=r.filter(v=>!iu.has(v)).reduce((v,S)=>v+e[S],0),l=Math.max(0,r.length-1),u=n-d-l*_d.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 m=r.length-1,h=(v,S,x)=>{if(v==="cwd")return Uo(t[v],S).padEnd(S);let T=Dx(t[v],S);return x?T:T.padEnd(S)},b=r.map((v,S)=>iu.has(v)?h(v,f.get(S)??0,S===m):o(v)).join(_d);return b.length>n?b.slice(0,n):b}function Dx(t,e){return e<=0?"":t.length<=e?t:e===1?"\u2026":t.slice(0,e-1)+"\u2026"}function Uo(t,e){if(e<=0)return"";if(t.length<=e)return t;if(e===1)return"\u2026";let n=Math.ceil((e-1)/2),s=e-1-n;return t.slice(0,n)+"\u2026"+t.slice(t.length-s)}var $d,_i,iu,$i,_d,$x,Fd=K(()=>{"use strict";ru();he();En();$d=["session","upstream","host","state","agent","model","age","cwd","title","cost"],_i=["session","state","age","cwd","title","agent","cost"],iu=new Set(["cwd","title"]),$i={session:"SESSION",upstream:"UPSTREAM",host:"HOST",state:"STATE",agent:"AGENT",model:"MODEL",age:"AGE",title:"TITLE",cwd:"CWD",cost:"COST"},_d=" ",$x=32});import{spawn as Yx}from"child_process";import{Writable as Qx}from"stream";function Od(t={}){let e=t.isTTY??process.stdout.isTTY===!0;if(t.disabled===!0||!e)return{stream:process.stdout,flush:async()=>{}};let n=t.env??process.env,s=Gx(n);if(s===null)return{stream:process.stdout,flush:async()=>{}};let r=t.spawn??Yx,i={...n};i.LESS===void 0&&(i.LESS="FRX");let o=r(s,[],{shell:!0,stdio:["pipe","inherit","inherit"],env:i}),a=o.stdin;if(a===null)return{stream:process.stdout,flush:async()=>{}};a.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
106
+ `)});let c=new Qx({write(l,u,f){if(!a.writable){f();return}a.write(l,m=>{if(m&&m.code!=="EPIPE"){f(m);return}f()})||a.once("drain",()=>{})},final(l){a.writable&&a.end(),l()}});c.on("error",l=>{l.code!=="EPIPE"&&process.stderr.write(`pager: ${l.message}
107
+ `)});let d=new Promise(l=>{o.once("exit",()=>l()),o.once("error",()=>l())});return{stream:c,flush:async()=>{a.writable&&await new Promise(l=>{c.end(()=>l())}),await d}}}function Gx(t){let e=t.HYDRA_ACP_PAGER;if(e!==void 0)return e.length===0?null:e;let n=t.PAGER;return n!==void 0?n.length===0?null:n:"less"}var ou=K(()=>{"use strict"});import Xx from"chalk";import{highlight as Zx,supportsLanguage as Ld}from"cli-highlight";import Nd from"string-width";function Os(t,e={}){switch(t.kind){case"user-text":{let n=au(t.text,"\u258E ","user",void 0,t.sentBy,!0);if(t.attachments&&t.attachments.length>0)for(let s of t.attachments)n.push({prefix:"\u258E ",prefixStyle:"user",body:`\u{1F4CE} ${s.name??"image"}`,bodyStyle:"user",fillRow:!0,iterm2Image:{data:s.data,heightCells:5}});return n}case"agent-text":return au(t.text," ","agent");case"agent-thought":return au(t.text," ","thought","thought");case"tool-call":case"tool-call-update":return[];case"exit-plan-mode":return[];case"plan":return SC(t,e.maxPlanItems??bC);case"mode-changed":return[{prefix:"\xBB ",prefixStyle:"info",body:`mode: ${t.mode}`,bodyStyle:"info"}];case"model-changed":return[];case"turn-complete":return[];case"usage-update":return[];case"available-commands":case"available-modes":case"config-options":return[];case"session-info":return[];case"unknown":return[]}}function du(t,e){return Li(t,e).styled}function Li(t,e){let n=e?.codeOpen??"^C",s=e?.codeReset??"^:",r=e?.boldReset??"^:",i=e?.linkOpen??"^C^_",o=e?.linkReset??"^:",a="",c=0,d=!1,l=[],u=0;for(;u<t.length;){let f=t[u];if(f==="^"){a+="^^",c+=1,u+=1;continue}if(f==="*"&&t[u+1]==="*"){let p=t.indexOf("**",u+2);if(p!==-1&&p>u+2){let m=t.slice(u+2,p),h=Li(m,e),y=c;a+=`^+${h.styled}${r}`;for(let b of h.links)l.push({start:y+b.start,end:y+b.end,url:b.url});c+=h.cleanLength,h.ansi&&(d=!0),u=p+2;continue}}if(f==="`"){let p=t.indexOf("`",u+1);if(p!==-1&&p>u+1){let m=t.slice(u+1,p);a+=`${n}${m}${s}`,c+=m.length,u=p+1;continue}}if(f==="["){let p=t.indexOf("]",u+1);if(p!==-1&&t[p+1]==="("&&p>u+1){let m=-1;{let h=1,y=p+2;for(;y<t.length;){let b=t[y];if(b==="\\"&&y+1<t.length){y+=2;continue}if(b==="(")h+=1;else if(b===")"&&(h-=1,h===0)){m=y;break}y+=1}}if(m!==-1&&m>p+2){let h=t.slice(u+1,p),y=t.slice(p+2,m),b=Li(h,e),v=c,S=y.startsWith("file://");S?a+=`${i}${b.styled}${o}`:(a+=`\x1B]8;;${y}\x1B\\${i}${b.styled}${o}\x1B]8;;\x1B\\`,d=!0);for(let x of b.links)l.push({start:v+x.start,end:v+x.end,url:x.url});c+=b.cleanLength,S&&l.push({start:v,end:c,url:y}),u=m+1;continue}}}a+=f,c+=1,u+=1}return{styled:a,links:l,cleanLength:c,ansi:d}}function eC(t){switch(t){case"plan-done":return{codeOpen:"^C",boldReset:"^:^g",codeReset:"^:^g"};case"plan-pending":return{codeOpen:"^C",boldReset:"^:^-",codeReset:"^:^-"};default:return{codeOpen:"^C",boldReset:"^:^Y",codeReset:"^:^Y"}}}function bg(t){switch(t){case"heading-1":return{codeOpen:"^C",boldReset:"^+^Y",codeReset:"^+^Y"};case"heading-2":return{codeOpen:"^Y",boldReset:"^+^C",codeReset:"^+^C"};default:return{codeOpen:"^C",boldReset:"^:^+",codeReset:"^:^+"}}}function vg(t,e){let{proseStyle:n,highlightCode:s,prefixStyle:r,firstPrefix:i=" ",inlineOpts:o,maxWidth:a}=e,c=[],d=t.replace(/^\s+/,"").split(`
108
+ `),l=!1,u="",f=[],p=i!==" ",m=(b,v,S=" ",x,T)=>{let _={prefix:S,body:b,bodyStyle:v};r!==void 0&&(_.prefixStyle=r),x&&x.length>0&&(_.links=x),T&&(_.ansi=!0),c.push(_)},h=()=>p?(p=!1,i):" ",y=()=>{if(f.length!==0){if(s){let b=kg(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)m(b.replace(/\^/g,"^^"),n);f=[],u=""}};for(let b=0;b<d.length;b++){let v=d[b],S=v.match(/^\s*```\s*(\w*)\s*$/);if(S){l?(y(),l=!1):(l=!0,u=S[1]??"");continue}if(l){f.push(v);continue}let x=v.match(/^(#{1,6})\s+(.*)$/);if(x){let D=x[1].length,L=x[2]??"",U=s?D===1?"heading-1":D===2?"heading-2":"heading-3":n,Q=s?bg(U):o;m(du(L,Q),U,h());continue}let T=d[b+1];if(v.includes("|")&&T!==void 0&&tC(T)&&jo(v).length===jo(T).length){let D=jo(v),L=[],U=b+2;for(;U<d.length&&d[U].includes("|");)L.push(jo(d[U])),U++;let Q=dC(D,L,a);for(let V of Q)r!==void 0&&(V.prefixStyle=r),c.push(V);b=U-1;continue}let _=v.match(/^(\s*)[-*+]\s+(.*)$/);if(_){let D=_[1]??"",L=_[2]??"",U=Li(L,o),Q=D.length+2,V=U.links.map(be=>({start:be.start+Q,end:be.end+Q,url:be.url}));m(`${D}\u2022 ${U.styled}`,n,h(),V,U.ansi);continue}let F=v.match(/^(\s*)(\d+)\.\s+(.*)$/);if(F){let D=F[1]??"",L=F[2]??"",U=F[3]??"",Q=Li(U,o),V=D.length+L.length+2,be=Q.links.map(Y=>({start:Y.start+V,end:Y.end+V,url:Y.url}));m(`${D}${L}. ${Q.styled}`,n,h(),be,Q.ansi);continue}let j=v.trim()==="",J=Li(v,o);m(J.styled,n,j?" ":h(),J.links,J.ansi)}for(l&&y();c.length>0&&c[c.length-1].body==="";)c.pop();return c}function Ls(t,e){return vg(t,{proseStyle:"agent",highlightCode:!0,maxWidth:e?.maxWidth})}function Bi(t){return vg(t,{proseStyle:"thought",highlightCode:!1,prefixStyle:"thought",firstPrefix:" ",inlineOpts:{codeOpen:"^c",boldReset:"^-",codeReset:"^K"}})}function jo(t){let e=t.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],s="",r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(o==="\\"&&i+1<e.length&&e[i+1]==="|"){s+="|",i+=1;continue}if(o==="`"){r=!r,s+=o;continue}if(o==="|"&&!r){n.push(s.trim()),s="";continue}s+=o}return n.push(s.trim()),n}function tC(t){if(!t.includes("|"))return!1;let e=jo(t);return e.length===0?!1:e.every(n=>/^:?-+:?$/.test(n))}function Bd(t){let e=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1");return Nd(e)}function rC(t){let e=[],n=0;for(;n<t.length;){let s=t[n];if(s===" "||s===" "){let o=n;for(;o<t.length&&(t[o]===" "||t[o]===" ");)o++;let a=t.slice(n,o);e.push({text:a,isWS:!0,width:Nd(a)}),n=o;continue}let r="",i=n;for(;i<t.length;){let o=t[i];if(o===" "||o===" ")break;if(t[i]==="*"&&t[i+1]==="*"){let a=t.indexOf("**",i+2);a===-1?(r+="**",i+=2):(r+=t.slice(i,a+2),i=a+2);continue}if(o==="`"){let a=t.indexOf("`",i+1);a===-1?(r+="`",i+=1):(r+=t.slice(i,a+1),i=a+1);continue}r+=o,i+=1}e.push({text:r,isWS:!1,width:Bd(r)}),n=i}return e}function iC(t,e){let n=[],s="",r=0;for(let i of t){let o=Nd(i);r>0&&r+o>e?(n.push(s),s=i,r=o):(s+=i,r+=o)}return s.length>0&&n.push(s),n}function oC(t,e){if(e<=0)return t.length===0?[""]:[t.map(o=>o.text).join("")];let n=[],s="",r=0,i=()=>{n.push(s.replace(/[ \t]+$/,"")),s="",r=0};for(let o of t){if(o.isWS){if(r===0)continue;s+=o.text,r+=o.width;continue}if(o.width>e){if(r>0&&i(),o.text.includes("**")||o.text.includes("`"))n.push(o.text);else{let c=iC(o.text,e);for(let l=0;l<c.length-1;l++)n.push(c[l]);let d=c[c.length-1]??"";s=d,r=Nd(d)}continue}if(r===0){s=o.text,r=o.width;continue}r+o.width>e?(i(),s=o.text,r=o.width):(s+=o.text,r+=o.width)}return(s.length>0||n.length===0)&&i(),n}function aC(t,e){let n=t.length;if(t.reduce((l,u)=>l+u,0)<=e)return t.slice();let r=t.map(l=>Math.min(l,Sg)),i=r.reduce((l,u)=>l+u,0);if(i>=e)return r;let o=e-i,a=t.map((l,u)=>({i:u,slack:Math.max(0,l-r[u])})).filter(l=>l.slack>0),c=a.reduce((l,u)=>l+u.slack,0);if(c===0)return r;for(let l of a){let u=Math.floor(o*l.slack/c);r[l.i]=r[l.i]+Math.min(u,l.slack)}i=r.reduce((l,u)=>l+u,0);let d=e-i;for(;d>0;){let l=-1,u=0;for(let f=0;f<n;f++){let p=t[f]-r[f];p>u&&(u=p,l=f)}if(l<0)break;r[l]=r[l]+1,d--}return r}function dC(t,e,n){let s=t.length,r=new Array(s).fill(0);for(let d=0;d<s;d++)r[d]=Bd(t[d]??"");for(let d of e)for(let l=0;l<s;l++){let u=d[l]??"",f=Bd(u);f>r[l]&&(r[l]=f)}let i=r.slice();if(n!==void 0){let d=Math.max(s*Sg,n-nC-(s-1)*sC);i=aC(r,d)}let o=(d,l,u)=>{let f=[],p=1;for(let h=0;h<s;h++){let y=d[h]??"",b=i[h],v=oC(rC(y),b);f.push(v),v.length>p&&(p=v.length)}let m=[];for(let h=0;h<p;h++){let y=[];for(let b=0;b<s;b++){let v=f[b][h]??"",S=i[b],x=Bd(v),T=du(v,u);y.push(T+" ".repeat(Math.max(0,S-x)))}m.push({prefix:" ",body:y.join(" \u2502 "),bodyStyle:l})}return m},a=[];a.push(...o(t,"heading-3",bg("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 kg(t,e){if(t.length===0||!Ld(t))return e.map(r=>({body:r,ansi:!1}));let n;try{n=Zx(e.join(`
109
+ `),{language:t,theme:cC,ignoreIllegals:!0})}catch{return e.map(r=>({body:r,ansi:!1}))}n=n.replace(/\x1b\[39m/g,"\x1B[37m");let s=n.split(`
110
+ `);return s.length!==e.length?e.map(r=>({body:r,ansi:!1})):s.map((r,i)=>({body:r,ansi:r!==e[i]}))}function uC(t){if(!t)return"";let e=t.split(/[\\/]/).pop()?.toLowerCase()??"";if(e==="dockerfile"||e.startsWith("dockerfile."))return Ld("dockerfile")?"dockerfile":"";if(e==="makefile"||e==="gnumakefile")return Ld("makefile")?"makefile":"";let n=e.lastIndexOf(".");if(n<0)return"";let s=e.slice(n),r=lC[s];return r&&Ld(r)?r:""}function au(t,e,n,s,r,i){let o=t.replace(/^\s+/,"").split(`
111
+ `),a=[];r&&a.push({prefix:"\u21B3 ",prefixStyle:"dim",body:`from ${r}`,bodyStyle:"dim"});for(let c of o){let d={prefix:e,prefixStyle:s??n,body:c,bodyStyle:n};i&&(d.fillRow=!0),a.push(d)}return a}function fC(t){return t<1024?`${t} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ln(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),s=e%60;if(n<60)return s===0?`${n}m`:`${n}m ${s}s`;let r=Math.floor(n/60),i=n%60;return i===0?`${r}h`:`${r}h ${i}m`}function Ig(t){if(t.length<=4096&&t.split(`
112
112
  `).length<=40)return{text:t,truncated:!1};let s=t.slice(0,4096),r=t.length>4096,i=s.split(`
113
113
  `);return i.length>40&&(s=i.slice(0,40).join(`
114
- `),r=!0),{text:s,truncated:r}}function $o(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,f=o.toLowerCase(),u=l.toLowerCase();(u.startsWith(`${f} `)||u.startsWith(`${f} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let m=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let h=t.locations?.[0]?.path??t.detailFull??"";(h.startsWith("/")||h.startsWith("~"))&&a.push({start:m,end:m+l.length,url:h})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Mn(l-t.startedAt)}`}let c={prefix:` ${Yx(t.status)} `,prefixStyle:Vx(t.status),body:o,bodyStyle:eC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:Ie(t.errorText),bodyStyle:"tool-status-fail"}),d}function cg(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
115
- `))e.push({prefix:" ",body:Ie(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:Ie(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
116
- `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=qx(r);if(i.length>0){let o=ag(i,s.map(a=>Ie(a)));for(let a of o){let c={prefix:" ",body:a.body,bodyStyle:"code",fillRow:!0};a.ansi&&(c.ansi=!0),e.push(c)}}else for(let o of s)e.push({prefix:" ",body:Ie(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function ug(t){lg=t>=0?t:0}function Xl(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${Wx(d)})`}else{let d=Jx(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${Ie(Ue(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=Zl(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...xs(c)),s.length>0&&s.unshift({body:""}),s}function fg(t){let e=tt(t.oldText).split(`
114
+ `),r=!0),{text:s,truncated:r}}function qo(t,e=Date.now()){let n=t.initialTitle,s=t.latestTitle,r=n.toLowerCase(),i=s.toLowerCase(),o;s===n||i.includes(r)?o=s:r.includes(i)?o=n:o=`${n} \xB7 ${s}`;let a=[];if(t.detail){let l=t.detail,u=o.toLowerCase(),f=l.toLowerCase();(f.startsWith(`${u} `)||f.startsWith(`${u} `))&&(l=l.slice(o.length).trimStart());let p=o.includes(l)||t.detailFull!==void 0&&o.includes(t.detailFull);if(l.length>0&&!p){let m=o.length+3;if(o=`${o} \xB7 ${l}`,l.startsWith("\u2026")){let h=t.locations?.[0]?.path??t.detailFull??"";(h.startsWith("/")||h.startsWith("~"))&&a.push({start:m,end:m+l.length,url:h})}}}if(t.startedAt!==void 0){let l=t.endedAt??e;o=`${o} \xB7 ${Ln(l-t.startedAt)}`}let c={prefix:` ${gC(t.status)} `,prefixStyle:yC(t.status),body:o,bodyStyle:kC(t.status)};a.length>0&&(c.links=a);let d=[c];return t.status==="failed"&&t.errorText&&d.push({prefix:" ",body:xe(t.errorText),bodyStyle:"tool-status-fail"}),d}function xg(t){if(t.editDiff!==void 0)return[];let e=[],n=t.detailFull??t.detail;if(n)for(let s of n.split(`
115
+ `))e.push({prefix:" ",body:xe(s),bodyStyle:"dim"});if(t.status==="failed"&&t.errorText&&e.push({prefix:" ",body:xe(t.errorText),bodyStyle:"tool-status-fail"}),t.resultText){let s=t.resultText.split(`
116
+ `),r=t.locations?.[0]?.path??t.detailFull??t.detail,i=uC(r);if(i.length>0){let o=kg(i,s.map(a=>xe(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:xe(o),bodyStyle:"dim"});t.resultTruncated&&e.push({prefix:" ",body:"\u2026 (truncated)",bodyStyle:"dim"})}return e}function Ag(t){Cg=t>=0?t:0}function cu(t,e,n={}){let s=[],r=t.oldRef!==void 0||t.newRef!==void 0,i;if(r){let d=(t.oldRef?.bytes??0)+(t.newRef?.bytes??0);i=` (~${fC(d)})`}else{let d=mC(t),l=[];d.added>0&&l.push(`+${d.added}`),d.removed>0&&l.push(`-${d.removed}`),i=l.length>0?` (${l.join(" ")})`:""}let o=d=>({prefix:" ",body:`${d?"\u25BE":"\u25B8"} Edited ${xe(ze(t.path))}${i}`,bodyStyle:"dim"});if(e==="edit")return t.path&&s.push(o(!1)),s;if(r)return t.path&&(s.push(o(!0)),s.push(n.deferredStatus==="error"?{prefix:" ",body:"\u26A0 failed to load diff",bodyStyle:"tool-status-fail"}:{prefix:" ",body:"\u22EF fetching diff\u2026",bodyStyle:"dim"}),s.unshift({body:""})),s;let a=lu(t,{maxLines:1/0});if(a.length===0)return t.path&&s.push(o(!1)),s;t.path&&s.push(o(!0));let c="```diff\n"+a+"\n```";return s.push(...Ls(c)),s.length>0&&s.unshift({body:""}),s}function Rg(t){let e=tt(t.oldText).split(`
117
117
  `),n=tt(t.newText).split(`
118
- `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function Jx(t){let{oldLines:e,newLines:n}=fg(t),s=0,r=0;for(let i of pg(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function sg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function Zl(t,e={}){let n=e.maxLines??zx,s=e.contextLines??lg,{oldLines:r,newLines:i}=fg(t),o=pg(r,i),a=[];if(Number.isFinite(s)){if(!o.some(u=>u.op!=="="))return"";let l=new Array(o.length).fill(!1);for(let u=0;u<o.length;u++)if(o[u].op!=="="){let p=Math.max(0,u-s),m=Math.min(o.length-1,u+s);for(let h=p;h<=m;h++)l[h]=!0}let f=0;for(;f<o.length;){if(l[f]){a.push(sg(o[f])),f++;continue}let u=f;for(;u<o.length&&!l[u];)u++;let p=u-f;a.push(` \u22EF ${p} unchanged line${p===1?"":"s"}`),f=u}}else for(let d of o)a.push(sg(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let f=a.length-d;c.push(`\u2026 ${f} more line${f===1?"":"s"}`);break}c.push(a[d])}return c.join(`
119
- `)}function pg(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...Kx(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function Kx(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function eu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function Yx(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function Vx(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function mg(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...xs(t.plan));let n=t.status;if(n!==void 0){let s=Gx(n);s!==null&&e.push(s)}return e}function Gx(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function Xx(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function Zx(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:c,end:d}=Xx(t.entries,e),l=d-c<a,f="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let m=a-p;f=m===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${m} left`}let u=[{prefix:"\u25A3 ",prefixStyle:o,body:f,bodyStyle:o}];for(let p=c;p<d;p++){let m=t.entries[p];if(!m)continue;let h=m.status??"pending",w=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",b=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=m.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=Ql(v,_x(b));u.push({prefix:" ",body:`${w} ${S}`,bodyStyle:b})}return u}function eC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var og,Ox,Fx,We,Ux,jx,zx,lg,Qx,Ri=K(()=>{"use strict";pe();ys();og=6,Ox=2,Fx=3;We=new Px.Instance({level:3}),Ux={keyword:We.blueBright,built_in:We.cyan,type:We.cyanBright,literal:We.blue,number:We.greenBright,string:We.yellow,regexp:We.red,comment:We.gray,function:We.yellow,title:We.yellow,class:We.yellowBright,attr:We.cyan,attribute:We.cyan,variable:We.white,params:We.white,meta:We.magenta,symbol:We.magenta,addition:We.greenBright,deletion:We.redBright,section:We.cyan,tag:We.cyan,name:We.cyanBright};jx={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".kts":"kotlin",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"csharp",".swift":"swift",".m":"objectivec",".mm":"objectivec",".php":"php",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".ps1":"powershell",".sql":"sql",".html":"xml",".htm":"xml",".xml":"xml",".svg":"xml",".css":"css",".scss":"scss",".sass":"scss",".less":"less",".yaml":"yaml",".yml":"yaml",".toml":"ini",".ini":"ini",".md":"markdown",".markdown":"markdown",".lua":"lua",".pl":"perl",".pm":"perl",".r":"r",".dart":"dart",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".clj":"clojure",".cljs":"clojure",".vim":"vim",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".el":"lisp"};zx=40,lg=Number.POSITIVE_INFINITY;Qx=5});import{highlight as tC,supportsLanguage as nC}from"cli-highlight";async function gg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
120
- `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Ee(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Ee(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=ln(d)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
121
- `),process.exit(1)}let f=di(l.history);r=e.fold===!0?f.map(u=>({...u,hunks:ci(u.hunks)})):f}else process.stderr.write(`Daemon returned HTTP ${s.status}
118
+ `);return e.length>0&&e[e.length-1]===""&&e.pop(),n.length>0&&n[n.length-1]===""&&n.pop(),{oldLines:e,newLines:n}}function mC(t){let{oldLines:e,newLines:n}=Rg(t),s=0,r=0;for(let i of Tg(e,n))i.op==="+"?s++:i.op==="-"&&r++;return{added:s,removed:r}}function wg(t){return t.op==="="?` ${t.text}`:t.op==="-"?`- ${t.text}`:`+ ${t.text}`}function lu(t,e={}){let n=e.maxLines??pC,s=e.contextLines??Cg,{oldLines:r,newLines:i}=Rg(t),o=Tg(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),m=Math.min(o.length-1,f+s);for(let h=p;h<=m;h++)l[h]=!0}let u=0;for(;u<o.length;){if(l[u]){a.push(wg(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(wg(d));let c=[];for(let d=0;d<a.length;d++){if(c.length>=n-1&&d<a.length-1){let u=a.length-d;c.push(`\u2026 ${u} more line${u===1?"":"s"}`);break}c.push(a[d])}return c.join(`
119
+ `)}function Tg(t,e){let n=0,s=Math.min(t.length,e.length);for(;n<s&&t[n]===e[n];)n++;let r=t.length,i=e.length;for(;r>n&&i>n&&t[r-1]===e[i-1];)r--,i--;let o=[];for(let a=0;a<n;a++)o.push({op:"=",text:t[a]});o.push(...hC(t.slice(n,r),e.slice(n,i)));for(let a=r;a<t.length;a++)o.push({op:"=",text:t[a]});return o}function hC(t,e){let n=t.length,s=e.length;if(n===0||s===0){let c=[];for(let d of t)c.push({op:"-",text:d});for(let d of e)c.push({op:"+",text:d});return c}let r=Array.from({length:n+1},()=>new Array(s+1).fill(0));for(let c=n-1;c>=0;c--)for(let d=s-1;d>=0;d--)t[c]===e[d]?r[c][d]=r[c+1][d+1]+1:r[c][d]=Math.max(r[c+1][d],r[c][d+1]);let i=[],o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(i.push({op:"=",text:t[o]}),o++,a++):r[o+1][a]>=r[o][a+1]?(i.push({op:"-",text:t[o]}),o++):(i.push({op:"+",text:e[a]}),a++);for(;o<n;)i.push({op:"-",text:t[o]}),o++;for(;a<s;)i.push({op:"+",text:e[a]}),a++;return i}function uu(t){switch(t){case"completed":case"succeeded":case"ok":case"failed":case"error":case"rejected":case"cancelled":return!0;default:return!1}}function gC(t){switch(t){case"completed":case"succeeded":case"ok":return"\u2713";case"failed":case"error":return"\u2717";case"rejected":return"\u2298";case"cancelled":return"\u229D";default:return"\u25D0"}}function yC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"cancelled":return"tool-status-cancelled";default:return"tool-status-running"}}function Eg(t){let e=[{prefix:"\u25A3 ",prefixStyle:"plan",body:"Plan",bodyStyle:"plan"}];e.push(...Ls(t.plan));let n=t.status;if(n!==void 0){let s=wC(n);s!==null&&e.push(s)}return e}function wC(t){switch(t){case"completed":case"succeeded":case"ok":return{prefix:" ",body:"\u2713 Approved",bodyStyle:"tool-status-ok"};case"failed":case"error":case"rejected":return{prefix:" ",body:"\u2717 Rejected",bodyStyle:"tool-status-fail"};case"cancelled":return{prefix:" ",body:"\u229D Cancelled",bodyStyle:"tool-status-cancelled"};case"pending":case"in_progress":case"running":case"updated":return{prefix:" ",body:"awaiting approval\u2026",bodyStyle:"dim"};default:return null}}function vC(t,e){let n=t.length;if(e<=0||n<=e)return{start:0,end:n};let s=t.findIndex(d=>(d.status??"pending")==="in_progress"),r=t.findIndex(d=>(d.status??"pending")==="pending"),i=s>=0?s:r>=0?r:n-1,o=Math.floor((e-1)/2),a=Math.max(0,i-o),c=Math.min(n,a+e);return c-a<e&&(a=Math.max(0,c-e)),{start:a,end:c}}function SC(t,e){let n=t.stopped===!0,r=t.amended===!0?"tool-status-cancelled":"tool-status-fail",o=t.entries.every(p=>(p.status??"pending")==="completed")?"plan-done":n?r:"plan",a=t.entries.length,{start:c,end:d}=vC(t.entries,e),l=d-c<a,u="Plan";if(l){let p=0;for(let h of t.entries)(h.status??"pending")==="completed"&&(p+=1);let m=a-p;u=m===0?`Plan \xB7 ${p} done`:`Plan \xB7 ${p} done \xB7 ${m} left`}let f=[{prefix:"\u25A3 ",prefixStyle:o,body:u,bodyStyle:o}];for(let p=c;p<d;p++){let m=t.entries[p];if(!m)continue;let h=m.status??"pending",y=h==="completed"?"[x]":h==="in_progress"?"[~]":"[ ]",b=h==="completed"?"plan-done":h==="in_progress"?n?"plan-pending":"plan":"plan-pending",v=m.content.replace(/^\d+\/\d+\s+/,"").replace(/\s*\(?\d+\/\d+\)?\s*$/,""),S=du(v,eC(b));f.push({prefix:" ",body:`${y} ${S}`,bodyStyle:b})}return f}function kC(t){switch(t){case"completed":case"succeeded":case"ok":return"tool-status-ok";case"failed":case"error":case"rejected":return"tool-status-fail";case"in_progress":case"running":case"updated":return"tool-status-running";case"cancelled":return"tool-status-cancelled";default:return"tool-status-pending"}}var Sg,nC,sC,Ve,cC,lC,pC,Cg,bC,Ni=K(()=>{"use strict";he();Es();Sg=6,nC=2,sC=3;Ve=new Xx.Instance({level:3}),cC={keyword:Ve.blueBright,built_in:Ve.cyan,type:Ve.cyanBright,literal:Ve.blue,number:Ve.greenBright,string:Ve.yellow,regexp:Ve.red,comment:Ve.gray,function:Ve.yellow,title:Ve.yellow,class:Ve.yellowBright,attr:Ve.cyan,attribute:Ve.cyan,variable:Ve.white,params:Ve.white,meta:Ve.magenta,symbol:Ve.magenta,addition:Ve.greenBright,deletion:Ve.redBright,section:Ve.cyan,tag:Ve.cyan,name:Ve.cyanBright};lC={".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"};pC=40,Cg=Number.POSITIVE_INFINITY;bC=5});import{highlight as IC,supportsLanguage as xC}from"cli-highlight";async function Mg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp session diff <session-id> [--json] [--no-color]
120
+ `),process.exit(2));let n=e.fold===!0?"?fold=true":"",s=await Fe(`/v1/sessions/${encodeURIComponent(t)}/diff${n}`),r;if(s.ok)r=s.body;else if(s.status===404){let d=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,l;try{l=gn(d)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
121
+ `),process.exit(1)}let u=bi(l.history);r=e.fold===!0?u.map(f=>({...f,hunks:vi(f.hunks)})):u}else process.stderr.write(`Daemon returned HTTP ${s.status}
122
122
  `),process.exit(1);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
123
- `);return}let i=kd({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(tu(r,a)),await i.flush()}function tu(t,e){if(t.length===0)return`No file edits found in this session.
124
- `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=iC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
125
- `:n.join("")}function sC(t){let e=[];for(let n of t.hunks){let s=Zl(n,{maxLines:1/0});rC(s)&&e.push({body:s,oldCount:hg(n.oldText),newCount:hg(n.newText)})}return e}function rC(t){if(t.length===0)return!1;for(let e of t.split(`
126
- `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function iC(t,e){let n=sC(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
123
+ `);return}let i=Od({disabled:e.noPager===!0}),o=process.stdout.isTTY===!0,a=!e.noColor&&o;i.stream.write(fu(r,a)),await i.flush()}function fu(t,e){if(t.length===0)return`No file edits found in this session.
124
+ `;let n=[],s=[...t].sort((r,i)=>r.path.localeCompare(i.path));for(let r of s){let i=RC(r,e);i!==null&&n.push(i)}return n.length===0?`No file edits found in this session.
125
+ `:n.join("")}function CC(t){let e=[];for(let n of t.hunks){let s=lu(n,{maxLines:1/0});AC(s)&&e.push({body:s,oldCount:Pg(n.oldText),newCount:Pg(n.newText)})}return e}function AC(t){if(t.length===0)return!1;for(let e of t.split(`
126
+ `))if(e.startsWith("+ ")||e.startsWith("- "))return!0;return!1}function RC(t,e){let n=CC(t);if(n.length===0)return null;let s=[];s.push(`diff --hydra a/${t.path} b/${t.path}`),t.created?(s.push("new file"),s.push("--- /dev/null"),s.push(`+++ b/${t.path}`)):(s.push(`--- a/${t.path}`),s.push(`+++ b/${t.path}`));let r=n.length;n.forEach((o,a)=>{let c=o.oldCount===0?0:1,d=o.newCount===0?0:1,l=r>1?` edit ${a+1} of ${r}`:"";s.push(`@@ -${c},${o.oldCount} +${d},${o.newCount} @@${l}`),s.push(o.body)});let i=s.join(`
127
127
  `)+`
128
128
 
129
- `;return!e||!nC("diff")?i:tC(i,{language:"diff"})}function hg(t){if(t.length===0)return 0;let e=t.split(`
130
- `);return e[e.length-1]===""&&e.pop(),e.length}var nu=K(()=>{"use strict";Ss();or();ed();Ri();Vl()});async function yg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
131
- `),process.exit(2));let n=await Ee(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Ee(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=ln(i)}catch(u){process.stderr.write(`Failed to decode session bundle: ${u.message}
132
- `),process.exit(1)}let a=iu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let u=di(o.history);d=e.fold===!0?u.map(p=>({...p,hunks:ci(p.hunks)})):u}if(e.json){let u={...a};d!==null&&(u.diff=d),process.stdout.write(JSON.stringify(u,null,2)+`
133
- `);return}let l=process.stdout.isTTY===!0,f=!e.noColor&&l;if(c){let u=kd({disabled:e.noPager===!0});u.stream.write(Ad(a,e.verbose===!0)),u.stream.write(`
134
- `),u.stream.write(tu(d??[],f)),await u.flush();return}process.stdout.write(Ad(a,e.verbose===!0))}function iu(t,e){let n=t.session,s=t.history,r=sm(s),i=al(s),o=dl(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function Ad(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${aC(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,f)=>l+f.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,su),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>su&&n.push(` ... ${t.tools.length-su} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>oC.has(l.name)),d=c.reduce((l,f)=>l+f.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,ru),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let f=l.byTool.map(u=>`${u.name}\xD7${u.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${f})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>ru&&n.push(` ... ${o.length-ru} more (use --verbose to see all)`)}return n.join(`
129
+ `;return!e||!xC("diff")?i:IC(i,{language:"diff"})}function Pg(t){if(t.length===0)return 0;let e=t.split(`
130
+ `);return e[e.length-1]===""&&e.pop(),e.length}var pu=K(()=>{"use strict";$s();yr();pd();Ni();ou()});async function _g(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions info <session-id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]
131
+ `),process.exit(2));let n=await Fe(`/v1/sessions/${encodeURIComponent(t)}`,{expectStatus:[200,404]}),s=n.status===200?n.body.status:void 0,i=(await Fe(`/v1/sessions/${encodeURIComponent(t)}/export`,{expectStatus:200})).body,o;try{o=gn(i)}catch(f){process.stderr.write(`Failed to decode session bundle: ${f.message}
132
+ `),process.exit(1)}let a=gu(o,s??"cold"),c=e.diff===!0,d=null;if(c){let f=bi(o.history);d=e.fold===!0?f.map(p=>({...p,hunks:vi(p.hunks)})):f}if(e.json){let f={...a};d!==null&&(f.diff=d),process.stdout.write(JSON.stringify(f,null,2)+`
133
+ `);return}let l=process.stdout.isTTY===!0,u=!e.noColor&&l;if(c){let f=Od({disabled:e.noPager===!0});f.stream.write(Dd(a,e.verbose===!0)),f.stream.write(`
134
+ `),f.stream.write(fu(d??[],u)),await f.flush();return}process.stdout.write(Dd(a,e.verbose===!0))}function gu(t,e){let n=t.session,s=t.history,r=wm(s),i=wl(s),o=bl(s),a=n.currentUsage,c=Date.parse(n.createdAt),d=Date.parse(n.updatedAt),l=Number.isFinite(c)&&Number.isFinite(d)?d-c:null;return{sessionId:n.sessionId,...n.upstreamSessionId!==void 0?{upstreamSessionId:n.upstreamSessionId}:{},...n.title!==void 0?{title:n.title}:{},cwd:n.cwd,agentId:n.agentId,...n.currentModel!==void 0?{currentModel:n.currentModel}:{},status:e,createdAt:n.createdAt,updatedAt:n.updatedAt,synopsis:n.synopsis??null,summarizedThroughEntry:n.summarizedThroughEntry??null,turns:r,tools:i,files:o,cost:{amount:a?.costAmount??null,currency:a?.costCurrency??null,cumulative:a?.cumulativeCost??null,inputTokens:a?.used??null,outputTokens:a?.size??null},duration:{totalMs:l},historyEntries:s.length}}function Dd(t,e){let n=[],s=a=>a.padEnd(14);n.push(`${s("Session:")}${t.sessionId}`),t.upstreamSessionId&&n.push(`${s("Upstream:")}${t.upstreamSessionId}`),t.title&&n.push(`${s("Title:")}${t.title}`),n.push(`${s("Cwd:")}${t.cwd}`);let r=t.currentModel?` \xB7 ${t.currentModel}`:"";n.push(`${s("Agent:")}${t.agentId}${r}`),n.push(`${s("Status:")}${t.status}`),n.push(`${s("Created:")}${t.createdAt}`),n.push(`${s("Last active:")}${t.updatedAt}`),t.duration.totalMs!==null&&n.push(`${s("Duration:")}${EC(t.duration.totalMs)}`),n.push(`${s("Turns:")}${t.turns}`);let i=[];if(t.cost.amount!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.amount.toFixed(4)}`)}else if(t.cost.cumulative!==null){let a=t.cost.currency??"USD";i.push(`${a} ${t.cost.cumulative.toFixed(4)} (cumulative)`)}if(t.cost.inputTokens!==null||t.cost.outputTokens!==null){let a=[];t.cost.inputTokens!==null&&a.push(`${t.cost.inputTokens.toLocaleString()} in`),t.cost.outputTokens!==null&&a.push(`${t.cost.outputTokens.toLocaleString()} out`),i.push(a.join(" / "))}if(i.length>0&&n.push(`${s("Cost:")}${i.join(" | ")}`),t.synopsis){n.push(""),n.push("Synopsis:");let a=" ",c=d=>d.padEnd(22);if(t.synopsis.goal&&n.push(`${a}${c("Goal:")}${t.synopsis.goal}`),t.synopsis.outcome&&n.push(`${a}${c("Outcome:")}${t.synopsis.outcome}`),t.synopsis.rejected_approaches&&t.synopsis.rejected_approaches.length>0){n.push(`${a}${c("Rejected approaches:")}`);for(let d of t.synopsis.rejected_approaches)n.push(`${a} - ${d}`)}if(t.synopsis.open_threads&&t.synopsis.open_threads.length>0){n.push(`${a}${c("Open threads:")}`);for(let d of t.synopsis.open_threads)n.push(`${a} - ${d}`)}if(t.synopsis.files_touched&&t.synopsis.files_touched.length>0){n.push(`${a}${c("Files touched:")}`);for(let d of t.synopsis.files_touched)n.push(`${a} - ${d}`)}if(t.synopsis.tools_used&&t.synopsis.tools_used.length>0){n.push(`${a}${c("Tools used:")}`);for(let d of t.synopsis.tools_used)n.push(`${a} - ${d}`)}}else n.push(""),n.push("Synopsis: (none yet \u2014 generated on idle-close or daemon shutdown)");if(t.tools.length>0){n.push("");let a=t.tools.reduce((l,u)=>l+u.count,0);n.push(`Tools (${a} calls):`);let c=e?t.tools:t.tools.slice(0,mu),d=Math.max(...c.map(l=>l.name.length),4);for(let l of c)n.push(` ${l.name.padEnd(d)} ${l.count}`);!e&&t.tools.length>mu&&n.push(` ... ${t.tools.length-mu} more (use --verbose to see all)`)}let o=e?t.files:t.files.map(a=>{let c=a.byTool.filter(l=>TC.has(l.name)),d=c.reduce((l,u)=>l+u.count,0);return{path:a.path,count:d,byTool:c}}).filter(a=>a.count>0);if(o.length>0){n.push("");let a=e?"Files touched":"Files edited";n.push(`${a} (${o.length}):`);let c=e?o:o.slice(0,hu),d=Math.max(...c.map(l=>l.path.length),4);for(let l of c)if(e){let u=l.byTool.map(f=>`${f.name}\xD7${f.count}`).join(", ");n.push(` ${l.path.padEnd(d)} ${l.count} (${u})`)}else n.push(` ${l.path.padEnd(d)} ${l.count}`);!e&&o.length>hu&&n.push(` ... ${o.length-hu} more (use --verbose to see all)`)}return n.join(`
135
135
  `)+`
136
- `}function aC(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var su,ru,oC,ou=K(()=>{"use strict";Ss();or();cl();ed();Vl();nu();su=10,ru=15,oC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var Ed,Yn,Ei,Oo,Wg,Fo,uu,Pd,mr,zg,hr,Jg,gr,Kg,yr,Pi,Mi,Yg,_i,Vg,Gg,Qg,fu,Xg,Md,Zg,ey,Lo=K(()=>{"use strict";Ed="\x1B[?2004h",Yn="\x1B[?2004l",Ei="\x1B[200~",Oo="\x1B[201~",Wg="\x1B[?1049l",Fo="\x1B[?7h",uu="\x1B[?7l",Pd="\x1B[?25h",mr="\x1B[?1l",zg="\x1B[>1u",hr="\x1B[<u",Jg="\x1B[>4;2m",gr="\x1B[>4;0m",Kg="\x1B[>5;1m",yr="\x1B[>5;0m",Pi="\x1B[?1000l",Mi="\x1B[?1002l",Yg="\x1B[?1003l",_i="\x1B[?1006l",Vg="\x1B[?1015l",Gg="\x1B[?w",Qg="\x1B[=24;1w",fu="\x1B[=0;0w",Xg="\x1B]22;pointer\x07",Md="\x1B]22;default\x07",Zg="\x1B[?2026h",ey="\x1B[?2026l"});function Vn(){process.stdout.write(hr),process.stdout.write(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(Pi),process.stdout.write(Mi),process.stdout.write(_i),process.stdout.write(mr),process.stdout.write("\x1B>")}function fn(t){return t.width??80}function wr(t){return t.height??24}function Gn(t,e){let n=fn(t),s=wr(t),r=e.contentWidth??cC,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),f=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let u=ty.repeat(a-2),p=mC(u,e.title);t.moveTo(l,f),t.dim.noFormat(lC),hC(t,p),t.dim.noFormat(uC);for(let m=1;m<=c;m++)t.moveTo(l,f+m),t.dim.noFormat(ny),t.moveTo(l+a-1,f+m),t.dim.noFormat(ny);return t.moveTo(l,f+d-1),t.dim.noFormat(fC+ty.repeat(a-2)+pC),{x:l,y:f,w:a,h:d,contentX:l+1,contentY:f+1,contentW:o,contentH:c}}function mC(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function hC(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function nt(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function _d(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Cs(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(u,p,m)=>{a||s(u,p,m,f)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},f=u=>{l(),o(u)};e.grabInput({}),e.on("key",d),e.on("resize",c)})}var cC,ty,ny,lC,uC,fC,pC,Oi=K(()=>{"use strict";Lo();cC=64,ty="\u2500",ny="\u2502",lC="\u250C",uC="\u2510",fC="\u2514",pC="\u2518"});function sy(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function wC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??gC,footer:yC};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${sy(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function bC(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function vC(t){return typeof t!="object"||t===null?!1:t.code===z.AuthRequired}function ry(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[mt];if(!(typeof s!="object"||s===null))return s}function SC(t){let e=ry(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function kC(t){let e=ry(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function iy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!vC(e))throw e;let n=SC(e)??t.fallbackAgentId??"",s=kC(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function IC(t,e,n){t.grabInput(!1),Vn(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
136
+ `}function EC(t){if(t<0)return"0s";let e=Math.floor(t/1e3),n=Math.floor(e/86400),s=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,o=[];return n>0&&o.push(`${n}d`),s>0&&o.push(`${s}h`),r>0&&o.push(`${r}m`),(o.length===0||i>0)&&o.push(`${i}s`),o.join(" ")}var mu,hu,TC,yu=K(()=>{"use strict";$s();yr();vl();pd();ou();pu();mu=10,hu=15,TC=new Set(["Edit","MultiEdit","Write","NotebookEdit"])});var jd,ns,Hi,Wo,iy,zo,ku,qd,Cr,oy,Ar,ay,Rr,dy,Tr,Ui,ji,cy,qi,ly,uy,fy,Iu,py,Wd,my,hy,Jo=K(()=>{"use strict";jd="\x1B[?2004h",ns="\x1B[?2004l",Hi="\x1B[200~",Wo="\x1B[201~",iy="\x1B[?1049l",zo="\x1B[?7h",ku="\x1B[?7l",qd="\x1B[?25h",Cr="\x1B[?1l",oy="\x1B[>1u",Ar="\x1B[<u",ay="\x1B[>4;2m",Rr="\x1B[>4;0m",dy="\x1B[>5;1m",Tr="\x1B[>5;0m",Ui="\x1B[?1000l",ji="\x1B[?1002l",cy="\x1B[?1003l",qi="\x1B[?1006l",ly="\x1B[?1015l",uy="\x1B[?w",fy="\x1B[=24;1w",Iu="\x1B[=0;0w",py="\x1B]22;pointer\x07",Wd="\x1B]22;default\x07",my="\x1B[?2026h",hy="\x1B[?2026l"});function ss(){process.stdout.write(Ar),process.stdout.write(ns),process.stdout.write(Rr),process.stdout.write(Tr),process.stdout.write(Ui),process.stdout.write(ji),process.stdout.write(qi),process.stdout.write(Cr),process.stdout.write("\x1B>")}function yn(t){return t.width??80}function Er(t){return t.height??24}function rs(t,e){let n=yn(t),s=Er(t),r=e.contentWidth??MC,i=Math.max(10,n-4),o=Math.min(r,i),a=o+2,c=Math.max(1,Math.min(e.contentHeight,s-4)),d=c+2,l=Math.max(1,Math.floor((n-a)/2)+1),u=Math.max(1,Math.floor((s-d)/2)+1);t.moveTo(1,1).eraseDisplayBelow();let f=gy.repeat(a-2),p=LC(f,e.title);t.moveTo(l,u),t.dim.noFormat(_C),BC(t,p),t.dim.noFormat($C);for(let m=1;m<=c;m++)t.moveTo(l,u+m),t.dim.noFormat(yy),t.moveTo(l+a-1,u+m),t.dim.noFormat(yy);return t.moveTo(l,u+d-1),t.dim.noFormat(FC+gy.repeat(a-2)+OC),{x:l,y:u,w:a,h:d,contentX:l+1,contentY:u+1,contentW:o,contentH:c}}function LC(t,e){if(!e)return{dashes:t};let n=` ${e} `;if(n.length+4>t.length)return{dashes:t};let s=2;return{dashes:t.slice(0,s)+" ".repeat(n.length)+t.slice(s+n.length),title:{offset:s,text:n}}}function BC(t,e){if(!e.title){t.dim.noFormat(e.dashes);return}t.dim.noFormat(e.dashes.slice(0,e.title.offset)),t.brightCyan.noFormat(e.title.text),t.dim.noFormat(e.dashes.slice(e.title.offset+e.title.text.length))}function nt(t,e){return e<=1?"":t.length<=e?t:t.slice(0,Math.max(0,e-1))+"\u2026"}function zd(t,e){return t.length>=e?t.slice(0,e):t+" ".repeat(e-t.length)}async function Bs(t){let{term:e,render:n,onKey:s,onResize:r}=t,i=t.hideCursor!==!1;return n(),i&&e.hideCursor(),await new Promise(o=>{let a=!1,c=()=>{a||(r??n)()},d=(f,p,m)=>{a||s(f,p,m,u)},l=()=>{a||(a=!0,e.off("key",d),e.off("resize",c),e.grabInput(!1),e.hideCursor(!1),e.moveTo(1,1).eraseDisplayBelow())},u=f=>{l(),o(f)};e.grabInput({}),e.on("key",d),e.on("resize",c)})}var MC,gy,yy,_C,$C,FC,OC,zi=K(()=>{"use strict";Jo();MC=64,gy="\u2500",yy="\u2502",_C="\u250C",$C="\u2510",FC="\u2514",OC="\u2518"});function wy(t){let e=(t.name&&t.name.length>0?t.name:void 0)??(t.description&&t.description.length>0?t.description:void 0);return e?`${e} (${t.id})`:t.id}function HC(t,e,n){let s={title:`Agent "${t}" needs to be set up`,description:e?.description??NC,footer:DC};if(e?.command&&(s.command=e.command),e?.url&&(s.url=e.url),n&&n.length>0){s.authMethods=n;let r=n.map((c,d)=>({index:d,label:`[${d+1}] ${wy(c)}`,method:c}));s.methodLines=r;let i=Math.min(n.length,9),o=i===1?"[1]":`[1\u2026${i}]`,a=n.length===1?" \xB7 [Enter] choose":"";s.footer=`${o} choose method${a} \xB7 [r] retry \xB7 [Esc] back`}return s}function UC(t,e,n=0){if(t==="CTRL_C"||t==="CTRL_D")return{kind:"cancel"};if(t==="ESCAPE")return{kind:"back"};if(t==="ENTER"||t==="KP_ENTER")return n===1?{kind:"selectMethod",index:0}:{kind:"retry"};if(e?.isCharacter&&/^[1-9]$/.test(t)){let s=Number(t)-1;return s<n?{kind:"selectMethod",index:s}:{kind:"ignore"}}return e?.isCharacter&&t.toLowerCase()==="r"?{kind:"retry"}:{kind:"ignore"}}function jC(t){return typeof t!="object"||t===null?!1:t.code===W.AuthRequired}function by(t){if(typeof t!="object"||t===null)return;let e=t.data;if(typeof e!="object"||e===null)return;let n=e._meta;if(typeof n!="object"||n===null)return;let s=n[ht];if(!(typeof s!="object"||s===null))return s}function qC(t){let e=by(t);if(!e)return;let n=e.agentId;return typeof n=="string"?n:void 0}function WC(t){let e=by(t);if(!e)return;let n=e.authMethods;if(!Array.isArray(n))return;let s=[];for(let r of n){if(typeof r!="object"||r===null)continue;let i=r.id;if(typeof i!="string"||i.length===0)continue;let o=r.description,a=r.type,c=r.name,d=r._meta,l={id:i,description:typeof o=="string"?o:""};(a==="agent"||a==="terminal")&&(l.type=a),typeof c=="string"&&(l.name=c),d!==null&&typeof d=="object"&&!Array.isArray(d)&&(l._meta=d),s.push(l)}return s.length>0?s:void 0}async function vy(t){for(;;)try{return{kind:"ok",result:await t.request()}}catch(e){if(!jC(e))throw e;let n=qC(e)??t.fallbackAgentId??"",s=WC(e),r=await t.resolveOnboarding(n),i=await t.showBanner(n,r,s);if(i==="back")return{kind:"back"};if(i==="cancel")return{kind:"cancel"}}}async function zC(t,e,n){t.grabInput(!1),ss(),t.moveTo(1,1).eraseDisplayBelow();let s=`\u2500 Running ${e.command} ${e.args.join(" ")} \u2014 finish setup, then return to hydra \u2500`;process.stdout.write(s+`
137
137
  `);let r=n?.spawn??(await import("child_process")).spawn;return await new Promise(i=>{let o=()=>{try{t.grabInput({})}catch{}};try{let a=r(e.command,e.args,{stdio:"inherit",env:e.env,cwd:e.cwd});a.on("exit",c=>{o(),i({exitCode:c})}),a.on("error",c=>{o(),process.stdout.write(`
138
138
  failed to spawn ${e.command}: ${c.message}
139
139
  `),i({exitCode:-1})})}catch(a){o(),process.stdout.write(`
140
140
  failed to spawn ${e.command}: ${a.message}
141
- `),i({exitCode:-1})}})}function xC(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function pu(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(xC(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function oy(t,e,n,s,r){Vn();let i=wC(e,n,s),o=!1,a,c,d=()=>{let f=4;i.command&&f++,i.url&&f++,i.methodLines&&(f+=1+i.methodLines.length),a&&f++,c&&f++;let u=Gn(t,{contentHeight:f,contentWidth:80,title:"Authentication required"}),p=u.contentW,m=0;if(a&&(t.moveTo(u.contentX,u.contentY+m),t.brightYellow.noFormat(nt(` ${a}`,p)),m++),c&&(t.moveTo(u.contentX,u.contentY+m),t.brightRed.noFormat(nt(` ${c}`,p)),m++),t.moveTo(u.contentX,u.contentY+m),t.brightWhite.bold.noFormat(nt(` ${i.title}`,p)),m+=2,t.moveTo(u.contentX,u.contentY+m),t.noFormat(nt(` ${i.description}`,p)),m++,i.command&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(nt(i.command,p-7)),m++),i.url&&(t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(nt(i.url,p-7)),m++),i.methodLines){t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" Methods reported by the agent:"),m++;for(let h of i.methodLines)t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(" "),t.noFormat(nt(h.label,p-3)),m++}return m++,t.moveTo(u.contentX,u.contentY+m),t.dim.noFormat(` ${i.footer}`),u},l=i.methodLines?.length??0;return Cs({term:t,render:()=>{d()},onKey:(f,u,p,m)=>{if(o)return;let h=bC(f,p,l);if(h.kind!=="ignore"){if(h.kind==="retry"||h.kind==="back"||h.kind==="cancel"){m(h.kind);return}if(h.kind==="selectMethod"){let w=i.methodLines?.[h.index]?.method;if(!w||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${sy(w)}\u2026`,d();let b=r.runTerminalAuth??(v=>IC(t,v));(async()=>{let v=await pu(w,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){m("terminal-completed");return}if(v.kind==="retry"){m("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var gC,yC,mu=K(()=>{"use strict";wa();va();Oi();gC="This agent requires authentication before use.",yC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as uy}from"timers/promises";function $C(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var EC,PC,MC,_C,Fi,hu=K(()=>{"use strict";Eo();fi();EC=200,PC=5e3,MC=2,_C=60,Fi=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current||this.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),uy(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=EC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await ur(s,this.opts.subprotocols);this.bindStream(Tn(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=_C)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await uy(n),this.destroyed)return;n=Math.min(n*MC,PC)}}bindStream(e){this.current=e,e.onMessage(n=>{if($C(n)&&n.id!==null){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}async flushQueue(){if(!this.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(n){this.scheduleReconnect(n);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
142
- `)}}});function fy(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function br(t){return{outcome:{outcome:"selected",optionId:fy(t,["allow_once","allow_always"])}}}function py(t){return{outcome:{outcome:"selected",optionId:fy(t,["reject_once","reject_always"])}}}function Fd(t){return t&&typeof t=="object"?t:void 0}function Bo(t){return typeof t=="string"&&t.length>0?t:void 0}function my(t){let e=Fd(t),n=Fd(e?.toolCall),s={paths:[]};if(!n)return s;let r=Bo(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Bo(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(Fd(d)?.path);let c=Fd(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Bo(c.command);d&&(s.command=d);let l=Bo(c.url);l&&(s.url=l);let f=Bo(c.description);f&&(s.description=f)}return s}function hy(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var Ld=K(()=>{"use strict"});function _A(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Oy(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function $A(t,e){let n=Oy(t),s=Oy(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function No(){if(Rs!==void 0)return Rs;if(_A())return Rs=null,Rs;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Fy,version:fe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&$A(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Rs={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Rs=null}}catch{Rs=null}return Rs}function Do(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Fy}`}var Fy,Rs,wu=K(()=>{"use strict";Nt();Fy="@hydra-acp/cli"});import*as Ho from"fs/promises";import*as bu from"path";async function Uo(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=bu.resolve(je(e)),s;try{s=await Ho.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function Ly(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await Ho.stat(r)).isDirectory())return r}catch{}return null}async function By(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=bu.resolve(je(r)),o;try{o=(await Ho.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var vu=K(()=>{"use strict";Ne()});import{EventEmitter as OA}from"events";import{WebSocket as FA}from"ws";function LA(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=so(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new FA(t,e,n),o=()=>{i.off("error",a),s(Tn(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function Ny(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??LA,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new Pt(d),f;try{try{await l.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-sidechain"}})}catch{}if(s.reuseSessionId!==void 0)f=s.reuseSessionId;else{let h=n.replace(/\s+/g," ").trim().slice(0,60);f=(await yd(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}}catch(h){throw d.close().catch(()=>{}),h}let u=new Su(l,d,f,t,o),p=!1,m=h=>{p||(p=!0,u.emit("event",h),d.close().catch(()=>{}))};l.onNotification("session/update",h=>{let w=h?.update;w!==void 0&&u.emit("event",{kind:"update",update:w})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:f,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw d.close().catch(()=>{}),Pn(t,f,o).catch(()=>{}),h}r(u),setImmediate(()=>{l.request("session/prompt",{sessionId:f,prompt:[{type:"text",text:n}],_meta:{[mt]:{ancillary:!0}}}).then(h=>{let w=h&&typeof h=="object"?h.stopReason:void 0;m(w==="cancelled"?{kind:"cancelled"}:w==="error"||w==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var Su,Dy=K(()=>{"use strict";ro();Po();sr();fi();It();Su=class extends OA{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),Pn(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var ku,Ud,Hy=K(()=>{"use strict";Ri();ys();ku=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},Ud=class extends ku{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=Rn(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=Ai(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Ai(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=$o(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=$o(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=Is(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return xs(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this._pendingThoughtText=null,this._pendingThoughtRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function NA(t,e){return`[pasted #${t} +${e} lines]`}var BA,jd,Iu,DA,Qn,xu=K(()=>{"use strict";BA=/\[pasted #(\d+) \+\d+ lines\]/g,jd=/\[pasted #(\d+) \+\d+ lines\]$/,Iu=/^\[pasted #(\d+) \+\d+ lines\]/;DA=500,Qn=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastEscapeAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>DA&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.lastEscapeAt=null,this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){this.lastEscapeAt=null,this.recordEdit();let n=e.text.split(`
143
- `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(NA(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e!=="escape"&&(this.lastEscapeAt=null),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.moveLeft(),[];case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":{if(this.turnRunning)return this.lastEscapeAt=null,[{type:"cancel",prefill:!0}];let n=Date.now();return this.lastEscapeAt!==null&&n-this.lastEscapeAt<=500?(this.lastEscapeAt=null,[{type:"switch-session"}]):(this.lastEscapeAt=n,[])}}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
144
- `)}expandPastes(e){return e.replace(BA,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
141
+ `),i({exitCode:-1})}})}function JC(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.kind==="terminal"&&typeof e.command=="string"&&Array.isArray(e.args)}async function xu(t,e){let n;try{n=await e.authenticate(t.id)}catch(s){return{kind:"error",message:s instanceof Error&&s.message.length>0?s.message:String(s)}}if(JC(n)){let s={command:n.command,args:n.args,env:n.env,cwd:n.cwd},r=await e.runTerminalAuth(s);return r.exitCode===0?{kind:"terminal-completed"}:{kind:"exit-nonzero",exitCode:r.exitCode}}return{kind:"retry"}}async function Sy(t,e,n,s,r){ss();let i=HC(e,n,s),o=!1,a,c,d=()=>{let u=4;i.command&&u++,i.url&&u++,i.methodLines&&(u+=1+i.methodLines.length),a&&u++,c&&u++;let f=rs(t,{contentHeight:u,contentWidth:80,title:"Authentication required"}),p=f.contentW,m=0;if(a&&(t.moveTo(f.contentX,f.contentY+m),t.brightYellow.noFormat(nt(` ${a}`,p)),m++),c&&(t.moveTo(f.contentX,f.contentY+m),t.brightRed.noFormat(nt(` ${c}`,p)),m++),t.moveTo(f.contentX,f.contentY+m),t.brightWhite.bold.noFormat(nt(` ${i.title}`,p)),m+=2,t.moveTo(f.contentX,f.contentY+m),t.noFormat(nt(` ${i.description}`,p)),m++,i.command&&(t.moveTo(f.contentX,f.contentY+m),t.dim.noFormat(" Run: "),t.brightWhite.noFormat(nt(i.command,p-7)),m++),i.url&&(t.moveTo(f.contentX,f.contentY+m),t.dim.noFormat(" Docs: "),t.brightWhite.noFormat(nt(i.url,p-7)),m++),i.methodLines){t.moveTo(f.contentX,f.contentY+m),t.dim.noFormat(" Methods reported by the agent:"),m++;for(let h of i.methodLines)t.moveTo(f.contentX,f.contentY+m),t.dim.noFormat(" "),t.noFormat(nt(h.label,p-3)),m++}return m++,t.moveTo(f.contentX,f.contentY+m),t.dim.noFormat(` ${i.footer}`),f},l=i.methodLines?.length??0;return Bs({term:t,render:()=>{d()},onKey:(u,f,p,m)=>{if(o)return;let h=UC(u,p,l);if(h.kind!=="ignore"){if(h.kind==="retry"||h.kind==="back"||h.kind==="cancel"){m(h.kind);return}if(h.kind==="selectMethod"){let y=i.methodLines?.[h.index]?.method;if(!y||!r?.authenticate)return;o=!0,c=void 0,a=`Authenticating with ${wy(y)}\u2026`,d();let b=r.runTerminalAuth??(v=>zC(t,v));(async()=>{let v=await xu(y,{authenticate:r.authenticate,runTerminalAuth:b});if(v.kind==="terminal-completed"){m("terminal-completed");return}if(v.kind==="retry"){m("retry");return}if(v.kind==="error"){c=v.message,a=void 0,o=!1,d();return}a=void 0,c=`auth process exited with code ${v.exitCode??"(signal)"}`,o=!1,d()})()}}}})}var NC,DC,Cu=K(()=>{"use strict";Ma();$a();zi();NC="This agent requires authentication before use.",DC="[r] retry \xB7 [Esc] back to picker"});import{setTimeout as Ay}from"timers/promises";function tA(t){return!("method"in t)&&"id"in t&&t.id!==void 0}var GC,XC,ZC,eA,Ji,Au=K(()=>{"use strict";Do();Ii();GC=200,XC=5e3,ZC=2,eA=60,Ji=class{constructor(e){this.opts=e}opts;current;outboundQueue=[];flushing=!1;messageHandlers=[];closeHandlers=[];destroyed=!1;firstConnect=!0;reconnectInFlight;connectGate;releaseConnectGate;pendingRequests=new Map;async start(){await this.connectWithRetry()}onMessage(e){this.messageHandlers.push(e)}onClose(e){this.closeHandlers.push(e)}async send(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(this.connectGate||!this.current||this.flushing){this.outboundQueue.push(e);return}this.outboundQueue.push(e),await this.flushQueue()}async request(e){if(this.destroyed)throw new Error("resilient ws stream is destroyed");if(!this.current)throw new Error("resilient ws stream not connected");let n=e.id,s=new Promise((r,i)=>{this.pendingRequests.set(n,{resolve:r,reject:i})});try{await this.current.send(e)}catch(r){throw this.pendingRequests.delete(n),r}return s}async close(){if(this.destroyed=!0,this.reconnectInFlight&&await Promise.race([this.reconnectInFlight.catch(()=>{}),Ay(2e3)]),this.current&&await this.current.close().catch(()=>{}),this.pendingRequests.size>0){let e=new Error("resilient ws stream is destroyed");for(let{reject:n}of this.pendingRequests.values())n(e);this.pendingRequests.clear()}for(let e of this.closeHandlers)e()}async connectWithRetry(){let e=0,n=GC;for(;!this.destroyed;)try{let s=typeof this.opts.url=="function"?await this.opts.url():this.opts.url,r=await kr(s,this.opts.subprotocols);this.bindStream($n(r));let i=this.firstConnect;this.firstConnect=!1,this.connectGate=new Promise(o=>{this.releaseConnectGate=o});try{if(this.opts.onConnect)try{await this.opts.onConnect(i)}catch(o){this.log(`hydra-acp: post-connect handler failed: ${o.message}`)}}finally{this.releaseConnectGate?.(),this.releaseConnectGate=void 0,this.connectGate=void 0}await this.flushQueue();return}catch(s){if(e+=1,this.opts.onConnectFailure&&this.opts.onConnectFailure(s),e>=eA)throw new Error(`hydra-acp: gave up reconnecting after ${e} attempts: ${s.message}`);if(this.log(`hydra-acp: connect attempt ${e} failed (${s.message}); retrying in ${n}ms`),await Ay(n),this.destroyed)return;n=Math.min(n*ZC,XC)}}bindStream(e){this.current=e,e.onMessage(n=>{if(tA(n)&&n.id!==null){let s=this.pendingRequests.get(n.id);s&&(this.pendingRequests.delete(n.id),s.resolve(n))}for(let s of this.messageHandlers)s(n)}),e.onClose(n=>{if(!this.destroyed){if(this.current=void 0,this.pendingRequests.size>0){let s=n??new Error("ws closed before response");for(let{reject:r}of this.pendingRequests.values())r(s);this.pendingRequests.clear()}this.scheduleReconnect(n)}})}async flushQueue(){if(!this.flushing){this.flushing=!0;try{for(;!this.destroyed&&this.current&&this.outboundQueue.length>0;){let e=this.outboundQueue[0];try{await this.current.send(e)}catch(n){this.scheduleReconnect(n);return}this.outboundQueue.shift()}}finally{this.flushing=!1}}}scheduleReconnect(e){if(!(this.destroyed||this.reconnectInFlight)){if(this.log(`hydra-acp: connection lost (${e?.message??"no error"}); reconnecting...`),this.opts.onDisconnect)try{this.opts.onDisconnect(e)}catch(n){this.log(`hydra-acp: onDisconnect handler threw: ${n.message}`)}this.reconnectInFlight=(async()=>{try{await this.connectWithRetry()}catch(n){for(let s of this.closeHandlers)s(n);this.destroyed=!0}finally{this.reconnectInFlight=void 0}})()}}log(e){if(this.opts.log){this.opts.log(e);return}process.stderr.write(`${e}
142
+ `)}}});function Ry(t,e){let n=t&&typeof t=="object"?t.options:void 0;if(Array.isArray(n)){for(let i of e){let o=n.find(a=>typeof a=="object"&&a!==null&&a.kind===i&&typeof a.optionId=="string");if(o?.optionId!==void 0)return o.optionId}let r=n.find(i=>typeof i=="object"&&i!==null&&typeof i.optionId=="string");if(r?.optionId!==void 0)return r.optionId}let s=e[0]??"allow";return console.warn(`[permission-pick] no optionId match for preferredKinds=${JSON.stringify(e)}; falling back to kind name ${JSON.stringify(s)} (agent will likely reject)`),s}function Pr(t){return{outcome:{outcome:"selected",optionId:Ry(t,["allow_once","allow_always"])}}}function Ty(t){return{outcome:{outcome:"selected",optionId:Ry(t,["reject_once","reject_always"])}}}function Vd(t){return t&&typeof t=="object"?t:void 0}function Ko(t){return typeof t=="string"&&t.length>0?t:void 0}function Ey(t){let e=Vd(t),n=Vd(e?.toolCall),s={paths:[]};if(!n)return s;let r=Ko(n.kind);r&&(s.kind=r);let i=new Set,o=d=>{let l=Ko(d);l&&!i.has(l)&&(i.add(l),s.paths.push(l))},a=n.locations;if(Array.isArray(a))for(let d of a)o(Vd(d)?.path);let c=Vd(n.rawInput);if(c){o(c.file_path),o(c.filePath),o(c.path);let d=Ko(c.command);d&&(s.command=d);let l=Ko(c.url);l&&(s.url=l);let u=Ko(c.description);u&&(s.description=u)}return s}function Py(t){let e=[];return t.command?e.push(`$ ${t.command}`):t.url?e.push(t.url):t.paths.length===1?e.push(t.paths[0]):t.paths.length>1?e.push(`${t.paths[0]} (+${t.paths.length-1} more)`):t.description&&e.push(t.description),e.join(" ").replace(/\s+/g," ").trim()}var Yd=K(()=>{"use strict"});function eR(){return!!(process.env.NO_UPDATE_NOTIFIER==="1"||process.argv.includes("--no-update-notifier"))}function Yy(t){let n=(t.split("-",1)[0]??t).split("."),s=Number(n[0]),r=Number(n[1]),i=Number(n[2]);return!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i)?null:[s,r,i]}function tR(t,e){let n=Yy(t),s=Yy(e);if(!n||!s)return t!==e;for(let r=0;r<3;r++){let i=n[r],o=s[r];if(i>o)return!0;if(i<o)return!1}return!1}async function Vo(){if(Ds!==void 0)return Ds;if(eR())return Ds=null,Ds;try{let t=await import("update-notifier"),n=(t.default??t)({pkg:{name:Qy,version:pe}}),s=n.update;if(s&&typeof s.latest=="string"&&typeof s.current=="string"&&tR(s.latest,s.current)){try{n.config?.set?.("update",s)}catch{}Ds={current:s.current,latest:s.latest,type:typeof s.type=="string"?s.type:"unknown"}}else{if(s&&typeof s.latest=="string"&&typeof s.current=="string")try{n.config?.set?.("update",void 0)}catch{}Ds=null}}catch{Ds=null}return Ds}function Yo(t){return`hydra-acp ${t.latest} available (current ${t.current}) \xB7 run: npm update -g ${Qy}`}var Qy,Ds,Eu=K(()=>{"use strict";Wt();Qy="@hydra-acp/cli"});import*as Qo from"fs/promises";import*as Pu from"path";async function Go(t){let e=t.trim();if(e.length===0)return{ok:!1,reason:"path is empty"};let n=Pu.resolve(Je(e)),s;try{s=await Qo.stat(n)}catch{return{ok:!1,reason:`${n} does not exist`}}return s.isDirectory()?{ok:!0,path:n}:{ok:!1,reason:`${n} is not a directory`}}async function Gy(t){let e=[],n=new Set,s=r=>{n.has(r)||(n.add(r),e.push(r))};s(t),t.startsWith("/Users/")?s("/home/"+t.slice(7)):t.startsWith("/home/")&&s("/Users/"+t.slice(6));for(let r of e)try{if((await Qo.stat(r)).isDirectory())return r}catch{}return null}async function Xy(t){let e=t.lastIndexOf("/"),n,s,r;e===-1?(n="",s=t,r="."):(n=t.slice(0,e+1),s=t.slice(e+1),r=e===0?"/":n);let i=Pu.resolve(Je(r)),o;try{o=(await Qo.readdir(i,{withFileTypes:!0})).map(l=>({name:l.name,isDir:l.isDirectory()}))}catch{return{prefix:n,basePrefix:s,matches:[]}}let a=s.startsWith("."),c=o.filter(d=>d.name.startsWith(s)).filter(d=>a||!d.name.startsWith(".")).map(d=>d.isDir?`${d.name}/`:d.name).sort();return{prefix:n,basePrefix:s,matches:c}}var Mu=K(()=>{"use strict";je()});var Zy,ew,tw,nw=K(()=>{"use strict";Zy="hydra-acp/question/list",ew="hydra-acp/question/answer",tw="hydra-acp/question/dismiss"});import{EventEmitter as nR}from"events";import{WebSocket as sR}from"ws";function rR(t,e){let n={};try{let s=new URL(t);if(s.protocol==="wss:"){let r=mo(s.hostname);r.rejectUnauthorized!==void 0&&(n.rejectUnauthorized=r.rejectUnauthorized),r.autoSelectFamily!==void 0&&(n.autoSelectFamily=r.autoSelectFamily),r.checkServerIdentity!==void 0&&(n.checkServerIdentity=r.checkServerIdentity)}}catch{}return new Promise((s,r)=>{let i=new sR(t,e,n),o=()=>{i.off("error",a),s($n(i))},a=c=>{i.off("open",o),r(c)};i.once("open",o),i.once("error",a)})}function sw(t,e,n,s={}){return new Promise((r,i)=>{(async()=>{let o=s.fetchImpl??fetch,a=s._streamFactory??rR,c=["acp.v1",`hydra-acp-token.${t.token}`],d=await a(t.wsUrl,c),l=new _t(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 h=n.replace(/\s+/g," ").trim().slice(0,60);u=(await Pd(t,e,{forkAt:s.forkAt,cwd:s.cwd,agentId:s.agentId,title:`btw: ${h}`},o)).sessionId}}catch(h){throw d.close().catch(()=>{}),h}let f=new _u(l,d,u,t,o),p=!1,m=h=>{p||(p=!0,f.emit("event",h),d.close().catch(()=>{}))};l.onNotification("session/update",h=>{let y=h?.update;y!==void 0&&f.emit("event",{kind:"update",update:y})}),l.onClose(()=>{p||m({kind:"completed"})});try{await l.request("session/attach",{sessionId:u,historyPolicy:"full",clientInfo:{name:"hydra-acp-sidechain"}})}catch(h){throw d.close().catch(()=>{}),On(t,u,o).catch(()=>{}),h}r(f),setImmediate(()=>{l.request("session/prompt",{sessionId:u,prompt:[{type:"text",text:n}],_meta:{[ht]:{ancillary:!0}}}).then(h=>{let y=h&&typeof h=="object"?h.stopReason:void 0;m(y==="cancelled"?{kind:"cancelled"}:y==="error"||y==="errored"?{kind:"errored",error:new Error("turn ended with error stopReason")}:{kind:"completed"})}).catch(h=>{m({kind:"errored",error:h instanceof Error?h:new Error(String(h))})})})})().catch(i)})}var _u,rw=K(()=>{"use strict";ho();Ho();pr();Ii();xt();_u=class extends nR{_conn;_stream;_sessionId;_target;_fetchImpl;_cancelled=!1;constructor(e,n,s,r,i){super(),this._conn=e,this._stream=n,this._sessionId=s,this._target=r,this._fetchImpl=i}get sessionId(){return this._sessionId}cancel(){this._cancelled||(this._cancelled=!0,this._conn.notify("session/cancel",{sessionId:this._sessionId}).catch(()=>{}),this._stream.close().catch(()=>{}),On(this._target,this._sessionId,this._fetchImpl).catch(()=>{}))}once(e,n){return super.once(e,n)}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}}});var $u,ec,iw=K(()=>{"use strict";Ni();Es();$u=class{_listeners=new Map;on(e,n){let s=this._listeners.get(e);s||(s=new Set,this._listeners.set(e,s)),s.add(n)}off(e,n){this._listeners.get(e)?.delete(n)}emit(e){this._listeners.get(e)?.forEach(s=>s())}},ec=class extends $u{_lines=[];_toolStates=new Map;_toolRanges=new Map;_pendingAgentText=null;_pendingAgentRange=null;_pendingThoughtText=null;_pendingThoughtRange=null;_emitChanged;_getMaxWidth;constructor(e={}){super(),this._emitChanged=e.emitChanged??!0,this._getMaxWidth=e.getMaxWidth}append(e){let n=_n(e);if(!n)return 0;switch(n.kind!=="agent-text"&&(this._pendingAgentText=null,this._pendingAgentRange=null),n.kind!=="agent-thought"&&(this._pendingThoughtText=null,this._pendingThoughtRange=null),n.kind){case"agent-text":{let s=n.text;if(this._pendingAgentText!==null&&this._pendingAgentRange!==null){this._pendingAgentText+=s;let o=this._parseAgent(this._pendingAgentText);return this._replaceAgentRange(this._pendingAgentRange,o),o.length}this._pendingAgentText=s;let r=this._parseAgent(s),i=this._lines.length;return this._pushLines(r),this._pendingAgentRange={start:i,length:r.length},r.length}case"agent-thought":{let s=n.text;if(this._pendingThoughtText!==null&&this._pendingThoughtRange!==null){this._pendingThoughtText+=s;let o=Bi(this._pendingThoughtText);return this._replaceThoughtRange(this._pendingThoughtRange,o),o.length}this._pendingThoughtText=s;let r=Bi(s),i=this._lines.length;return this._pushLines(r),this._pendingThoughtRange={start:i,length:r.length},r.length}case"tool-call":{let s={initialTitle:n.title,latestTitle:n.title,status:n.status??"pending"};n.detail!==void 0&&(s.detail=n.detail),this._toolStates.set(n.toolCallId,s);let r=qo(s),i=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:i,length:r.length}),r.length}case"tool-call-update":{let s=this._toolStates.get(n.toolCallId);if(!s)return 0;n.title!==void 0&&(s.latestTitle=n.title),n.status!==void 0&&(s.status=n.status),n.detail!==void 0&&(s.detail=n.detail),n.errorText!==void 0&&(s.errorText=n.errorText);let r=qo(s),i=this._toolRanges.get(n.toolCallId);if(!i){let o=this._lines.length;return this._pushLines(r),this._toolRanges.set(n.toolCallId,{start:o,length:r.length}),r.length}return this._replaceRange(n.toolCallId,i,r),r.length}default:{let s=Os(n);return this._pushLines(s),s.length}}}_parseAgent(e){let n=this._getMaxWidth?.();return Ls(e,n!==void 0&&n>0?{maxWidth:n}:void 0)}_replaceAgentRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingThoughtRange&&this._pendingThoughtRange.start>e.start&&(this._pendingThoughtRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceThoughtRange(e,n){let s=n.length-e.length;if(this._lines.splice(e.start,e.length,...n),e.length=n.length,s!==0){for(let r of this._toolRanges.values())r.start>e.start&&(r.start+=s);this._pendingAgentRange&&this._pendingAgentRange.start>e.start&&(this._pendingAgentRange.start+=s)}this._emitChanged&&this.emit("changed")}_replaceRange(e,n,s){let r=s.length-n.length;if(this._lines.splice(n.start,n.length,...s),n.length=s.length,r!==0){for(let[i,o]of this._toolRanges)i!==e&&o.start>n.start&&(o.start+=r);this._pendingAgentRange&&this._pendingAgentRange.start>n.start&&(this._pendingAgentRange.start+=r),this._pendingThoughtRange&&this._pendingThoughtRange.start>n.start&&(this._pendingThoughtRange.start+=r)}this._emitChanged&&this.emit("changed")}getLines(){return this._lines.slice()}clear(){(this._lines.length>0||this._toolStates.size>0)&&(this._lines.length=0,this._toolStates.clear(),this._toolRanges.clear(),this._pendingAgentText=null,this._pendingAgentRange=null,this._pendingThoughtText=null,this._pendingThoughtRange=null,this.emit("changed"))}get size(){return this._lines.length}_pushLines(e){let n=this._lines.length;for(let s of e)this._lines.push(s);this._emitChanged&&this._lines.length>n&&this.emit("changed")}}});function oR(t,e){return`[pasted #${t} +${e} lines]`}var iR,tc,Fu,aR,is,Ou=K(()=>{"use strict";iR=/\[pasted #(\d+) \+\d+ lines\]/g,tc=/\[pasted #(\d+) \+\d+ lines\]$/,Fu=/^\[pasted #(\d+) \+\d+ lines\]/;aR=500,is=class{buffer=[""];row=0;col=0;planMode=!1;historyIndex=-1;queueIndex=-1;savedDraft=null;history=[];historySearch=null;queue=[];turnRunning=!1;killBuffer="";attachments=[];savedAttachments=null;pastes=new Map;nextPasteId=1;collapsePastes;lastEscapeAt=null;undoStack=[];redoStack=[];constructor(e={}){this.history=[...e.history??[]],this.planMode=e.planMode??!1,this.collapsePastes=e.collapsePastes??!0}expandedText(){return this.expandPastes(this.bufferText())}state(){return Object.freeze({buffer:this.buffer,row:this.row,col:this.col,planMode:this.planMode,historyIndex:this.historyIndex,queueIndex:this.queueIndex,attachments:this.attachments,historySearchQuery:this.historySearch?.query??null})}addAttachment(e){this.recordEdit(),this.attachments.push(e)}removeAttachment(e){e<0||e>=this.attachments.length||(this.recordEdit(),this.attachments.splice(e,1))}snapshotState(){return{buffer:[...this.buffer],row:this.row,col:this.col,planMode:this.planMode,attachments:[...this.attachments]}}restoreSnapshot(e){this.buffer=[...e.buffer],this.row=e.row,this.col=e.col,this.planMode=e.planMode,this.attachments=[...e.attachments]}recordEdit(){this.undoStack.push(this.snapshotState()),this.undoStack.length>aR&&this.undoStack.shift(),this.redoStack=[]}clearUndoHistory(){this.undoStack=[],this.redoStack=[]}undo(){let e=this.undoStack.pop();e!==void 0&&(this.redoStack.push(this.snapshotState()),this.restoreSnapshot(e))}redo(){let e=this.redoStack.pop();e!==void 0&&(this.undoStack.push(this.snapshotState()),this.restoreSnapshot(e))}setTurnRunning(e){this.turnRunning=e}setHistory(e){this.history=[...e],this.historyIndex=-1,this.savedDraft=null,this.historySearch=null,this.clearUndoHistory()}setQueue(e){this.queue=[...e],this.queueIndex>=this.queue.length&&(this.queueIndex=-1)}replaceFirstLine(e){this.recordEdit(),this.buffer[0]=e,this.row===0&&(this.col=e.length)}replaceRangeOnCurrentLine(e,n,s){this.recordEdit();let r=this.currentLine(),i=Math.max(0,Math.min(e,r.length)),o=Math.max(i,Math.min(n,r.length));this.setCurrentLine(r.slice(0,i)+s+r.slice(o)),this.col=i+s.length}setBuffer(e,n=[]){this.loadEntry(e),this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[...n],this.clearUndoHistory()}feed(e){if(this.historySearch!==null){if(e.type==="char")return this.mutateHistorySearchQuery(this.historySearch.query+e.ch.toLowerCase());if(e.type==="paste")return this.mutateHistorySearchQuery(this.historySearch.query+e.text.replace(/\n/g," ").toLowerCase());if(e.type==="key"){if(e.name==="ctrl-r")return this.advanceHistorySearch();if(e.name==="ctrl-s")return this.retreatHistorySearch(),[];if(e.name==="escape"||e.name==="ctrl-c")return this.cancelHistorySearch(),[];if(e.name==="backspace")return this.historySearch.query.length===0?(this.cancelHistorySearch(),[]):this.mutateHistorySearchQuery(this.historySearch.query.slice(0,-1));this.historySearch=null}}if(e.type==="char")return this.lastEscapeAt=null,this.recordEdit(),this.insertChar(e.ch),[];if(e.type==="paste"){this.lastEscapeAt=null,this.recordEdit();let n=e.text.split(`
143
+ `).length;if(this.collapsePastes&&n>10){let s=this.nextPasteId++;this.pastes.set(s,e.text),this.insertText(oR(s,n))}else this.insertText(e.text);return[]}return e.type==="attachment-paths"?[]:this.handleKey(e.name)}handleKey(e){switch(e!=="escape"&&(this.lastEscapeAt=null),e){case"enter":return this.send();case"shift-enter":case"ctrl-enter":return this.amend();case"alt-enter":return this.recordEdit(),this.insertNewline(),[];case"shift-tab":return this.recordEdit(),this.planMode=!this.planMode,[{type:"plan-toggle",on:this.planMode},{type:"redraw-banner"}];case"tab":return this.recordEdit(),this.insertText(" "),[];case"up":return this.handleUp();case"down":return this.handleDown();case"left":return this.moveLeft(),[];case"right":return this.moveRight(),[];case"ctrl-a":return this.col=0,[];case"ctrl-e":return this.col=this.currentLine().length,[];case"home":return this.handleHome();case"end":return this.handleEnd();case"ctrl-b":return this.moveLeft(),[];case"ctrl-f":return this.moveRight(),[];case"ctrl-g":return[{type:"show-help"}];case"alt-b":return this.moveWordBackward(),[];case"alt-f":return this.moveWordForward(),[];case"ctrl-k":return this.recordEdit(),this.killToEnd(),[];case"ctrl-n":return this.handleDown();case"ctrl-o":return[{type:"toggle-options"}];case"ctrl-q":return[{type:"toggle-questions"}];case"backspace":return this.recordEdit(),this.backspace(),[];case"delete":return this.recordEdit(),this.deleteForward(),[];case"ctrl-c":return this.handleCtrlC();case"ctrl-d":return this.bufferIsEmpty()?[{type:"exit"}]:(this.recordEdit(),this.deleteForward(),[]);case"ctrl-l":return[{type:"redraw"}];case"ctrl-p":return[{type:"switch-session"}];case"ctrl-t":return[{type:"toggle-thoughts"}];case"alt-n":case"alt-tab":return[{type:"next-live-session"}];case"ctrl-r":return this.startHistorySearch();case"ctrl-s":return this.amend();case"ctrl-u":return this.recordEdit(),this.killLine(),[];case"ctrl-v":return[{type:"attachment-request",source:"clipboard"}];case"ctrl-w":return this.recordEdit(),this.killWord(),[];case"ctrl-x":return[{type:"toggle-mouse"}];case"ctrl-y":return this.recordEdit(),this.yank(),[];case"ctrl-underscore":return this.undo(),[];case"alt-underscore":return this.redo(),[];case"escape":{if(this.turnRunning)return this.lastEscapeAt=null,[{type:"cancel",prefill:!0}];let n=Date.now();return this.lastEscapeAt!==null&&n-this.lastEscapeAt<=500?(this.lastEscapeAt=null,[{type:"switch-session"}]):(this.lastEscapeAt=n,[])}}}currentLine(){return this.buffer[this.row]??""}setCurrentLine(e){this.buffer[this.row]=e}bufferText(){return this.buffer.join(`
144
+ `)}expandPastes(e){return e.replace(iR,(n,s)=>{let r=parseInt(s,10),i=this.pastes.get(r);return i!==void 0?i:n})}bufferIsEmpty(){return this.buffer.length===1&&this.buffer[0]===""}clearBuffer(){this.buffer=[""],this.row=0,this.col=0,this.historyIndex=-1,this.queueIndex=-1,this.savedDraft=null,this.savedAttachments=null,this.historySearch=null,this.attachments=[],this.clearUndoHistory()}insertChar(e){if(e.length===0)return;if(e.includes(`
145
145
  `)){this.insertText(e);return}let n=this.currentLine();this.setCurrentLine(n.slice(0,this.col)+e+n.slice(this.col)),this.col+=e.length}insertText(e){let n=e.split(`
146
- `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(jd);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Iu);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
146
+ `);if(n.length===1){this.insertChar(n[0]??"");return}let s=this.currentLine(),r=s.slice(0,this.col),i=s.slice(this.col),o=n[0]??"",a=n[n.length-1]??"",c=n.slice(1,-1);this.setCurrentLine(r+o);let d=[...c,a+i];this.buffer.splice(this.row+1,0,...d),this.row+=n.length-1,this.col=a.length}insertNewline(){let e=this.currentLine(),n=e.slice(0,this.col),s=e.slice(this.col);this.setCurrentLine(n),this.buffer.splice(this.row+1,0,s),this.row+=1,this.col=0}backspace(){if(this.col>0){let s=this.currentLine(),i=s.slice(0,this.col).match(tc);if(i!==null){this.pastes.delete(parseInt(i[1],10)),this.setCurrentLine(s.slice(0,this.col-i[0].length)+s.slice(this.col)),this.col-=i[0].length;return}this.setCurrentLine(s.slice(0,this.col-1)+s.slice(this.col)),this.col-=1;return}if(this.row===0)return;let e=this.buffer[this.row-1]??"",n=this.currentLine();this.buffer.splice(this.row,1),this.row-=1,this.col=e.length,this.buffer[this.row]=e+n}deleteForward(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Fu);if(s!==null){this.pastes.delete(parseInt(s[1],10)),this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+s[0].length));return}this.setCurrentLine(e.slice(0,this.col)+e.slice(this.col+1));return}if(this.row<this.buffer.length-1){let n=this.buffer[this.row+1]??"";this.buffer.splice(this.row+1,1),this.setCurrentLine(e+n)}}killLine(){if(this.col>0){let n=this.currentLine();this.killBuffer=n.slice(0,this.col),this.setCurrentLine(n.slice(this.col)),this.col=0;return}if(this.row===0)return;if(this.currentLine().length===0){this.killBuffer=`
147
147
  `,this.buffer.splice(this.row,1),this.row-=1,this.col=this.currentLine().length;return}let e=this.buffer[this.row-1]??"";this.killBuffer=e+`
148
148
  `,this.buffer.splice(this.row-1,1),this.row-=1}killToEnd(){let e=this.currentLine();if(this.col<e.length){this.killBuffer=e.slice(this.col),this.setCurrentLine(e.slice(0,this.col));return}if(this.row>=this.buffer.length-1)return;if(e.length===0){this.killBuffer=`
149
149
  `,this.buffer.splice(this.row,1);return}let n=this.buffer[this.row+1]??"";this.killBuffer=`
150
- `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(jd);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(jd);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Iu);if(s!==null){this.col+=s[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(jd);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(Iu);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
151
- `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.recordEdit(),this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});var Ni,qd,Cu=K(()=>{"use strict";Ni=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},qd=class{constructor(e){this.deps=e}deps;lastRepaintAt=0;timer=null;get pendingTimer(){return this.timer}schedule(){if(!this.deps.isStarted())return;if(this.deps.isRepaintPaused()){this.deps.markRepaintPending();return}let e=this.deps.throttleMs();if(e<=0){this.deps.doRepaint();return}let s=Date.now()-this.lastRepaintAt;if(s>=e){this.cancel(),this.deps.doRepaint();return}this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.doRepaint()},e-s))}noteRepaintStart(){this.lastRepaintAt=Date.now(),this.cancel()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}}});import HA from"path";function jo(t){return Uy[HA.extname(t).toLowerCase()]??null}function UA(t){return jo(t)!==null}function Au(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!jA.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function qA(t){return Au(t)!==null}function Vt(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function jy(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!qA(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!UA(o))return null;n.push(o)}return n.length>0?n:null}var _n,Uy,jA,Wd=K(()=>{"use strict";_n=10*1024*1024,Uy={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};jA=new Set(Object.values(Uy))});import WA from"string-width";function qy(t,e){if(!t||e<=0)return 0;let n=0;for(let s of zA.segment(t)){let r=WA(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function Wy(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var zA,zy=K(()=>{"use strict";zA=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as JA}from"child_process";import Ru from"fs/promises";import KA from"os";import YA from"path";async function Yy(t={}){let e={...Tu,...t};return e.platform==="darwin"?XA(e):e.platform==="linux"?ZA(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function Vy(t={}){let e={...Tu,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Di(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Di(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await qo(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function Gy(t,e={}){let{target:n="both",...s}=e,r={...Tu,...s},i=await VA(r,t,n);if(i.ok)return i;let o=GA(r,t,n);return o.ok||o.reason!==Qy?o:i}async function VA(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await zd(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await Di(t,"wl-copy")?Ky(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Di(t,"xclip")?Ky(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function Ky(t,e,n,s,r,i,o){let a=n;if(i){try{await zd(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await zd(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await zd(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function GA(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>Jy)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${Jy} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??QA)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:Qy}}function QA(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function XA(t){let e=YA.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await Xy(t.spawn,"osascript",s);let r=await rR(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Ru.unlink(e).catch(()=>{})}try{let r=await qo(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function ZA(t){let e=await eR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await sR(t,e),s=nR(n);if(s)try{let r=await qo(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>_n?{ok:!1,reason:`clipboard image is ${Vt(r.length)}, max ${Vt(_n)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await qo(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Eu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function eR(t){return t.env.WAYLAND_DISPLAY&&await Di(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Di(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function nR(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of tR)if(e.has(n))return n;return null}async function sR(t,e){try{return(await qo(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
152
- `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Eu(t){return t.replace(/\r\n?/g,`
153
- `)}async function Di(t,e){try{return await Xy(t.spawn,"which",[e]),!0}catch{return!1}}async function rR(t,e){try{let n=await Ru.readFile(t);return e&&await Ru.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>_n?{ok:!1,reason:`clipboard image is ${Vt(n.length)}, max ${Vt(_n)}`}:{ok:!0,kind:"image",attachment:{mimeType:jo(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function Xy(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function zd(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function qo(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",f=>{o.push(typeof f=="string"?Buffer.from(f):f)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",f=>{d||(d=!0,r(f))}),i.on("close",f=>{c=f??0,l()})})}var Tu,Jy,Qy,tR,Pu=K(()=>{"use strict";Wd();Tu={platform:process.platform,env:process.env,spawn:JA,tmpdir:KA.tmpdir};Jy=74994;Qy="no TTY available for OSC 52 clipboard write";tR=["image/png","image/jpeg","image/gif","image/webp"]});function iR(){Wo===0&&process.stdout.write(Zg),Wo++}function oR(){Wo!==0&&(Wo--,Wo===0&&process.stdout.write(ey))}function De(t){iR();try{t()}finally{oR()}}var Wo,Mu=K(()=>{"use strict";Lo();Wo=0});import{spawn as aR}from"child_process";import{statSync as dR}from"fs";import{homedir as Zy}from"os";import{isAbsolute as ew,resolve as cR}from"path";import Sr from"string-width";import lR from"wrap-ansi";function wR(t){let e=t.replace(/\r\n?$|\n$/,"");return yR.test(e)?e:null}function bR(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function tw(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let c=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function Zn(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let c=r[a];if(c===" "||c===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function Es(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function nw(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){Xn(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let c=o.indexOf(s,a);if(c===-1){Xn(t,e.slice(a),n);return}c>a&&Xn(t,e.slice(a,c),n);let d=r!==null&&c===r;Xn(t,e.slice(c,c+s.length),d?"search-highlight-active":"search-highlight"),a=c+s.length}}function zo(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function Xn(t,e,n){if(e.length!==0)switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.green.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}function vR(t,e){return e<=0?[t]:t.length===0?[""]:lR(t,e,{hard:!0,trim:!1}).split(`
154
- `)}function uw(t){lw=t}function fw(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function Ts(t){return Sr(t,{ambiguousIsNarrow:!lw})}function Hi(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return SR.test(n)?{text:t.slice(e,e+2),width:0}:null}function sw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Hi(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function rw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=Hi(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function kR(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=Hi(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function pw(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(Hi(t,e))return!0;return!1}function*ju(t){let e=0;for(;e<t.length;){let n=Hi(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(Hi(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Uu.segment(t.slice(e,s)))yield{text:i,width:Ts(i)};e=s}}function IR(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function xR(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&pw(t);return!s&&!cw.test(t)?CR(t,e):AR(t,e,s)}function CR(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function AR(t,e,n){let s=[],r=n?[...ju(t)]:RR(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function RR(t){let e=[];for(let{segment:n}of Uu.segment(t))e.push({text:n,width:Ts(n)});return e}function lt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&pw(t);if(!s&&t.length<=e&&!cw.test(t))return t;if(!s)return Ts(t)<=e?t:e<=1?iw(t,e):iw(t,e-1)+"\u2026";let r=[...ju(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?ow(r,e):ow(r,e-1)+"\u2026"}function iw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Uu.segment(t)){let i=Ts(r);if(s+i>e)break;n+=r,s+=i}return n}function ow(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function TR(t){let e=t.indexOf(`
155
- `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function aw(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${Kd(t.used)}/${Kd(t.size)}`):e.push(Kd(t.used)):typeof t.size=="number"&&e.push(`/${Kd(t.size)}`),typeof t.costAmount=="number"&&e.push(Jl(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function Kd(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function Gd(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function Yd(){let t=[Pi,Mi,Yg,_i,Vg,fu,Yn,gr,yr,hr,mr,"\x1B>",Fo,Pd,Md,"\x1B]9;4;0\x07",Wg].join("");try{process.stdout.write(t)}catch{}}function mw(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function dw(t,e){let n={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var _u,Jd,$u,Ou,uR,Le,ze,Be,Fu,Lu,fR,pR,mR,Bu,Nu,Du,hR,gR,yR,Vd,cw,Uu,lw,SR,Hu,qu=K(()=>{"use strict";Cu();Kl();pe();xn();Wd();Ri();zy();Pu();Mu();Lo();_u=500,Jd=1,$u=/[A-Za-z0-9_]/,Ou=/[A-Za-z0-9_./\-~+@]/,uR=/\x1b\[[0-9;]*[A-Za-z]/g,Le=1,ze=1,Be=1,Fu=8,Lu=5,fR=12,pR=12,mR=30,Bu=6,Nu=4,Du=2,hR=1e3,gR=1e4,yR=/^(https?|ftp):\/\/\S+$/;Vd=class{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onMouse;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let n=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onMouse=e.onMouse,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??hR,this.painter=new Ni(this.term),this.scheduler=new qd({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??gR,this.mouseEnabled=e.mouse??!1,this.inAppSelectionEnabled=e.inAppSelection??this.mouseEnabled,this.selectionClipboard=e.selectionClipboard??"both";let s=e.openFileCommand,r=typeof s=="string"?s.split(/\s+/).filter(i=>i.length>0):s;this.openFileCommand=r&&r.length>0?r:null,this.progressIndicatorEnabled=e.progressIndicator??!0,this.readonly=e.readonly??!1,this.resizeHandler=()=>this.repaint(),this.keyHandler=(i,o,a)=>this.handleKey(i,a),this.mouseHandler=(i,o)=>this.handleMouse(i,o),this.rawStdinHandler=i=>this.handleRawStdin(i)}start(e={}){this.started||(this.started=!0,e.skipFullscreen||this.term.fullscreen(!0),this.painter.clearCache(),this.lastWindowTitle=null,process.stdout.write(uu),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Md),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(Fo),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(Yd(),this.term.fullscreen(!1),this.term(`
156
- `)))}installBracketedPaste(){process.stdout.write(Ed),process.stdout.write(Jg),process.stdout.write(Kg),process.stdout.write(zg);let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.on("data",this.rawStdinHandler))}uninstallBracketedPaste(){process.stdout.write(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(hr),process.stdout.write(mr),process.stdout.write("\x1B>");let e=this.term;!e.stdin||this.terminalKitStdinHandler===null||(e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.terminalKitStdinHandler),this.terminalKitStdinHandler=null,this.pasteActive=!1,this.pasteBuffer="")}installSelectiveMouseReporting(){this.mouseEnabled||this.selectiveMouseProbing||this.selectiveMouseSupported||(this.selectiveMouseProbing=!0,process.stdout.write(Gg),this.selectiveMouseProbeTimer=setTimeout(()=>{this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer=null},250))}uninstallSelectiveMouseReporting(){this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseProbing=!1,this.selectiveMouseSupported&&(process.stdout.write(fu),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>Yd(),this.onProcessSignal=e=>{Yd(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{Yd(),process.stderr.write(`
150
+ `+n,this.buffer.splice(this.row+1,1)}killWord(){let e=this.currentLine();if(this.col===0){this.backspace();return}let s=e.slice(0,this.col).match(tc);if(s!==null){this.killBuffer=s[0];let o=this.col-s[0].length;this.setCurrentLine(e.slice(0,o)+e.slice(this.col)),this.col=o;return}let r=this.col;for(;r>0&&/\s/.test(e[r-1]??"");)r-=1;for(;r>0&&!/\s/.test(e[r-1]??"");)r-=1;let i=e.slice(r,this.col);i.length>0&&(this.killBuffer=i),this.setCurrentLine(e.slice(0,r)+e.slice(this.col)),this.col=r}yank(){this.killBuffer.length!==0&&this.insertText(this.killBuffer)}moveLeft(){if(this.col>0){let n=this.currentLine().slice(0,this.col).match(tc);if(n!==null){this.col-=n[0].length;return}this.col-=1;return}this.row>0&&(this.row-=1,this.col=this.currentLine().length)}moveRight(){let e=this.currentLine();if(this.col<e.length){let s=e.slice(this.col).match(Fu);if(s!==null){this.col+=s[0].length;return}this.col+=1;return}this.row<this.buffer.length-1&&(this.row+=1,this.col=0)}moveWordBackward(){if(this.col===0){if(this.row===0)return;this.row-=1,this.col=this.currentLine().length;return}let e=this.currentLine(),n=this.col;for(;n>0&&/\s/.test(e[n-1]??"");)n-=1;let r=e.slice(0,n).match(tc);if(r!==null){this.col=n-r[0].length;return}for(;n>0&&!/\s/.test(e[n-1]??"");)n-=1;this.col=n}moveWordForward(){let e=this.currentLine();if(this.col>=e.length){if(this.row>=this.buffer.length-1)return;this.row+=1,this.col=0;return}let n=this.col;for(;n<e.length&&/\s/.test(e[n]??"");)n+=1;let r=e.slice(n).match(Fu);if(r!==null){this.col=n+r[0].length;return}for(;n<e.length&&!/\s/.test(e[n]??"");)n+=1;this.col=n}handleUp(){return this.row>0?(this.row-=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.queueIndex===-1&&this.historyIndex===-1?this.queue.length===0&&this.history.length===0?[]:(this.savedDraft={buffer:[...this.buffer],row:this.row,col:this.col},this.savedAttachments=[...this.attachments],this.attachments=[],this.queue.length>0?(this.queueIndex=this.queue.length-1,this.loadEntry(this.queue[this.queueIndex]??"")):(this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??"")),[]):this.queueIndex>=0?this.queueIndex>0?(this.queueIndex-=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):this.history.length===0?[]:(this.queueIndex=-1,this.historyIndex=this.history.length-1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex>0&&(this.historyIndex-=1,this.loadEntry(this.history[this.historyIndex]??"")),[])}handleDown(){return this.row<this.buffer.length-1&&this.historyIndex===-1&&this.queueIndex===-1?(this.row+=1,this.col=Math.min(this.col,this.currentLine().length),[]):this.historyIndex>=0?this.historyIndex<this.history.length-1?(this.historyIndex+=1,this.loadEntry(this.history[this.historyIndex]??""),[]):(this.historyIndex=-1,this.queue.length>0?(this.queueIndex=0,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.restoreDraft(),[])):this.queueIndex>=0?this.queueIndex<this.queue.length-1?(this.queueIndex+=1,this.loadEntry(this.queue[this.queueIndex]??""),[]):(this.queueIndex=-1,this.restoreDraft(),[]):[]}restoreDraft(){this.savedDraft?(this.buffer=[...this.savedDraft.buffer],this.row=this.savedDraft.row,this.col=this.savedDraft.col,this.savedDraft=null,this.attachments=this.savedAttachments??[],this.savedAttachments=null):this.clearBuffer()}startHistorySearch(){let e=this.bufferText().toLowerCase();if(e.length===0)return this.historySearch={query:"",matchIndices:[],cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},[];let n=this.findHistoryMatches(e);return n.length===0?[{type:"escalate-search",query:e}]:(this.historySearch={query:e,matchIndices:n,cursor:0,savedDraft:{buffer:[...this.buffer],row:this.row,col:this.col}},this.loadEntry(this.history[n[0]]??""),[])}advanceHistorySearch(){if(this.historySearch===null)return[];let e=this.historySearch;if(e.cursor>=e.matchIndices.length-1){if(e.query.length===0)return[];let r=e.query,i=e.savedDraft;return this.historySearch=null,this.buffer=[...i.buffer],this.row=i.row,this.col=i.col,[{type:"escalate-search",query:r}]}e.cursor+=1;let s=e.matchIndices[e.cursor];return this.loadEntry(this.history[s]??""),[]}retreatHistorySearch(){if(this.historySearch===null||this.historySearch.cursor===0)return;this.historySearch.cursor-=1;let e=this.historySearch.matchIndices[this.historySearch.cursor];this.loadEntry(this.history[e]??"")}mutateHistorySearchQuery(e){if(this.historySearch===null)return[];if(e.length===0){this.historySearch.query="",this.historySearch.matchIndices=[],this.historySearch.cursor=0;let s=this.historySearch.savedDraft;return this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[]}let n=this.findHistoryMatches(e);if(n.length===0){let s=this.historySearch.savedDraft;return this.historySearch=null,this.buffer=[...s.buffer],this.row=s.row,this.col=s.col,[{type:"escalate-search",query:e}]}return this.historySearch.query=e,this.historySearch.matchIndices=n,this.historySearch.cursor=0,this.loadEntry(this.history[n[0]]??""),[]}findHistoryMatches(e){let n=[];for(let s=this.history.length-1;s>=0;s--){let r=this.history[s]??"";(e.length===0||r.toLowerCase().includes(e))&&n.push(s)}return n}cancelHistorySearch(){if(this.historySearch===null)return;let e=this.historySearch.savedDraft;this.historySearch=null,this.buffer=[...e.buffer],this.row=e.row,this.col=e.col}loadEntry(e){this.buffer=e.split(`
151
+ `),this.buffer.length===0&&(this.buffer=[""]),this.row=this.buffer.length-1,this.col=(this.buffer[this.row]??"").length}send(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=[...this.attachments];return this.clearBuffer(),n.trim().length===0?[{type:"queue-remove",index:i}]:[{type:"queue-edit",index:i,text:n,displayText:e,attachments:o}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"send",text:n,displayText:e,planMode:s,attachments:r}]}amend(){let e=this.bufferText(),n=this.expandPastes(e);if(this.queueIndex>=0&&this.queueIndex<this.queue.length){let i=this.queueIndex,o=this.planMode,a=[...this.attachments],c=n.trim().length===0&&a.length===0;return this.clearBuffer(),c?[{type:"queue-remove",index:i}]:[{type:"queue-remove",index:i},{type:"amend",text:n,displayText:e,planMode:o,attachments:a}]}if(n.trim().length===0&&this.attachments.length===0)return[];let s=this.planMode,r=[...this.attachments];return this.clearBuffer(),[{type:"amend",text:n,displayText:e,planMode:s,attachments:r}]}handleHome(){return this.row!==0||this.col!==0?(this.row=0,this.col=0,[]):[{type:"scroll-to-top"}]}handleEnd(){let e=this.buffer.length-1,n=(this.buffer[e]??"").length;return this.row!==e||this.col!==n?(this.row=e,this.col=n,[]):[{type:"scroll-to-bottom"}]}handleCtrlC(){if(this.queueIndex>=0){let e=this.queueIndex;return this.queueIndex=-1,this.restoreDraft(),[{type:"queue-remove",index:e}]}return!this.bufferIsEmpty()||this.attachments.length>0?(this.recordEdit(),this.buffer=[""],this.row=0,this.col=0,this.attachments=[],this.historyIndex=-1,this.savedDraft=null,this.savedAttachments=null,[]):this.turnRunning?[{type:"cancel"}]:[{type:"exit"}]}}});var Yi,nc,Lu=K(()=>{"use strict";Yi=class{constructor(e){this.term=e}term;lastFrameRows=new Map;lastFrameW=0;lastFrameH=0;clearCache(){this.lastFrameRows.clear(),this.lastFrameW=0,this.lastFrameH=0}ensureSize(e,n){return e!==this.lastFrameW||n!==this.lastFrameH?(this.lastFrameRows.clear(),this.lastFrameW=e,this.lastFrameH=n,!0):!1}paintRow(e,n,s){e<1||e>this.term.height||this.lastFrameRows.get(e)!==n&&(this.lastFrameRows.set(e,n),this.term.moveTo(1,e),s(),this.term.styleReset(),this.term.eraseLineAfter())}},nc=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 dR from"path";function Xo(t){return ow[dR.extname(t).toLowerCase()]??null}function cR(t){return Xo(t)!==null}function Bu(t){let e=t.match(/^data:(image\/[a-z0-9.+\-]+);base64,([A-Za-z0-9+/=]+)$/);if(!e)return null;let n=e[1].toLowerCase();if(!lR.has(n))return null;let s=e[2],r=s.endsWith("==")?2:s.endsWith("=")?1:0,i=Math.floor(s.length*3/4)-r;return{mimeType:n,data:s,sizeBytes:i}}function uR(t){return Bu(t)!==null}function nn(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${(t/1024).toFixed(0)}KB`:`${t}B`}function aw(t){let e=t.trim();if(e.length===0)return null;let n=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]??"");)s++;if(s>=e.length)break;let r=e[s],i="";if(r==="'"||r==='"'){let a=r;for(s++;s<e.length&&e[s]!==a;)i+=e[s],s++;if(s>=e.length)return null;s++}else for(;s<e.length&&!/\s/.test(e[s]??"");)e[s]==="\\"&&s+1<e.length?(i+=e[s+1],s+=2):(i+=e[s],s++);if(i.startsWith("data:")){if(!uR(i))return null;n.push(i);continue}let o=i;if(o.startsWith("file://")&&(o=decodeURI(o.slice(7))),!o.startsWith("/")||!cR(o))return null;n.push(o)}return n.length>0?n:null}var Bn,ow,lR,sc=K(()=>{"use strict";Bn=10*1024*1024,ow={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};lR=new Set(Object.values(ow))});import fR from"string-width";function dw(t,e){if(!t||e<=0)return 0;let n=0;for(let s of pR.segment(t)){let r=fR(s.segment);if(e<n+r)return s.index;if(n+=r,e===n)return s.index+s.segment.length}return t.length}function cw(t,e){if(e<=0)return 0;let n=0,s=0;for(let r of t)if(r.width>0&&e<n+r.width||(n+=r.width,s+=r.text.length,r.width>0&&e===n))return s;return s}var pR,lw=K(()=>{"use strict";pR=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{spawn as mR}from"child_process";import Nu from"fs/promises";import hR from"os";import gR from"path";async function pw(t={}){let e={...Du,...t};return e.platform==="darwin"?vR(e):e.platform==="linux"?SR(e):{ok:!1,reason:`clipboard paste is not supported on ${e.platform}`}}async function mw(t={}){let e={...Du,...t},n,s;if(e.platform==="darwin")n="pbpaste",s=[];else if(e.platform==="linux")if(e.env.WAYLAND_DISPLAY&&await Qi(e,"wl-paste"))n="wl-paste",s=["--primary","-n"];else if(e.env.DISPLAY&&await Qi(e,"xclip"))n="xclip",s=["-selection","primary","-o"];else return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste the selection"};else return{ok:!1,reason:`selection paste is not supported on ${e.platform}`};try{let r=await Zo(e.spawn,n,s);return r.length===0?{ok:!1,reason:"selection is empty"}:{ok:!0,kind:"text",text:Hu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"selection read failed"}}}async function hw(t,e={}){let{target:n="both",...s}=e,r={...Du,...s},i=await yR(r,t,n);if(i.ok)return i;let o=wR(r,t,n);return o.ok||o.reason!==gw?o:i}async function yR(t,e,n){let s=Buffer.from(e,"utf-8");if(t.platform==="darwin")try{return await rc(t.spawn,"pbcopy",[],s),{ok:!0,method:"pbcopy"}}catch{return{ok:!1,reason:"pbcopy failed"}}if(t.platform==="linux"){let r=n==="clipboard"||n==="both",i=n==="primary"||n==="both";return t.env.WAYLAND_DISPLAY&&await Qi(t,"wl-copy")?fw(t,s,"wl-copy",[],["--primary"],r,i):t.env.DISPLAY&&await Qi(t,"xclip")?fw(t,s,"xclip",["-selection","clipboard","-i"],["-selection","primary","-i"],r,i):{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to copy to the clipboard"}}return{ok:!1,reason:`clipboard copy is not supported on ${t.platform}`}}async function fw(t,e,n,s,r,i,o){let a=n;if(i){try{await rc(t.spawn,n,s,e)}catch{return{ok:!1,reason:`${n} failed`}}if(o)try{await rc(t.spawn,n,r,e)}catch{}return{ok:!0,method:a}}try{return await rc(t.spawn,n,r,e),{ok:!0,method:a}}catch{return{ok:!1,reason:`${n} failed`}}}function wR(t,e,n){let s=Buffer.from(e,"utf-8").toString("base64");if(s.length>uw)return{ok:!1,reason:`selection is too large for terminal clipboard escape (${s.length} > ${uw} bytes)`};let i=`\x1B]52;${n==="both"?"cp":n==="primary"?"p":"c"};${s}\x07`;return t.env.TMUX&&(i=`\x1BPtmux;${i.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`),(t.ttyWrite??bR)(i)?{ok:!0,method:"osc52"}:{ok:!1,reason:gw}}function bR(t){let e=[process.stderr,process.stdout];for(let n of e)if(n&&n.isTTY)try{return n.write(t),!0}catch{}return!1}async function vR(t){let e=gR.join(t.tmpdir(),`hydra-clipboard-${Date.now()}-${process.pid}.png`),n=["set png_data to the clipboard as \xABclass PNGf\xBB",`set out_file to (open for access (POSIX file "${e}") with write permission)`,"write png_data to out_file","close access out_file"],s=[];for(let r of n)s.push("-e",r);try{await yw(t.spawn,"osascript",s);let r=await AR(e,!0);if(r.ok||r.reason.startsWith("clipboard image is"))return r}catch{await Nu.unlink(e).catch(()=>{})}try{let r=await Zo(t.spawn,"pbpaste",[]);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Hu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function SR(t){let e=await kR(t);if(!e)return{ok:!1,reason:"install wl-clipboard (Wayland) or xclip (X11) to paste from the clipboard"};let n=await CR(t,e),s=xR(n);if(s)try{let r=await Zo(t.spawn,e.cmd,e.imageArgs(s));if(r.length>0)return r.length>Bn?{ok:!1,reason:`clipboard image is ${nn(r.length)}, max ${nn(Bn)}`}:{ok:!0,kind:"image",attachment:{mimeType:s,data:r.toString("base64"),sizeBytes:r.length}}}catch{}try{let r=await Zo(t.spawn,e.cmd,e.textArgs);return r.length===0?{ok:!1,reason:"clipboard is empty"}:{ok:!0,kind:"text",text:Hu(r.toString("utf-8"))}}catch{return{ok:!1,reason:"clipboard read failed"}}}async function kR(t){return t.env.WAYLAND_DISPLAY&&await Qi(t,"wl-paste")?{cmd:"wl-paste",listTargetsArgs:["--list-types"],imageArgs:e=>["-t",e],textArgs:["-n"]}:t.env.DISPLAY&&await Qi(t,"xclip")?{cmd:"xclip",listTargetsArgs:["-selection","clipboard","-t","TARGETS","-o"],imageArgs:e=>["-selection","clipboard","-t",e,"-o"],textArgs:["-selection","clipboard","-o"]}:null}function xR(t){let e=new Set(t.map(n=>n.toLowerCase()));for(let n of IR)if(e.has(n))return n;return null}async function CR(t,e){try{return(await Zo(t.spawn,e.cmd,e.listTargetsArgs)).toString("utf-8").split(`
152
+ `).map(s=>s.trim()).filter(s=>s.length>0)}catch{return[]}}function Hu(t){return t.replace(/\r\n?/g,`
153
+ `)}async function Qi(t,e){try{return await yw(t.spawn,"which",[e]),!0}catch{return!1}}async function AR(t,e){try{let n=await Nu.readFile(t);return e&&await Nu.unlink(t).catch(()=>{}),n.length===0?{ok:!1,reason:"no image on clipboard"}:n.length>Bn?{ok:!1,reason:`clipboard image is ${nn(n.length)}, max ${nn(Bn)}`}:{ok:!0,kind:"image",attachment:{mimeType:Xo(t)??"image/png",data:n.toString("base64"),sizeBytes:n.length}}}catch{return{ok:!1,reason:"failed to read clipboard image"}}}function yw(t,e,n){return new Promise((s,r)=>{let i=t(e,n);i.stdout?.on("data",()=>{}),i.stderr?.on("data",()=>{}),i.on("error",r),i.on("close",o=>{o===0?s():r(new Error(`${e} exited ${o}`))})})}function rc(t,e,n,s){return new Promise((r,i)=>{let o=t(e,n,{stdio:["pipe","ignore","ignore"]});o.stdout?.on("data",()=>{}),o.stderr?.on("data",()=>{}),o.on("error",i),o.on("close",c=>{c===0?r():i(new Error(`${e} exited ${c}`))});let a=o.stdin;if(!a){i(new Error(`${e} has no stdin`));return}a.on("error",i),a.end(s)})}function Zo(t,e,n){return new Promise((s,r)=>{let i=t(e,n),o=[],a=i.stdout===null,c=null,d=!1,l=()=>{d||!a||c===null||(d=!0,c===0?s(Buffer.concat(o)):r(new Error(`${e} exited ${c}`)))};i.stdout?.on("data",u=>{o.push(typeof u=="string"?Buffer.from(u):u)}),i.stdout?.on("end",()=>{a=!0,l()}),i.stderr?.on("data",()=>{}),i.on("error",u=>{d||(d=!0,r(u))}),i.on("close",u=>{c=u??0,l()})})}var Du,uw,gw,IR,Uu=K(()=>{"use strict";sc();Du={platform:process.platform,env:process.env,spawn:mR,tmpdir:hR.tmpdir};uw=74994;gw="no TTY available for OSC 52 clipboard write";IR=["image/png","image/jpeg","image/gif","image/webp"]});function RR(){ea===0&&process.stdout.write(my),ea++}function TR(){ea!==0&&(ea--,ea===0&&process.stdout.write(hy))}function Be(t){RR();try{t()}finally{TR()}}var ea,ju=K(()=>{"use strict";Jo();ea=0});import{spawn as ER}from"child_process";import{statSync as PR}from"fs";import{homedir as ww}from"os";import{isAbsolute as bw,resolve as MR}from"path";import Nn from"string-width";import _R from"wrap-ansi";function UR(t){let e=t.replace(/\r\n?$|\n$/,"");return HR.test(e)?e:null}function jR(t){return t.includes("LEFT")?"left":t.includes("RIGHT")?"right":t.includes("MIDDLE")?"middle":t==="MOUSE_DRAG"||t==="MOUSE_BUTTON_RELEASED"?"left":"other"}function vw(t,e,n,s=null,r=null,i=null){let o=r===null?"":`a${r}`,a=i===null?"":`s${i.start}:${i.end}${i.toEndOfLine?"f":""}`;if(!n)return`${t}|${e}|empty|${s??""}|${o}|${a}`;let c=n.iterm2Image?`i${n.iterm2Image.heightCells}:${n.iterm2Image.data.length}`:"";return`${t}|${e}|${n.prefix??""}|${n.prefixStyle??""}|${n.body}|${n.bodyStyle??""}|${n.ansi?"1":"0"}|${n.fillRow?"1":"0"}|${s??""}|${o}|${a}|${c}`}function as(t,e){let n=[];for(let s=0;s<t.length;s++){let r=t[s]??"";if(r.length===0){n.push({bufferIdx:s,startCol:0,endCol:0});continue}let i=0;for(;i<r.length;){if(r.length-i<=e){n.push({bufferIdx:s,startCol:i,endCol:r.length}),i=r.length;break}let o=-1;for(let a=i+e-1;a>=i;a--){let c=r[a];if(c===" "||c===" "){o=a+1;break}}o===-1&&(o=i+e),n.push({bufferIdx:s,startCol:i,endCol:o}),i=o}}return n.length===0&&n.push({bufferIdx:0,startCol:0,endCol:0}),n}function Us(t,e,n){let s=0,r=0,i=-1;for(let c=0;c<t.length;c++){let d=t[c];if(!(!d||d.bufferIdx!==e.row)&&(i=c,e.col>=d.startCol&&e.col<d.endCol)){s=c,r=e.col-d.startCol,i=-1;break}}if(i!==-1){let c=t[i];c&&(s=i,r=e.col-c.startCol)}let o=Math.min(n,Math.max(1,t.length)),a=0;return t.length>o&&(a=Math.max(0,Math.min(t.length-o,s-(o-1))),s<a&&(a=s),s>=a+o&&(a=s-o+1)),{cursorVisualRow:s,cursorVisualCol:r,windowStart:a,rendered:o}}function Sw(t,e,n,s,r=null,i=0){if(e.length===0)return;if(s.length===0){os(t,e,n);return}let o=e.toLowerCase(),a=0;for(;a<e.length;){let c=o.indexOf(s,a);if(c===-1){os(t,e.slice(a),n);return}c>a&&os(t,e.slice(a,c),n);let d=r!==null&&c===r;os(t,e.slice(c,c+s.length),d?"search-highlight-active":"search-highlight"),a=c+s.length}}function ta(t){return t==="agent"||t==="thought"||t==="heading-1"||t==="heading-2"||t==="heading-3"||t==="plan"||t==="plan-done"||t==="plan-pending"}function os(t,e,n){if(e.length!==0)switch(n){case"user":t.bgColorGrayscale.bold.noFormat(43,e);return;case"agent":t(e);return;case"thought":t.brightBlack(e);return;case"tool":t.brightBlue.noFormat(e);return;case"tool-status-ok":t.green.noFormat(e);return;case"tool-status-fail":t.bold.red.noFormat(e);return;case"tool-status-pending":t.dim.noFormat(e);return;case"tool-status-running":t.brightYellow.noFormat(e);return;case"tool-status-cancelled":t.dim.noFormat(e);return;case"plan":t.brightYellow(e);return;case"plan-done":t.green(e);return;case"plan-pending":t.dim(e);return;case"system":t.brightYellow.noFormat(e);return;case"info":t.cyan.noFormat(e);return;case"dim":t.dim.noFormat(e);return;case"code":t.bgColorGrayscale.white.noFormat(28,e);return;case"heading-1":t.bold.brightYellow(e);return;case"heading-2":t.bold.brightCyan(e);return;case"heading-3":t.bold(e);return;case"search-highlight":t.bgBrightYellow.black.noFormat(e);return;case"selection-highlight":t.inverse.noFormat(e);return;case"search-highlight-active":t.bgRed.brightWhite.noFormat(e);return;default:t.noFormat(e)}}function qR(t,e){return e<=0?[t]:t.length===0?[""]:_R(t,e,{hard:!0,trim:!1}).split(`
154
+ `)}function Pw(t){Ew=t}function Mw(t,e){if(t==="wide")return!0;if(t==="narrow")return!1;let n=e.LC_ALL||e.LC_CTYPE||e.LANG||"";return!!(/^(ja|ko|zh)(_|\.|@|$)/i.test(n)||e.TERM_PROGRAM==="Apple_Terminal")}function Hs(t){return Nn(t,{ambiguousIsNarrow:!Ew})}function Gi(t,e){if(t.charCodeAt(e)!==94)return null;let n=t[e+1];if(n===void 0)return null;if(n==="^")return{text:"^^",width:1};if(n==="["){let s=t.indexOf("]",e+2);if(s!==-1)return{text:t.slice(e,s+1),width:0}}return WR.test(n)?{text:t.slice(e,e+2),width:0}:null}function kw(t){let e=new Array(t.length+1).fill(0),n="",s=0;for(;s<t.length;){e[s]=n.length;let r=Gi(t,s);if(r){r.width>0&&(n+="^");for(let i=1;i<r.text.length;i++)e[s+i]=n.length;s+=r.text.length;continue}n+=t[s],s+=1}return e[t.length]=n.length,{clean:n,rawToClean:e}}function Iw(t){if(!t.includes("^"))return t;let e="",n=0;for(;n<t.length;){let s=Gi(t,n);if(s){s.width>0&&(e+="^"),n+=s.text.length;continue}e+=t[n],n+=1}return e}function zR(t){if(!t.includes("^"))return"";let e="",n=0;for(;n<t.length;){let s=Gi(t,n);if(s){s.width===0&&(e+=s.text),n+=s.text.length;continue}n+=1}return e}function _w(t){if(!t.includes("^"))return!1;for(let e=0;e<t.length;e++)if(Gi(t,e))return!0;return!1}function*Zu(t){let e=0;for(;e<t.length;){let n=Gi(t,e);if(n){yield{text:n.text,width:n.width},e+=n.text.length;continue}let s=t.length,r=t.indexOf("^",e);for(;r!==-1&&r<t.length;){if(Gi(t,r)){s=r;break}r=t.indexOf("^",r+1)}if(s===e){yield{text:"^",width:1},e+=1;continue}for(let{segment:i}of Xu.segment(t.slice(e,s)))yield{text:i,width:Hs(i)};e=s}}function JR(t,e,n){let s=`\x1B]1337;File=inline=1;height=${e};preserveAspectRatio=1:${t}\x07`;return n?`\x1BPtmux;${s.replace(/\x1b/g,"\x1B\x1B")}\x1B\\`:s}function KR(t,e,n={}){if(e<=0)return[t];if(t.length===0)return[""];let s=n.stripMarkup===!0&&_w(t);return!s&&!Tw.test(t)?VR(t,e):YR(t,e,s)}function VR(t,e){let n=[],s=t;for(;s.length>e;){let r=s.slice(0,e+1),i=-1;for(let o=Math.min(e,r.length-1);o>=0;o--)if(r[o]===" "){i=o;break}i<=0?(n.push(s.slice(0,e)),s=s.slice(e)):(n.push(s.slice(0,i)),s=s.slice(i+1))}return n.push(s),n}function YR(t,e,n){let s=[],r=n?[...Zu(t)]:QR(t),i=0;for(;i<r.length;){let o="",a=0,c=-1,d="";for(;i<r.length;){let l=r[i];if(a+l.width>e){l.text===" "&&l.width===1&&(c=i,d=o);break}l.text===" "&&l.width===1&&(c=i,d=o),o+=l.text,a+=l.width,i+=1}if(i>=r.length){s.push(o);break}c>=0?(s.push(d),i=c+1):o.length===0?(s.push(r[i].text),i+=1):s.push(o)}return s}function QR(t){let e=[];for(let{segment:n}of Xu.segment(t))e.push({text:n,width:Hs(n)});return e}function dt(t,e,n={}){if(e<=0)return"";let s=n.stripMarkup===!0&&_w(t);if(!s&&t.length<=e&&!Tw.test(t))return t;if(!s)return Hs(t)<=e?t:e<=1?xw(t,e):xw(t,e-1)+"\u2026";let r=[...Zu(t)],i=0;for(let o of r)i+=o.width;return i<=e?t:e<=1?Cw(r,e):Cw(r,e-1)+"\u2026"}function xw(t,e){if(e<=0)return"";let n="",s=0;for(let{segment:r}of Xu.segment(t)){let i=Hs(r);if(s+i>e)break;n+=r,s+=i}return n}function Cw(t,e){if(e<=0)return"";let n="",s=0;for(let r of t){if(s+r.width>e)break;n+=r.text,s+=r.width}return n}function GR(t){let e=t.indexOf(`
155
+ `);return e===-1?t:`${t.slice(0,e)} \u21B5`}function Aw(t){if(!t)return null;let e=[];return typeof t.used=="number"?typeof t.size=="number"&&t.size>0?e.push(`${oc(t.used)}/${oc(t.size)}`):e.push(oc(t.used)):typeof t.size=="number"&&e.push(`/${oc(t.size)}`),typeof t.costAmount=="number"&&e.push(su(t.costAmount,t.costCurrency)),e.length===0?null:e.join(" \xB7 ")}function oc(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function cc(t){switch(t){case"ENTER":case"KP_ENTER":return"enter";case"ALT_ENTER":case"META_ENTER":return"alt-enter";case"SHIFT_ENTER":return"shift-enter";case"CTRL_ENTER":return"ctrl-enter";case"CTRL_J":return"ctrl-enter";case"ALT_B":case"META_B":return"alt-b";case"ALT_F":case"META_F":return"alt-f";case"ALT_N":case"META_N":return"alt-n";case"ALT_TAB":case"META_TAB":return"alt-tab";case"CTRL_T":return"ctrl-t";case"SHIFT_TAB":return"shift-tab";case"TAB":return"tab";case"UP":return"up";case"DOWN":return"down";case"LEFT":return"left";case"RIGHT":return"right";case"HOME":return"home";case"END":return"end";case"BACKSPACE":return"backspace";case"DELETE":return"delete";case"CTRL_A":return"ctrl-a";case"CTRL_B":return"ctrl-b";case"CTRL_C":return"ctrl-c";case"CTRL_D":return"ctrl-d";case"CTRL_E":return"ctrl-e";case"CTRL_F":return"ctrl-f";case"CTRL_G":return"ctrl-g";case"CTRL_K":return"ctrl-k";case"CTRL_L":return"ctrl-l";case"CTRL_N":return"ctrl-n";case"CTRL_O":return"ctrl-o";case"CTRL_P":return"ctrl-p";case"CTRL_Q":return"ctrl-q";case"CTRL_R":return"ctrl-r";case"CTRL_S":return"ctrl-s";case"CTRL_U":return"ctrl-u";case"CTRL_V":return"ctrl-v";case"CTRL_W":return"ctrl-w";case"CTRL_X":return"ctrl-x";case"CTRL_Y":return"ctrl-y";case"ESCAPE":return"escape";default:return null}}function ac(){let t=[Ui,ji,cy,qi,ly,Iu,ns,Rr,Tr,Ar,Cr,"\x1B>",zo,qd,Wd,"\x1B]9;4;0\x07",iy].join("");try{process.stdout.write(t)}catch{}}function $w(t){let e=[["width",80],["height",24]];for(let[n,s]of e){let r=Object.getOwnPropertyDescriptor(t,n);if(r&&r.get)continue;let i=Symbol(`raw-${n}`),o=t;o[i]=r?r.value:void 0,Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){let a=this[i];return typeof a=="number"&&Number.isFinite(a)&&a>0?a:s},set(a){this[i]=a}})}}function Rw(t,e){let n={97:"ctrl-a",98:"ctrl-b",99:"ctrl-c",100:"ctrl-d",101:"ctrl-e",102:"ctrl-f",103:"ctrl-g",104:"backspace",105:"tab",106:"ctrl-enter",107:"ctrl-k",108:"ctrl-l",109:"enter",110:"ctrl-n",111:"ctrl-o",112:"ctrl-p",113:"ctrl-q",114:"ctrl-r",115:"ctrl-s",116:"ctrl-t",117:"ctrl-u",118:"ctrl-v",119:"ctrl-w",120:"ctrl-x",121:"ctrl-y"};return e===5?n[t]??null:t===27?"escape":t===9?e===2?"shift-tab":e===3?"alt-tab":e===1?"tab":null:t===13?e===2?"shift-enter":e===3?"alt-enter":e===5?"ctrl-enter":e===1?"enter":null:t===127&&e===1?"backspace":(t===95||t===47)&&e===5?"ctrl-underscore":(t===95||t===47)&&e===7?"alt-underscore":e===3?t===98||t===66?"alt-b":t===102||t===70?"alt-f":t===110||t===78?"alt-n":t===95?"alt-underscore":null:null}var qu,ic,Wu,zu,$R,qe,Ye,FR,We,Ju,Ku,OR,LR,BR,Vu,Yu,Qu,NR,DR,HR,dc,Tw,Xu,Ew,WR,Gu,ef=K(()=>{"use strict";Lu();ru();he();En();sc();Ni();lw();Uu();ju();Jo();qu=500,ic=1,Wu=/[A-Za-z0-9_]/,zu=/[A-Za-z0-9_./\-~+@]/,$R=/\x1b\[[0-9;]*[A-Za-z]/g,qe=1,Ye=1,FR=1,We=0,Ju=8,Ku=5,OR=12,LR=12,BR=30,Vu=6,Yu=4,Qu=2,NR=1e3,DR=1e4,HR=/^(https?|ftp):\/\/\S+$/;dc=class{term;dispatcher;onKey;onBlockClick;onBlockDoubleClick;onMouse;onBlockVisible;onSuspend;pendingVisibleKeys=new Set;lines=[];keyedBlocks=new Map;stickyBottomKey=null;streamingActive=!1;hideThoughts=!1;lastPromptRows=0;queuedTexts=[];lastQueueEditingIndex=-1;attachments=[];repaintPaused=0;repaintPending=!1;contentRepaintThrottleMs;painter;scheduler;maxScrollbackLines;nextLineId=1;lineIds=new WeakMap;wrapCache=new Map;wrapCacheWidth=0;wrapOrigin=new WeakMap;permissionPrompt=null;optionsPrompt=null;confirmPrompt=null;compactionPrompt=null;helpPrompt=null;completions=[];scrollOffset=0;scrollbackSearch=null;scrollbackHighlight=null;selection=null;selectionRenderBounds=null;bannerNotification=null;bannerNotificationTimer=null;bannerSearchIndicator=null;compactionIndicator=null;btwOverlayOpen=!1;btwOverlayMaxHeight=12;btwOverlayLines=[];btwOverlayLabel="";btwOverlayStatus="busy";btwOverlaySessionId=null;btwOverlayUsage=void 0;focusedPane="main";banner={status:"ready",currentMode:void 0,hint:"\u21E7\u21E5 mode \xB7 \u2303P pick \xB7 \u2303G guide \xB7 \u2303D detach",queued:0};bannerHits=null;sessionbar={agent:"?",cwd:"?",sessionId:"?"};lastWindowTitle=null;resizeHandler;keyHandler;mouseHandler;pressCell=null;selectionAnchor=null;selectionDragStarted=!1;doubleClickPending=!1;lastLeftClick=null;pendingBlockClick=null;started=!1;terminalKitStdinHandler=null;pasteActive=!1;pasteBuffer="";rawStdinHandler;mouseEnabled;currentPointerShape="default";inAppSelectionEnabled;selectionClipboard;openFileCommand;progressIndicatorEnabled;emergencyCleanupInstalled=!1;onProcessExit=null;onProcessSignal=null;onProcessUncaught=null;selectiveMouseSupported=!1;selectiveMouseProbing=!1;selectiveMouseProbeTimer=null;lastProgressState=0;readonly;constructor(e){this.term=e.term,this.dispatcher=e.dispatcher;let n=e.onKey;this.onKey=i=>{this.selection!==null&&i.length>0&&this.clearSelection(),n(i)},this.onBlockClick=e.onBlockClick,this.onBlockDoubleClick=e.onBlockDoubleClick,this.onMouse=e.onMouse,this.onBlockVisible=e.onBlockVisible,this.onSuspend=e.onSuspend,this.contentRepaintThrottleMs=e.repaintThrottleMs??NR,this.painter=new Yi(this.term),this.scheduler=new nc({isStarted:()=>this.started,isRepaintPaused:()=>this.repaintPaused>0,markRepaintPending:()=>{this.repaintPending=!0},throttleMs:()=>this.contentRepaintThrottleMs,doRepaint:()=>this.repaint()}),this.maxScrollbackLines=e.maxScrollbackLines??DR,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(ku),this.mouseEnabled?this.term.grabInput({mouse:"motion"}):this.term.grabInput(!0),this.term.hideCursor(!1),this.term.on("key",this.keyHandler),this.mouseEnabled&&this.term.on("mouse",this.mouseHandler),this.term.on("resize",this.resizeHandler),this.installBracketedPaste(),this.installSelectiveMouseReporting(),this.installEmergencyCleanup(),this.lastProgressState=0,this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.repaint())}stop(e={}){this.started&&(this.bannerNotificationTimer&&(clearTimeout(this.bannerNotificationTimer),this.bannerNotificationTimer=null),this.scheduler.cancel(),this.cancelPendingBlockClick(),this.uninstallSelectiveMouseReporting(),this.uninstallBracketedPaste(),this.uninstallEmergencyCleanup(),this.term.off("key",this.keyHandler),this.mouseEnabled&&this.term.off("mouse",this.mouseHandler),this.term.off("resize",this.resizeHandler),this.term.grabInput(!1),this.term.hideCursor(!1),this.currentPointerShape!=="default"&&(process.stdout.write(Wd),this.currentPointerShape="default"),e.keepFullscreen||process.stdout.write(zo),this.writeProgressIndicator(0),this.started=!1,e.keepFullscreen||(ac(),this.term.fullscreen(!1),this.term(`
156
+ `)))}installBracketedPaste(){process.stdout.write(jd),process.stdout.write(ay),process.stdout.write(dy),process.stdout.write(oy);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(ns),process.stdout.write(Rr),process.stdout.write(Tr),process.stdout.write(Ar),process.stdout.write(Cr),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(uy),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(Iu),this.selectiveMouseSupported=!1)}installEmergencyCleanup(){this.emergencyCleanupInstalled||(this.emergencyCleanupInstalled=!0,this.onProcessExit=()=>ac(),this.onProcessSignal=e=>{ac(),process.off(e,this.onProcessSignal),process.kill(process.pid,e)},this.onProcessUncaught=e=>{ac(),process.stderr.write(`
157
157
  uncaught: ${e.stack??e.message}
158
- `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write(Qg),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(Ei)){this.handleRawStdinSegment(n);return}if(n.includes(`
158
+ `),process.exit(1)},process.on("exit",this.onProcessExit),process.on("SIGTERM",this.onProcessSignal),process.on("SIGHUP",this.onProcessSignal),process.on("uncaughtException",this.onProcessUncaught))}uninstallEmergencyCleanup(){this.emergencyCleanupInstalled&&(this.emergencyCleanupInstalled=!1,this.onProcessExit&&(process.off("exit",this.onProcessExit),this.onProcessExit=null),this.onProcessSignal&&(process.off("SIGTERM",this.onProcessSignal),process.off("SIGHUP",this.onProcessSignal),this.onProcessSignal=null),this.onProcessUncaught&&(process.off("uncaughtException",this.onProcessUncaught),this.onProcessUncaught=null))}consumeSelectiveMouseSequences(e){if(!e.includes("\x1B["))return e;if(this.selectiveMouseProbing){let a=/\x1b\[\?(\d+);(\d+) w/.exec(e);a&&(this.selectiveMouseProbing=!1,this.selectiveMouseProbeTimer&&(clearTimeout(this.selectiveMouseProbeTimer),this.selectiveMouseProbeTimer=null),this.selectiveMouseSupported=!0,process.stdout.write(fy),e=e.slice(0,a.index)+e.slice(a.index+a[0].length))}if(!this.selectiveMouseSupported)return e;let n=/\x1b\[<(64|65);\d+;\d+M/g,s="",r=0,i;for(;(i=n.exec(e))!==null;)s+=e.slice(r,i.index),i[1]==="64"?this.scrollBy(3):this.scrollBy(-3),r=i.index+i[0].length;return s+=e.slice(r),s}handleRawStdin(e){let n=e.toString("binary");if(n=this.consumeSelectiveMouseSequences(n),n.length!==0){if(this.pasteActive){this.handleRawStdinSegment(n);return}if(n===""&&this.onSuspend){this.onSuspend();return}if(this.onSuspend&&(n==="\x1B[27;5;122~"||n==="\x1B[122;5u")){this.onSuspend();return}if(n===""){this.onKey([{type:"key",name:"ctrl-underscore"}]);return}if(n==="\x1B"||n==="\x1B_"){this.onKey([{type:"key",name:"alt-underscore"}]);return}if(/\x1b\[27;\d+;\d+~/.test(n)){this.handleCsi27Stdin(n);return}if(n.includes(Hi)){this.handleRawStdinSegment(n);return}if(n.includes(`
159
159
  `)){let s=n.split(`
160
- `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=dw(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=dw(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n=Ei,s=Oo;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
161
- `);this.pasteBuffer="";let a=jy(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=wR(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),c=n.length-s.count,d=this.lines.splice(s.start,s.count,...n);for(let l of d)this.forgetLine(l);if(this.trackLines(n),this.invalidateSelectionIfTouches(d),s.count=n.length,c!==0)for(let[l,f]of this.keyedBlocks)l!==e&&f.start>s.start&&(f.start+=c);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
162
- `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let f=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-f}}else{if(this.lines.length>0){let f=this.lines[this.lines.length-1];if(!(f&&f.body===""&&(!f.prefix||f.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let f={prefix:d,body:l,bodyStyle:s};this.lines.push(f),this.trackLine(f),c+=this.wrappedRowsOf(f)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=Hu(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&De(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",c;r.ansi?c=s===e.loIdx||s===e.hiIdx?"":a.replace(uR,""):(c=a.slice(o.start,o.end),zo(r.bodyStyle)&&(c=rw(c))),n.push(c)}return n.join(`
163
- `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let f=this.lineIds.get(l);if(f===void 0)continue;let u=(l.body??"").length,p=d===r?Math.max(0,Math.min(u,o)):0,m=d===i?Math.max(0,Math.min(u,a)):u;c.set(f,{start:p,end:m,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null||e.ansi)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,f]of this.keyedBlocks)if(!n.has(l)&&f.start>=c&&f.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(uu),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&this.clearSelection(),this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.focusedPane="main",this.scheduleRepaint())}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=Gd(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n),r=bR(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),s!==null&&i!=="release"){let o=this.keyAtRow(s.y)!==null;this.setPointerShape(o?"pointer":"default")}if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let o=this.lastLeftClick;o!==null&&s!==null&&Math.abs(s.x-o.x)<=Jd&&Math.abs(s.y-o.y)<=Jd&&Date.now()-o.t<=_u||this.flushPendingBlockClick(),this.pressCell=s,this.handleSelectionPress(s);return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let c=this.keyAtRow(s.y);if(c!==null){let d=s.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;this.schedulePendingBlockClick(c,s.y-d)}}this.handleSelectionRelease(s)}}handleSelectionPress(e){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let n=this.resolveCellToSource(e.x,e.y);if(n===null){this.lastLeftClick=null;return}this.selectionAnchor=n;let s=Date.now(),r=this.lastLeftClick;if(r!==null&&s-r.t<=_u&&Math.abs(e.x-r.x)<=Jd&&Math.abs(e.y-r.y)<=Jd){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let a=this.keyAtRow(e.y);if(a!==null){let c=e.y;for(;c>1&&this.keyAtRow(c-1)===a;)c-=1;let d=e.y-c;if(this.onBlockDoubleClick(a,d)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(n)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let o=this.wordBoundsAt(n);o!==null&&(this.setSelection({sourceLineId:n.sourceLineId,offset:o.start},{sourceLineId:n.sourceLineId,offset:o.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}handleSelectionRelease(e){let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=sw(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length,a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!$u.test(r[a]))return null;let c=a;for(;c>0&&$u.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&$u.test(r[d]);)d++;let l=s.length,f=s.length;for(let u=0;u<i.length;u++)if(i[u]===c&&l===s.length&&(l=u),i[u]===d&&f===s.length){f=u;break}return{start:l,end:f}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=sw(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let m=p.url;return{raw:m.startsWith("file://")?m.slice(7):m,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!Ou.test(r[a]))return null;let c=a;for(;c>0&&Ou.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Ou.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let f=null,u=r.slice(d).match(/^:(\d+)(?::\d+)?/);return u&&(f=Number.parseInt(u[1],10)),{raw:l,line:f}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?Zy():`${Zy()}/${n.slice(2)}`);let s=ew(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=ew(n)?n:cR(this.sessionbar.cwd,n);if(s)return i;try{if(dR(i).isFile())return i}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let f of c)f.includes("%f")&&(d=!0),!(o===""&&f.includes("%n"))&&l.push(f.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let f=aR(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});f.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),f.unref();let u=s===null?i:`${i}:${s}`;this.notify(`opening ${u}`)}catch(f){this.notify(`open file failed: ${f.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},_u);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&Gy(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?Xg:Md))}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),f=i-l;return f<0||f>=d.length?null:d[f]?.blockKey??null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),f=Math.max(0,i-l.length),u=o-f;if(u<0||u>=l.length)return null;let p=l[u];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Ts(p.prefix??""),w=e-1-h;if(w<0)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=zo(p.bodyStyle)?Wy(ju(p.body),w):qy(p.body,w);return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+b}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let f=this.lines[l];f&&(r+=this.wrapOne(f,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),f=0;for(let u=0;u<l.length;u++){let p=l[u];if(!p)continue;let m=p.body.length;if(e.col<f+m){o=l.length-1-u;break}f+=m}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-Le-Be-ze-Be-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),De(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-ze-Be-Le;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSeparator(n-Le),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=Hu(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=qh(this.sessionbar.agent,this.sessionbar.model),o=Ue(this.sessionbar.cwd),a=aw(this.sessionbar.usage),c=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,c,()=>{let d=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+d,f=Math.max(8,e-l),u,p;if(r){let m=Math.min(r.length,8);u=Math.min(o.length,Math.max(8,f-m)),p=Math.max(0,f-u)}else p=0,u=f;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(lt(o,u)),r&&this.term(" \xB7 ").bold.noFormat(lt(r,p)),this.term.eraseLineAfter(),a){let m=Sr(a),h=Math.max(1,e-m);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Hu(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=aw(this.btwOverlayUsage),a=o?` ${o} `:"",c=o?"\u2500\u2500":"",d=s.length+Sr(n)+i.length+Sr(r)+Sr(a)+c.length,l="\u2500".repeat(Math.max(0,e-d)),f=`${e}|${r}|${this.btwOverlayStatus}|${o??""}`;return{left:s,label:n,sidSep:i,sid:r,middle:l,usage:a,right:c,signature:f}}paintBtwHeader(e){switch(this.term.dim(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&this.term.yellow(e.sid),this.term.dim(e.middle),e.usage&&this.term.dim.noFormat(e.usage),this.term.dim(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let u=Math.max(0,r.length-s);this.scrollOffset>u&&(this.scrollOffset=u)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),f=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let u=0;u<s;u++){let p=n+u,m=u-d,h=m>=0?c[m]:void 0,w=this.activeMatchCol(h,l),b=h?this.selectionRangeForChunk(h):null,v=tw("sb",e,h,this.scrollbackHighlight,w,b);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,w,f,b)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let u=new Set;for(let m of c)m.blockKey!==void 0&&u.add(m.blockKey);let p=[];for(let m of this.pendingVisibleKeys)u.has(m)&&p.push(m);for(let m of p)this.pendingVisibleKeys.delete(m),this.onBlockVisible(m)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Lu,this.queuedTexts.length)}chipRows(){return Math.min(Nu,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Bu,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Le-Be-ze,i=this.queuedRows(),o=this.chipRows(),c=r-1-i-o-e+1,d=0;for(let l of this.completions.slice(0,e))l.name.length>d&&(d=l.name.length);for(let l=0;l<e;l++){let f=c+l,u=this.completions[l],p=l===e-1&&this.completions.length>Bu,m=this.completions.length-Bu+1,h=u?p?`comp|${n}|overflow|${m}`:`comp|${n}|${d}|${u.name}|${u.description??""}`:`comp|${n}|empty`;this.paintRow(f,h,()=>{if(!u)return;if(p){this.term.dim(` + ${m} more match(es)`);return}let w=u.name.padEnd(d),b=u.description??"",v=n-w.length-4,S=v>0?lt(b,v):"";this.term(" ").brightCyan(w),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-Le-Be-ze-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Nu,f=this.attachments.length-Nu,u=this.attachments[c],p=u?`${u.name??"image"} \xB7 ${Vt(u.sizeBytes)}`:"",m=l?`chip|${n}|overflow|${f}`:u?`chip|${n}|${a?"i":"t"}|${p}|${u.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,m,()=>{if(l){this.term.dim(` \u{1F4CE} + ${f+1} more attached`);return}u&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(u.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(IR(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-Le-Be-ze,i=this.chipRows(),a=r-1-i-e+1,c=this.dispatcher.state().queueIndex;for(let d=0;d<e;d++){let l=a+d,f=this.queuedTexts[d],u=d===e-1&&this.queuedTexts.length>Lu,p=this.queuedTexts.length-Lu,m=f===void 0?"":u?`+ ${p+1} more queued`:lt(TR(f),n-4),h=!u&&d===c,w=f===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":u?"ovf":"row"}|${m}`;this.paintRow(l,w,()=>{if(f===void 0)return;let b=`\u23F3 ${m}`,v=b+" ".repeat(Math.max(0,n-1-b.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Zn(s.buffer,n),i=Es(r,s,Fu),o=this.term.height-i.rendered-ze-Be-Le+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,f="wrap",u="";d&&(d.bufferIdx===0&&d.startCol===0?f="first":d.startCol===0&&(f="newline"),u=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${f}|${u}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(f==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):f==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(u):this.term.noFormat(u))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Du-ze-Be-Le+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${lt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${lt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-ze-Be-Le+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${lt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,f=` ${d?"\u276F":" "} ${a+1}. ${lt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(f):this.term.dim(f)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-ze-Be-Le+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${lt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,f=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(f),this.term.noFormat(` ${lt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${lt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(mR,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-ze-Be-Le+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${lt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${lt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,u=` ${l?"\u276F":" "} ${c+1}. ${lt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(u):this.term.dim(u)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}drawBanner(){let e=this.term.height-Le-Be,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Mn(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let c=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${c} stalled`):this.term.brightYellow(`${c} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${c} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${c} ${this.banner.status}`):this.term.brightGreen(`${c} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let d=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;if(this.term(" \xB7 ").dim(d),this.term.eraseLineAfter(),r){let l=Sr(r.text),f=Math.max(1,n-l);this.term.moveTo(f,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):r.kind==="compaction"?this.term.brightYellow.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),u=this.term.height-l-ze-Be-Le+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.optionsPrompt){let l=this.optionsRows(),u=this.term.height-l-ze-Be-Le+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.confirmPrompt){let l=this.term.height-Du-ze-Be-Le+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),u=this.term.height-l-ze-Be-Le+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-ze-Be-Le;this.term.moveTo(2,Math.min(u,p));return}if(this.helpPrompt){let l=this.helpRows(),f=this.term.height-l-ze-Be-Le+1;this.term.moveTo(2,f);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Zn(s.buffer,n),i=Es(r,s,Fu),a=this.term.height-i.rendered-ze-Be-Le+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-ze-Be-Le;this.term.moveTo(Math.min(c,this.term.width),Math.min(a,d))}promptRows(){if(this.permissionPrompt)return this.permissionRows();if(this.optionsPrompt)return this.optionsRows();if(this.confirmPrompt)return Du;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=Zn(s.buffer,n);return Math.min(Fu,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(fR,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(pR,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-ze-Be-Le+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${lt(e.title,n-5)}`)});let a=Math.max(...e.options.map(c=>c.label.length),0);for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,u=` ${l?"\u276F":" "} ${c+1}. `,p=d.label.padEnd(a),m=n-u.length-3,h=`${u}${lt(`${p} ${d.value}`,m)}`;o(`opts|o|${n}|${c}|${l?"1":"0"}|${d.value}|${d.label}`,()=>{l?this.term.brightYellow(h):this.term.dim(h)})}o(`opts|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close")})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-ze-Be-Le,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let f=this.wrapBtwTail(n,c);for(let u=0;u<c;u++){let p=d+1+u,m=f.length-c+u,h=m>=0?f[m]:void 0,w=tw(`btw|c${u}`,n,h);this.paintRow(p,w,()=>{h?this.writeFormattedLine(h,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let f of this.lines)s(f)||d.push(f);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let f=this.wrapOne(l,e);if(r.push(f),i+=f.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let f=this.wrapCache.get(s);if(f)return f}let r=e.prefix??"",i=Ts(r),o=Math.max(1,n-i),a=zo(e.bodyStyle),c=e.ansi?vR(e.body,o):xR(e.body,o,{stripMarkup:a}),d=[],l=0;for(let f=0;f<c.length;f++){let u=c[f]??"",p={prefix:f===0?e.prefix:" ".repeat(i),body:u};if(e.prefixStyle!==void 0&&(p.prefixStyle=e.prefixStyle),e.bodyStyle!==void 0&&(p.bodyStyle=e.bodyStyle),e.blockKey!==void 0&&(p.blockKey=e.blockKey),e.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),f===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&u.length>0){let m=e.body.indexOf(u,l),h=m===-1?l:m;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+u.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&Xn(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Ts(e.prefix??"")),a=zo(e.bodyStyle),c=e.ansi?e.body:lt(e.body,o,{stripMarkup:a}),d=(l,f)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let u=s!==null&&s>=f?s-f:null;nw(this.term,l,e.bodyStyle,this.scrollbackHighlight,u,r)}else Xn(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(c.length,i.start)),f=Math.max(l,Math.min(c.length,i.end)),u=zo(e.bodyStyle);if(d(c.slice(0,l),0),f>l){let m=c.slice(l,f);u&&(m=rw(m)),Xn(this.term,m,"selection-highlight")}let p=c.slice(f);if(u&&f>l){let m=kR(c.slice(0,f));m.length>0&&(p=m+p)}d(p,f)}else this.scrollbackHighlight!==null&&!e.ansi?nw(this.term,c,e.bodyStyle,this.scrollbackHighlight,s,r):Xn(this.term,c,e.bodyStyle);if(e.fillRow){let l=e.ansi?Sr(c):Ts(c),f=o-l;if(f>0){let u=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;Xn(this.term," ".repeat(f),u)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};cw=/[^\x20-\x7e]/,Uu=new Intl.Segmenter(void 0,{granularity:"grapheme"}),lw=!1;SR=/[a-zA-Z+\-:_!#/]/;Hu=Ve});function ER(t,e,n=Qd){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function hw(t,e){Vn();let n=Ve(e.sessionId),s=e.importedFromMachine??"another machine",r=Ue(e.cwd),i=Qd.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+Qd.length*2+2,d=Gn(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,f=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],u=0;for(let p of f)t.moveTo(d.contentX,d.contentY+u),t.dim.noFormat(` ${p.label}`),t.noFormat(nt(p.value,l-p.label.length-2)),u++;return u++,gw(t,d,u,{intro:"What do you want to do?",choices:Qd,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Cs({term:t,render:o,onKey:(a,c,d,l)=>{let f=PR(a,d);if(!f)return;let u=ER(i,f);if(u.kind==="cancel"){l("cancel");return}if(u.kind==="back"){l("back");return}if(u.kind==="resolve"){l(u.action);return}u.selected!==i&&(i=u.selected,o())}})}function gw(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(_d(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function PR(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function yw(t,e,n){let s=Ve(e.sessionId),r=e.title??Ue(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let c=Gn(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(nt(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+nt(r,d-2)),l++,l++,gw(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},f=p=>{l(),n.pop(),c(p)},u=(p,m,h)=>{if(p==="CTRL_C"||p==="CTRL_D"){f("cancel");return}if(p==="ESCAPE"){f("back");return}if(p==="ENTER"||p==="KP_ENTER"){f(i===0?"launch":"view");return}if(p==="UP"||p==="SHIFT_TAB"){i>0&&(i--,a());return}if(p==="DOWN"||p==="TAB"){i<o.length-1&&(i++,a());return}if(h?.isCharacter){let w=p.toLowerCase();if(w==="l"){f("launch");return}if(w==="v"){f("view");return}if(w==="n"){i<o.length-1&&(i++,a());return}if(w==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,m,h)=>{d||u(p,m,h)},onResize:()=>{d||a()}})})}var Qd,Wu=K(()=>{"use strict";pe();xn();Oi();Qd=[{key:"fork-local",label:"Fork locally",hotkey:"f",description:"spawn a local fork \u2014 original imported copy stays as-is"},{key:"view",label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}]});function Jo(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function ww(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=Jo(e);return o.length<=r.length?null:o+i}var Xd=K(()=>{"use strict"});import*as bw from"os";async function kr(t,e,n={}){let s=n.defaultCwd??(e?await Ly(e.cwd):void 0)??bw.homedir();Vn();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:Ve(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:Ue(e.cwd)}]:[],a=s,c=null,d=!1,l=null,f=[],u=[],p=()=>{f.push(a),f.length>500&&f.shift(),u=[]},m=()=>{let x=f.pop();x!==void 0&&(u.push(a),a=x)},h=()=>{let x=u.pop();x!==void 0&&(f.push(a),a=x)},w=()=>{let x=o.length+6;l=Gn(t,{contentHeight:x,title:r});let T=l.contentW,F=0;for(let $ of o)t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(` ${$.label}`),t.noFormat(nt($.value,T-$.label.length-2)),F++;F++,t.moveTo(l.contentX,l.contentY+F),t.noFormat(` ${i}`),F+=2,v(F),F+=2,c!==null?(t.moveTo(l.contentX,l.contentY+F),t.red.noFormat(` ${nt(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+F),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=x=>{if(!l)return;let T=x??b();t.moveTo(l.contentX,l.contentY+T).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+T),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+T),t.bold.noFormat(" cwd: ");let F=l.contentW-6-2;t.noFormat(MR(a,F)),d||t.bgWhite(" ")},S=()=>{if(v(),!l)return;let x=b()+2;t.moveTo(l.contentX,l.contentY+x).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+x),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+x),c!==null?t.red.noFormat(` ${nt(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Cs({term:t,render:w,hideCursor:!1,onKey:(x,T,F,$)=>{if(!d){if(x==="ENTER"||x==="KP_ENTER"){let H=a;d=!0,c=null,S(),Uo(H).then(J=>{if(d=!1,J.ok){$({kind:"ok",path:J.path});return}c=J.reason,S()});return}if(x==="ESCAPE"){$({kind:"back"});return}if(x==="CTRL_C"||x==="CTRL_D"){$({kind:"cancel"});return}if(x==="TAB"){d=!0,By(a).then(H=>{if(d=!1,H.matches.length===0)return;let J;if(H.matches.length===1)J=H.prefix+H.matches[0];else{let B=Jo(H.matches);if(B.length<=H.basePrefix.length)return;J=H.prefix+B}J!==a&&(p(),a=J,c=null,S())});return}if(x==="BACKSPACE"){a.length>0&&(p(),a=a.slice(0,-1),c=null,S());return}if(x==="CTRL_U"){a.length>0&&(p(),a="",c=null,S());return}if(x==="CTRL_W"){let H=a.replace(/[/\s]+$/,""),J=Math.max(H.lastIndexOf("/"),H.lastIndexOf(" ")),B=J>=0?H.slice(0,J+1):"";B!==a&&(p(),a=B,c=null,S());return}if(x===""){m(),c=null,S();return}if(x==="\x1B_"||x==="\x1B"){h(),c=null,S();return}if(F?.isCharacter){p(),a+=x,c=null,S();return}}}})}function MR(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var zu=K(()=>{"use strict";pe();xn();vu();Xd();Oi()});function Ku(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function Yu(t,e){let n=()=>{process.stdout.write(hr),process.stdout.write(Yn),process.stdout.write(gr),process.stdout.write(yr),process.stdout.write(Pi),process.stdout.write(Mi),process.stdout.write(_i),process.stdout.write(mr),process.stdout.write("\x1B>")};n();let s=e.prefs??Ku();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(P=>P.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=ec(e.sessions,r),o=R=>{let P=R;return s.filters.cwdOnly&&(P=P.filter(L=>L.cwd===r)),s.filters.includeNonInteractive||(P=P.filter(L=>L.interactive===!0)),P=LR(P,s.filters.hostFilter),P},a=o(i),c={columns:e.config.tui.sessionColumns??Si,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Ii(R,Date.now())),l=xi(d,c),f=1+a.length,u=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(P=>P.sessionId===e.currentSessionId);R>=0&&(u=R+1)}let m=!1,h="",w=120,b=!1,v=0,S="normal",x=null,T=!1,F="input",$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,j=null,X=!1,Y="",be=[],V=[],ge=()=>{be.push(Y),be.length>500&&be.shift(),V=[]},Je=()=>{let R=be.pop();R!==void 0&&(V.push(Y),Y=R)},Ms=()=>{let R=V.pop();R!==void 0&&(be.push(Y),Y=R)},Ct=()=>{be=[],V=[]},de=null,ee=!1,$e=new Qn({history:[]});e.initialPrompt&&$e.setBuffer(e.initialPrompt);let pn=e.config.tui.promptHistoryMaxEntries;ho(_.globalTuiHistoryFile()).then(R=>{let P=R.length>pn?R.slice(R.length-pn):R;$e.setHistory(P)}).catch(()=>{});let Ce=new Ni(t),$n=wr(t),Ke=fn(t),Xe=0,xr="",Gt=0,Qt=[],Ut=1,es=0,ve=0,Cr=0,Ar="",_s=[],mn=1,$s=0,Rr=[],ut=1,ts=0,Pe=0,Xt=0,gt=()=>{$n=wr(t),Ke=fn(t);let R=Math.max(10,Ke-Ju-1);Gt=Math.max(10,Ke-vw);let P=Math.max(10,Ke-8);xr=FR(r,P);let L=$e.state();Qt=Zn(L.buffer,Gt);let Z=Es(Qt,L,Zd);Ut=Z.rendered,es=Z.windowStart,ve=Z.cursorVisualRow,Cr=Z.cursorVisualCol;let re=6+Ut,Ye=Math.max(3,$n-re);Xe=Math.min(a.length,Ye),Ar=ks(ki,l,R,c).padEnd(R),_s=d.map(Se=>ks(Se,l,R,c).padEnd(R))},Ui=()=>{d=a.map(R=>Ii(R,Date.now())),l=xi(d,c),f=1+a.length,gt()},at=()=>{let R=o(i);m&&h.length>0?a=R.filter(P=>NR(P,h)):a=R,Ui(),m?(p=0,u=a.length>0?1:0):u>f-1&&(u=Math.max(0,f-1)),p+Xe>a.length&&(p=Math.max(0,a.length-Xe)),Zt()},ns=R=>{if(R!==void 0){let P=a.findIndex(L=>L.sessionId===R);if(P>=0){u=P+1,Zt();return}}u=a.length>0?1:0,p=0,Zt()},Zt=()=>{if(u===0)return;let R=u-1;R<p?p=R:R>=p+Xe?p=R-Xe+1:p+Xe>a.length&&(p=Math.max(0,a.length-Xe))},hn=()=>Math.max(2,Ke-2),Tr=()=>{let R=hn(),P=`\u2500 ${xr} `,L=Math.max(1,R-P.length),Z="\u2500".repeat(L);u===0?t.brightBlue.noFormat(`\u256D${P}${Z}\u256E`):t.dim.noFormat(`\u256D${P}${Z}\u256E`)},Er=()=>{let R=hn(),P="\u2500".repeat(R);u===0?t.brightBlue.noFormat(`\u2570${P}\u256F`):t.dim.noFormat(`\u2570${P}\u256F`)},ss=R=>{let P=Qt[R];return P?($e.state().buffer[P.bufferIdx]??"").slice(P.startCol,P.endCol):""},Os=R=>{let P=hn(),L=ss(R),Z=Math.max(0,P-1-L.length),re=" ".repeat(Z);u===0?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${L}${re}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${L}${re}`),t.dim.noFormat("\u2502"))},jt=R=>{let P=_s[R]??"",L=a[R],Z=L&&L.priority&&L.priority>0?"* ":" ";u===R+1?t.brightWhite.bgBlue.noFormat(`${Z}${P}`):t.noFormat(`${Z}${P}`)},ji=()=>{let R=p,P=Math.max(0,a.length-p-Xe),L=[];return s.filters.cwdOnly&&L.push("cwd-only"),s.filters.hostFilter!=="__all"&&L.push(s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`),s.filters.includeNonInteractive&&L.push("+non-interactive"),R>0&&L.push(`\u2191 ${R} above`),P>0&&L.push(`\u2193 ${P} below`),L.length===0?"":` ${L.join(" \xB7 ")}`},gn=R=>Ve(R),Ko=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,Y,de??"",m?`1|${h}|${a.length}`:"0",ji()].join("")},ue=()=>{De(()=>{Ce.paintRow(On(),Ko(),()=>{if(S==="confirm-kill"&&x)t.brightYellow.noFormat(` kill ${gn(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)x.status==="live"?t.brightRed.noFormat(` kill + delete ${gn(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${gn(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)t.dim.noFormat(` working on ${gn(x.sessionId)}\u2026`);else if(S==="rename"&&x)t.brightYellow.noFormat(` title: ${Y}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(de!==null)t.dim.noFormat(` ${de}`);else if(m){t.brightYellow.noFormat(` /${h}`),t.bgBrightYellow(" ");let R=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${R} \xB7 ^c clears`)}else t.dim.noFormat(ji())})})},yt=R=>mn+1+R,en=()=>mn+Ut+1,me=()=>mn+Ut+3,Yo=R=>me()+1+(R-p),On=()=>me()+1+Xe,Ge=()=>{let R=ve-es;if(R<0||R>=Ut)return;let P=3+Cr;t.moveTo(P,yt(R))},Fs=()=>`ct|${u===0?"f":"u"}|${hn()}|${xr}`,Ls=()=>`cb|${u===0?"f":"u"}|${hn()}`,k=R=>`cbb|${u===0?"f":"u"}|${hn()}|${ss(R)}`,qi=()=>`h|${Ar}`,Pr=R=>{let P=a[R],L=P&&P.priority&&P.priority>0?"* ":" ",Z=_s[R]??"";return`sr|${u===R+1?"1":"0"}|${L}${Z}`},Qe=()=>{De(()=>{t.hideCursor(),gt(),Zt(),mn=1,Ce.ensureSize(Ke,$n),Ce.paintRow(mn,Fs(),()=>{Tr()});for(let R=0;R<Ut;R++){let P=es+R;Ce.paintRow(yt(R),k(P),()=>{Os(P)})}Ce.paintRow(en(),Ls(),()=>{Er()}),Ce.paintRow(en()+1,"blank",()=>{}),Ce.paintRow(me(),qi(),()=>{t.dim.noFormat(` ${Ar}`)});for(let R=0;R<Xe;R++){let P=p+R,L=me()+1+R;P<a.length?Ce.paintRow(L,Pr(P),()=>{jt(P)}):Ce.paintRow(L,"blank",()=>{})}ue();for(let R=On()+1;R<=$n;R++)Ce.paintRow(R,"blank",()=>{});u===0&&(Ge(),t.hideCursor(!1))})},Bs=()=>{Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Qe()},Fn=()=>{De(()=>{t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
160
+ `);if(s.filter(i=>i.length>0).length>1){this.onKey([{type:"paste",text:n.replace(/\r/g,"")}]);return}for(let i=0;i<s.length;i++)s[i].length>0&&this.handleRawStdin(Buffer.from(s[i],"binary")),i<s.length-1&&this.onKey([{type:"key",name:"ctrl-enter"}]);return}if(n.includes("\x1B[")&&/\x1b\[\d+(?:;\d+)?u/.test(n)){this.handleCsiUStdin(n);return}this.handleRawStdinSegment(n)}}handleCsi27Stdin(e){let n=/\x1b\[27;(\d+);(\d+)~/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=parseInt(r[2],10),a=Rw(o,i);a!==null?this.onKey([{type:"key",name:a}]):(i===1||i===2)&&o>=32&&o<127&&this.handleRawStdinSegment(String.fromCharCode(o)),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleCsiUStdin(e){let n=/\x1b\[(\d+)(?:;(\d+))?u/g,s=0,r;for(;(r=n.exec(e))!==null;){r.index>s&&this.handleRawStdin(Buffer.from(e.slice(s,r.index),"binary"));let i=parseInt(r[1],10),o=r[2]!==void 0?parseInt(r[2],10):1,a=Rw(i,o);a!==null&&this.onKey([{type:"key",name:a}]),s=r.index+r[0].length}s<e.length&&this.handleRawStdin(Buffer.from(e.slice(s),"binary"))}handleRawStdinSegment(e){let n=Hi,s=Wo;for(;e.length>0;){if(this.pasteActive){let i=e.indexOf(s);if(i===-1){this.pasteBuffer+=e;return}this.pasteBuffer+=e.slice(0,i),e=e.slice(i+s.length),this.pasteActive=!1;let o=Buffer.from(this.pasteBuffer,"binary").toString("utf-8").replace(/\r\n?/g,`
161
+ `);this.pasteBuffer="";let a=aw(o);a!==null?this.onKey([{type:"attachment-paths",paths:a}]):this.onKey([{type:"paste",text:o}]);continue}let r=e.indexOf(n);if(r===-1){let i=UR(e);i!==null?this.onKey([{type:"paste",text:i}]):this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e,"binary"));return}r>0&&this.terminalKitStdinHandler&&this.terminalKitStdinHandler(Buffer.from(e.slice(0,r),"binary")),e=e.slice(r+n.length),this.pasteActive=!0}}width(){return this.term.width||0}appendLines(e){e.length!==0&&(this.streamingActive=!1,this.lines.push(...e),this.trackLines(e),this.adjustScrollForRowChange(this.wrappedRowsOfMany(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint())}appendLine(e){this.streamingActive=!1,this.lines.push(e),this.trackLine(e),this.adjustScrollForRowChange(this.wrappedRowsOf(e)),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}adjustScrollForRowChange(e){this.scrollOffset>0&&e!==0&&(this.scrollOffset=Math.max(0,this.scrollOffset+e))}wrappedRowsOf(e){let n=this.term.width;return this.wrapCacheWidth!==n&&(this.wrapCache.clear(),this.wrapCacheWidth=n),this.wrapOne(e,n).length}wrappedRowsOfMany(e){let n=0;for(let s of e)n+=this.wrappedRowsOf(s);return n}trackLine(e){this.lineIds.set(e,this.nextLineId++)}trackLines(e){for(let n of e)this.trackLine(n)}forgetLine(e){let n=this.lineIds.get(e);n!==void 0&&this.wrapCache.delete(n)}trimScrollback(){let e=this.lines.length-this.maxScrollbackLines;if(e<=0)return;let n=this.lines.splice(0,e);for(let s of n)this.forgetLine(s);this.invalidateSelectionIfTouches(n);for(let[s,r]of[...this.keyedBlocks.entries()])r.start-=e,r.start<0&&this.keyedBlocks.delete(s)}upsertLine(e,n){this.upsertLines(e,[n])}upsertLines(e,n){if(n.length===0)return;for(let o of n)o.blockKey=e;let s=this.keyedBlocks.get(e),r=!1,i=0;if(s){let o=s.start+s.count;r=o>=this.lines.length;let a=this.wrappedRowsOfMany(this.lines.slice(s.start,o)),c=n.length-s.count,d=this.lines.splice(s.start,s.count,...n);for(let l of d)this.forgetLine(l);if(this.trackLines(n),this.invalidateSelectionIfTouches(d),s.count=n.length,c!==0)for(let[l,u]of this.keyedBlocks)l!==e&&u.start>s.start&&(u.start+=c);i=this.wrappedRowsOfMany(n)-a}else r=!0,this.keyedBlocks.set(e,{start:this.lines.length,count:n.length}),this.lines.push(...n),this.trackLines(n),i=this.wrappedRowsOfMany(n);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(i),e!==this.stickyBottomKey&&this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}appendStreaming(e,n,s,r){if(e.length===0)return;let i=e.split(`
162
+ `),[o,...a]=i,c=0;if(this.streamingActive&&this.lines.length>0){let l=this.lines[this.lines.length-1];if(l){let u=this.wrappedRowsOf(l);this.forgetLine(l),l.body+=o??"",c+=this.wrappedRowsOf(l)-u}}else{if(this.lines.length>0){let u=this.lines[this.lines.length-1];if(!(u&&u.body===""&&(!u.prefix||u.prefix===""))){let p={body:""};this.lines.push(p),this.trackLine(p),c+=this.wrappedRowsOf(p)}}let l={prefix:n,body:o??"",bodyStyle:s};r!==void 0&&(l.prefixStyle=r),this.lines.push(l),this.trackLine(l),c+=this.wrappedRowsOf(l)}let d=" ".repeat(n.length);for(let l of a){let u={prefix:d,body:l,bodyStyle:s};this.lines.push(u),this.trackLine(u),c+=this.wrappedRowsOf(u)}this.streamingActive=!0,this.adjustScrollForRowChange(c),this.moveStickyToEnd(),this.trimScrollback(),this.scheduleRepaint()}setSessionbar(e){this.sessionbar={...this.sessionbar,...e},this.syncWindowTitle(),this.repaint()}syncWindowTitle(){let e=this.sessionbar.title?.trim(),n=Gu(this.sessionbar.sessionId)||"hydra",s=e&&e.length>0?e:n,i=(this.readonly?`${s} [VIEW ONLY]`:s).replace(/[\x00-\x1f\x7f]/g,"").slice(0,200);i!==this.lastWindowTitle&&(this.lastWindowTitle=i,process.stdout.write(`\x1B]0;${i}\x1B\\`))}clearWindowTitle(){this.lastWindowTitle=null,process.stdout.write("\x1B]0;\x1B\\")}setBanner(e){this.banner={...this.banner,...e},this.writeProgressIndicator(this.banner.status==="busy"?3:0),this.syncedPartialRepaint(()=>this.drawBanner())}syncedPartialRepaint(e){this.started&&Be(()=>{e(),this.placeCursor()})}currentModeId(){return this.banner.currentMode}writeProgressIndicator(e){this.started&&this.progressIndicatorEnabled&&e!==this.lastProgressState&&(this.lastProgressState=e,process.stdout.write(`\x1B]9;4;${e}\x1B\\`))}notify(e,n=4e3){this.bannerNotificationTimer&&clearTimeout(this.bannerNotificationTimer),this.bannerNotification=e,this.bannerNotificationTimer=setTimeout(()=>{this.bannerNotification=null,this.bannerNotificationTimer=null,this.syncedPartialRepaint(()=>this.drawBanner())},n),this.syncedPartialRepaint(()=>this.drawBanner())}setCompactionIndicator(e){this.compactionIndicator!==e&&(this.compactionIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}setMouseEnabled(e){this.mouseEnabled!==e&&(this.mouseEnabled=e,this.started&&(e?(this.term.grabInput({mouse:"drag"}),this.term.on("mouse",this.mouseHandler)):(this.term.off("mouse",this.mouseHandler),this.term.grabInput(!0)),this.reclaimStdinAfterGrabInput()))}reclaimStdinAfterGrabInput(){if(this.terminalKitStdinHandler===null)return;let e=this.term;!e.stdin||typeof e.onStdin!="function"||(this.terminalKitStdinHandler=e.onStdin,e.stdin.removeListener("data",e.onStdin),e.stdin.removeListener("data",this.rawStdinHandler),e.stdin.on("data",this.rawStdinHandler))}isMouseEnabled(){return this.mouseEnabled}setInAppSelectionEnabled(e){this.inAppSelectionEnabled=e}isInAppSelectionEnabled(){return this.inAppSelectionEnabled}setSelection(e,n){let s=this.lineIndexById(e.sourceLineId),r=this.lineIndexById(n.sourceLineId),i=s<r||s===r&&e.offset<=n.offset,o=i?e:n,a=i?n:e;if(o.sourceLineId===a.sourceLineId&&o.offset===a.offset){this.clearSelection();return}let c={startLineId:o.sourceLineId,startOffset:o.offset,endLineId:a.sourceLineId,endOffset:a.offset},d=this.selection;d&&d.startLineId===c.startLineId&&d.startOffset===c.startOffset&&d.endLineId===c.endLineId&&d.endOffset===c.endOffset||(this.selection=c,this.repaint())}clearSelection(){this.selection!==null&&(this.selection=null,this.repaint())}hasSelection(){return this.selection!==null}getSelection(){return this.selection===null?null:{start:{sourceLineId:this.selection.startLineId,offset:this.selection.startOffset},end:{sourceLineId:this.selection.endLineId,offset:this.selection.endOffset}}}getSelectionText(){let e=this.selectionLineBounds();if(e===null)return"";let n=[];for(let s=e.loIdx;s<=e.hiIdx;s++){let r=this.lines[s];if(!r)continue;let i=this.lineIds.get(r),o=i===void 0?void 0:e.byId.get(i);if(!o)continue;let a=r.body??"",c;r.ansi?c=s===e.loIdx||s===e.hiIdx?"":a.replace($R,""):(c=a.slice(o.start,o.end),ta(r.bodyStyle)&&(c=Iw(c))),n.push(c)}return n.join(`
163
+ `)}selectionLineBounds(){let e=this.selection;if(e===null)return null;let n=this.lineIndexById(e.startLineId),s=this.lineIndexById(e.endLineId);if(n===-1||s===-1)return null;let r=n,i=s,o=e.startOffset,a=e.endOffset;n>s&&(r=s,i=n,o=e.endOffset,a=e.startOffset);let c=new Map;for(let d=r;d<=i;d++){let l=this.lines[d];if(!l)continue;let u=this.lineIds.get(l);if(u===void 0)continue;let f=(l.body??"").length,p=d===r?Math.max(0,Math.min(f,o)):0,m=d===i?Math.max(0,Math.min(f,a)):f;c.set(u,{start:p,end:m,toEnd:d<i})}return{loIdx:r,hiIdx:i,byId:c}}selectionRangeForChunk(e){if(this.selection===null||e.ansi)return null;let n=this.selectionRenderBounds??this.selectionLineBounds()?.byId??null;if(n===null)return null;let s=this.wrapOrigin.get(e);if(!s)return null;let r=n.get(s.sourceLineId);if(!r)return null;let i=s.sourceColOffset,o=i+e.body.length,a=Math.max(r.start,i),c=Math.min(r.end,o);return c<=a?null:{start:a-i,end:c-i,toEndOfLine:r.toEnd||r.end>o}}setBannerSearchIndicator(e){this.bannerSearchIndicator!==e&&(this.bannerSearchIndicator=e,this.syncedPartialRepaint(()=>this.drawBanner()))}bannerRightContent(){if(this.scrollbackSearch!==null){let e=this.scrollbackSearch,n=e.matches.length>0?` ${e.matchIndex+1}/${e.matches.length}`:e.term.length===0?"":" 0/0";return{text:`\u{1F50D} ${e.term}${n}`,kind:"search"}}return this.bannerSearchIndicator!==null?{text:`\u{1F50D} ${this.bannerSearchIndicator}`,kind:"search"}:this.bannerNotification!==null?{text:this.bannerNotification,kind:"notify"}:this.compactionIndicator!==null?{text:this.compactionIndicator,kind:"compaction"}:null}clearScrollback(){this.lines=[],this.keyedBlocks.clear(),this.wrapCache.clear(),this.wrapCacheWidth=0,this.streamingActive=!1,this.scrollOffset=0,this.selection!==null&&(this.selection=null),this.repaint()}invalidateSelectionIfTouches(e){if(this.selection!==null)for(let n of e){let s=this.lineIds.get(n);if(s!==void 0&&(s===this.selection.startLineId||s===this.selection.endLineId)){this.selection=null;return}}}setHideThoughts(e){this.hideThoughts!==e&&(this.hideThoughts=e,this.repaint())}clearKey(e){this.keyedBlocks.delete(e)}hasKey(e){return this.keyedBlocks.has(e)}removeKey(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count,r=s>=this.lines.length,i=this.wrappedRowsOfMany(this.lines.slice(n.start,s)),o=this.lines.splice(n.start,n.count);for(let a of o)this.forgetLine(a);this.invalidateSelectionIfTouches(o),this.keyedBlocks.delete(e);for(let[a,c]of this.keyedBlocks)a!==e&&c.start>n.start&&(c.start-=n.count);r&&(this.streamingActive=!1),this.adjustScrollForRowChange(-i),this.moveStickyToEnd(),this.scheduleRepaint()}setStickyBottomKey(e){this.stickyBottomKey=e,this.moveStickyToEnd(),this.scheduleRepaint()}moveStickyToEnd(){if(this.stickyBottomKey===null)return;let e=this.keyedBlocks.get(this.stickyBottomKey);if(!e)return;let n=e.start+e.count;if(n>=this.lines.length)return;let s=this.lines.splice(e.start,e.count);for(let[r,i]of this.keyedBlocks)r!==this.stickyBottomKey&&i.start>=n&&(i.start-=e.count);e.start=this.lines.length,this.lines.push(...s),this.streamingActive=!1}removeBlock(e){let n=this.keyedBlocks.get(e);if(!n)return;let s=n.start+n.count>=this.lines.length,r=this.wrappedRowsOfMany(this.lines.slice(n.start,n.start+n.count)),i=this.lines.splice(n.start,n.count);for(let o of i)this.forgetLine(o);this.invalidateSelectionIfTouches(i),this.keyedBlocks.delete(e);for(let[,o]of this.keyedBlocks)o.start>n.start&&(o.start-=n.count);s&&(this.streamingActive=!1),this.adjustScrollForRowChange(-r),this.scheduleRepaint()}contiguousRun(e,n){if(!this.keyedBlocks.has(e))return[];let s=[...n].map(c=>{let d=this.keyedBlocks.get(c);return d?{key:c,start:d.start,count:d.count}:null}).filter(c=>c!==null).sort((c,d)=>c.start-d.start),r=s.findIndex(c=>c.key===e);if(r<0)return[];let i=(c,d)=>{for(let[l,u]of this.keyedBlocks)if(!n.has(l)&&u.start>=c&&u.start<d)return!0;return!1},o=r;for(;o>0&&!i(s[o-1].start+s[o-1].count,s[o].start);)o--;let a=r;for(;a<s.length-1&&!i(s[a].start+s[a].count,s[a+1].start);)a++;return s.slice(o,a+1).map(c=>c.key)}setRunCollapsed(e,n,s){if(e.length===0)return;let r=e[0];if(!this.keyedBlocks.has(r))return;this.upsertLines(r,s);let i=this.keyedBlocks.get(r),o=i.start+i.count;for(let a of e){let c=this.keyedBlocks.get(a);c&&(o=Math.max(o,c.start+c.count))}for(let a=i.start+i.count;a<o;a++){let c=this.lines[a];c&&(c.collapsed=n)}this.scheduleRepaint()}redraw(){this.repaint()}fullRedraw(){this.painter.clearCache(),this.lastWindowTitle=null,this.wrapCache.clear(),this.wrapCacheWidth=0,process.stdout.write(ku),this.term.clear(),this.repaint()}pauseRepaint(){this.repaintPaused+=1}resumeRepaint(){this.repaintPaused!==0&&(this.repaintPaused-=1,this.repaintPaused===0&&this.repaintPending&&(this.repaintPending=!1,this.repaint()))}setQueuedPrompts(e){this.queuedTexts=[...e],this.lastQueueEditingIndex=this.dispatcher.state().queueIndex,this.repaint()}repaintNow(){this.repaint()}setPermissionPrompt(e){e!==null&&this.permissionPrompt===null&&this.clearSelection(),this.permissionPrompt=e?{...e}:null,this.repaint()}setOptionsPrompt(e){e!==null&&this.optionsPrompt===null&&this.clearSelection(),this.optionsPrompt=e?{...e,options:e.options.map(n=>({...n}))}:null,this.repaint()}isOptionsPromptActive(){return this.optionsPrompt!==null}setConfirmPrompt(e){e!==null&&this.confirmPrompt===null&&this.clearSelection(),this.confirmPrompt=e?{...e}:null,this.repaint()}isCompactionPromptActive(){return this.compactionPrompt!==null}compactionPromptSpec(){return this.compactionPrompt?{...this.compactionPrompt}:null}setCompactionPrompt(e){e!==null&&this.compactionPrompt===null&&this.clearSelection(),this.compactionPrompt=e?{...e}:null,this.repaint()}setHelpPrompt(e){e!==null&&this.helpPrompt===null&&this.clearSelection(),this.helpPrompt=e?{...e,entries:[...e.entries]}:null,this.repaint()}isHelpPromptActive(){return this.helpPrompt!==null}openBtwOverlay(e){let n=e?.height??12;this.btwOverlayOpen=!0,this.btwOverlayMaxHeight=n,this.focusedPane="btw",this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.scheduleRepaint()}setBtwOverlayMeta(e){let n=!1;if(e.sessionId!==void 0&&this.btwOverlaySessionId!==e.sessionId&&(this.btwOverlaySessionId=e.sessionId,n=!0),e.usage!==void 0){let s=this.btwOverlayUsage,r=e.usage;(!s||s.used!==r.used||s.size!==r.size||s.costAmount!==r.costAmount||s.costCurrency!==r.costCurrency)&&(this.btwOverlayUsage={...r},n=!0)}n&&this.scheduleRepaint()}setBtwOverlayContent(e){if(this.btwOverlayLines.length===e.length){let n=!0;for(let s=0;s<e.length;s++)if(this.btwOverlayLines[s]!==e[s]){n=!1;break}if(n)return}this.btwOverlayLines=[...e],this.scheduleRepaint()}setBtwOverlayStatus(e){let n=this.btwOverlayLabel===e.label,s=this.btwOverlayStatus===e.style;n&&s||(this.btwOverlayLabel=e.label,this.btwOverlayStatus=e.style,this.scheduleRepaint())}closeBtwOverlay(){this.btwOverlayOpen&&(this.btwOverlayOpen=!1,this.btwOverlayLines=[],this.btwOverlaySessionId=null,this.btwOverlayUsage=void 0,this.focusedPane="main",this.scheduleRepaint())}toggleFocusedPane(){this.focusedPane=this.focusedPane==="main"?"btw":"main",this.scheduleRepaint()}getFocusedPane(){return this.focusedPane}isOverlayOpen(){return this.btwOverlayOpen}setCompletions(e){e.length===this.completions.length&&e.every((s,r)=>{let i=this.completions[r];return i!==void 0&&i.name===s.name&&i.description===s.description})||(this.completions=[...e],this.repaint())}ensureSeparator(e){if(this.lines.length===0)return;let n=this.stickyBottomKey!==null?this.keyedBlocks.get(this.stickyBottomKey):void 0,s=n!==void 0&&n.start+n.count===this.lines.length,r=s?n.start-1:this.lines.length-1;if(r<0)return;let i=this.lines[r];if(i&&i.body===""&&(i.prefix===void 0||i.prefix===""))return;let o={body:""};e!==void 0&&(o.bodyStyle=e),s?(this.lines.splice(n.start,0,o),n.start+=1):this.lines.push(o),this.trackLine(o),this.streamingActive=!1,this.adjustScrollForRowChange(this.wrappedRowsOf(o)),this.trimScrollback(),this.scheduleRepaint()}refreshPrompt(){if(this.promptRows()!==this.lastPromptRows){this.repaint();return}this.syncedPartialRepaint(()=>{let e=this.dispatcher.state().queueIndex;e!==this.lastQueueEditingIndex&&(this.lastQueueEditingIndex=e,this.drawQueuedZone()),this.drawPrompt()})}handleKey(e,n){if(n.isCharacter){this.onKey([{type:"char",ch:e}]);return}if(e==="PAGE_UP"){this.scrollBy(this.scrollPageSize());return}if(e==="PAGE_DOWN"){this.scrollBy(-this.scrollPageSize());return}let s=cc(e);s&&this.onKey([{type:"key",name:s}])}handleMouse(e,n){if(e==="MOUSE_WHEEL_UP"){this.scrollBy(3);return}if(e==="MOUSE_WHEEL_DOWN"){this.scrollBy(-3);return}let s=this.mouseCell(n),r=jR(e),i=null;if(e==="MOUSE_DRAG"||e==="MOUSE_MOTION"?i="move":e.endsWith("_PRESSED")?i="press":e.endsWith("_RELEASED")&&(i="release"),i!==null&&s!==null&&this.onMouse&&this.onMouse({kind:i,button:r,x:s.x,y:s.y,name:e}),s!==null&&i!=="release"){let o=this.keyAtRow(s.y)!==null;this.setPointerShape(o?"pointer":"default")}if(e==="MOUSE_LEFT_BUTTON_PRESSED"){let o=this.lastLeftClick;o!==null&&s!==null&&Math.abs(s.x-o.x)<=ic&&Math.abs(s.y-o.y)<=ic&&Date.now()-o.t<=qu||this.flushPendingBlockClick(),this.pressCell=s,this.handleSelectionPress(s);return}if(e.endsWith("_PRESSED")&&e!=="MOUSE_LEFT_BUTTON_PRESSED"&&this.flushPendingBlockClick(),e==="MOUSE_DRAG"&&s!==null){this.handleSelectionDrag(s);return}if(e==="MOUSE_LEFT_BUTTON_RELEASED"||e==="MOUSE_BUTTON_RELEASED"){let o=this.pressCell;this.pressCell=null;let a=this.inAppSelectionEnabled&&(this.selectionDragStarted||this.doubleClickPending);if(this.onBlockClick&&o!==null&&s!==null&&s.x===o.x&&s.y===o.y&&!a){let c=this.keyAtRow(s.y);if(c!==null){let d=s.y;for(;d>1&&this.keyAtRow(d-1)===c;)d-=1;this.schedulePendingBlockClick(c,s.y-d)}}this.handleSelectionRelease(s)}}handleSelectionPress(e){if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,!this.inAppSelectionEnabled||e===null)return;let n=this.resolveCellToSource(e.x,e.y);if(n===null){this.lastLeftClick=null;return}this.selectionAnchor=n;let s=Date.now(),r=this.lastLeftClick;if(r!==null&&s-r.t<=qu&&Math.abs(e.x-r.x)<=ic&&Math.abs(e.y-r.y)<=ic){if(this.cancelPendingBlockClick(),this.onBlockDoubleClick&&e!==null){let a=this.keyAtRow(e.y);if(a!==null){let c=e.y;for(;c>1&&this.keyAtRow(c-1)===a;)c-=1;let d=e.y-c;if(this.onBlockDoubleClick(a,d)){this.doubleClickPending=!0,this.lastLeftClick=null;return}}}if(this.tryOpenFileAt(n)){this.doubleClickPending=!0,this.lastLeftClick=null;return}let o=this.wordBoundsAt(n);o!==null&&(this.setSelection({sourceLineId:n.sourceLineId,offset:o.start},{sourceLineId:n.sourceLineId,offset:o.end}),this.doubleClickPending=!0),this.lastLeftClick=null}}handleSelectionDrag(e){if(!this.inAppSelectionEnabled||this.selectionAnchor===null||this.doubleClickPending)return;let n=this.resolveCellToSource(e.x,e.y);n!==null&&(this.selectionDragStarted=!0,this.setSelection(this.selectionAnchor,n))}handleSelectionRelease(e){let n=this.selectionDragStarted,s=this.doubleClickPending;if(this.selectionAnchor=null,this.selectionDragStarted=!1,this.doubleClickPending=!1,e!==null&&(this.lastLeftClick={x:e.x,y:e.y,t:Date.now()}),!!this.inAppSelectionEnabled){if(n||s){this.finalizeSelection();return}this.selection!==null&&this.clearSelection()}}wordBoundsAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=kw(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),!Wu.test(r[a]))return null;let c=a;for(;c>0&&Wu.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&Wu.test(r[d]);)d++;let l=s.length,u=s.length;for(let f=0;f<i.length;f++)if(i[f]===c&&l===s.length&&(l=f),i[f]===d&&u===s.length){u=f;break}return{start:l,end:u}}pathTokenAt(e){let n=this.lineById(e.sourceLineId);if(n===null||n.ansi)return null;let s=n.body??"";if(s.length===0)return null;let{clean:r,rawToClean:i}=kw(s);if(r.length===0)return null;let o=i[Math.min(e.offset,i.length-1)]??r.length;if(n.links){for(let p of n.links)if(o>=p.start&&o<p.end){let m=p.url;return{raw:m.startsWith("file://")?m.slice(7):m,line:null}}}let a=Math.max(0,Math.min(r.length-1,o));if(o>=r.length&&(a=r.length-1),!zu.test(r[a]))return null;let c=a;for(;c>0&&zu.test(r[c-1]);)c--;let d=a+1;for(;d<r.length&&zu.test(r[d]);)d++;let l=r.slice(c,d);if(l=l.replace(/[.]+$/,""),l.length===0)return null;let u=null,f=r.slice(d).match(/^:(\d+)(?::\d+)?/);return f&&(u=Number.parseInt(f[1],10)),{raw:l,line:u}}resolvePathToken(e){let n=e;(n==="~"||n.startsWith("~/"))&&(n=n==="~"?ww():`${ww()}/${n.slice(2)}`);let s=bw(n)||e.startsWith("~"),r=n.includes("/");if(!s&&!r)return null;let i=bw(n)?n:MR(this.sessionbar.cwd,n);if(s)return i;try{if(PR(i).isFile())return i}catch{return null}return null}tryOpenFileAt(e){if(this.openFileCommand===null)return!1;let n=this.pathTokenAt(e);if(n===null)return!1;let s=n.line===null?"":`:${n.line}`;return this.tryOpenPathString(n.raw+s)}tryOpenPathString(e){if(this.openFileCommand===null)return!1;let n=e,s=null,r=e.match(/^(.*?):(\d+)(?::\d+)?$/);r&&(n=r[1],s=Number.parseInt(r[2],10));let i=this.resolvePathToken(n);if(i===null)return!1;let o=s===null?"":String(s),[a,...c]=this.openFileCommand;if(!a)return!1;let d=!1,l=[];for(let u of c)u.includes("%f")&&(d=!0),!(o===""&&u.includes("%n"))&&l.push(u.replaceAll("%f",i).replaceAll("%n",o));d||l.push(i);try{let u=ER(a,l,{detached:!0,stdio:"ignore",cwd:this.sessionbar.cwd});u.on("error",p=>{this.notify(`open file failed: ${p.message}`)}),u.unref();let f=s===null?i:`${i}:${s}`;this.notify(`opening ${f}`)}catch(u){this.notify(`open file failed: ${u.message}`)}return!0}schedulePendingBlockClick(e,n){if(!this.onBlockClick)return;if(this.openFileCommand===null){this.onBlockClick(e,n);return}this.cancelPendingBlockClick();let s=this.onBlockClick,r=setTimeout(()=>{this.pendingBlockClick=null,s(e,n)},qu);typeof r.unref=="function"&&r.unref(),this.pendingBlockClick={timer:r,key:e,rowOffset:n}}cancelPendingBlockClick(){this.pendingBlockClick!==null&&(clearTimeout(this.pendingBlockClick.timer),this.pendingBlockClick=null)}flushPendingBlockClick(){let e=this.pendingBlockClick;e!==null&&(clearTimeout(e.timer),this.pendingBlockClick=null,this.onBlockClick&&this.onBlockClick(e.key,e.rowOffset))}lineById(e){for(let n of this.lines)if(this.lineIds.get(n)===e)return n;return null}lineIndexById(e){for(let n=0;n<this.lines.length;n++){let s=this.lines[n];if(s&&this.lineIds.get(s)===e)return n}return-1}finalizeSelection(){let e=this.getSelectionText();e.length!==0&&hw(e,{target:this.selectionClipboard}).then(n=>{if(n.ok){let s=e.length;this.notify(`copied ${s} char${s===1?"":"s"} to clipboard`)}else this.notify(`clipboard copy failed: ${n.reason}`)},n=>{this.notify(`clipboard copy failed: ${n.message}`)})}mouseCell(e){if(!e||typeof e!="object")return null;let n=e,s=Number(n.x),r=Number(n.y);return!Number.isFinite(s)||!Number.isFinite(r)?null:{x:s,y:r}}setPointerShape(e){e!==this.currentPointerShape&&(this.currentPointerShape=e,process.stdout.write(e==="pointer"?py:Wd))}keyAtRow(e){let n=this.term.width,s=1,r=this.scrollbackVisibleRows();if(r<=0)return null;let i=e-s;if(i<0||i>=r)return null;let{rows:o}=this.wrapTail(n,r+this.scrollOffset),a=o.length-this.scrollOffset,c=Math.max(0,a-r),d=o.slice(c,a),l=Math.max(0,r-d.length),u=i-l;return u<0||u>=d.length?null:d[u]?.blockKey??null}resolveCellToSource(e,n){if(!Number.isFinite(e)||!Number.isFinite(n))return null;let s=this.term.width,r=1,i=this.scrollbackVisibleRows();if(i<=0)return null;let o=n-r;if(o<0||o>=i||e<1||e>s)return null;let{rows:a}=this.wrapTail(s,i+this.scrollOffset),c=a.length-this.scrollOffset,d=Math.max(0,c-i),l=a.slice(d,c),u=Math.max(0,i-l.length),f=o-u;if(f<0||f>=l.length)return null;let p=l[f];if(!p)return null;let m=this.wrapOrigin.get(p);if(!m)return null;let h=Hs(p.prefix??""),y=e-1-h;if(y<0)return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset};let b=ta(p.bodyStyle)?cw(Zu(p.body),y):dw(p.body,y);return{sourceLineId:m.sourceLineId,offset:m.sourceColOffset+b}}scrollBy(e){if(e===0)return;this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let n=this.maxScrollOffset(),s=Math.min(n,Math.max(0,this.scrollOffset+e));s!==this.scrollOffset&&(this.scrollOffset=s,this.repaint())}scrollToBottom(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch(),this.scrollOffset!==0&&(this.scrollOffset=0,this.repaint())}scrollToTop(){this.scrollbackSearch!==null&&this.acceptScrollbackSearch();let e=this.maxScrollOffset();this.scrollOffset!==e&&(this.scrollOffset=e,this.repaint())}isScrolledBack(){return this.scrollOffset>0}isScrollbackSearchActive(){return this.scrollbackSearch!==null}enterScrollbackSearch(){this.scrollbackSearch===null&&(this.scrollbackSearch={term:"",matchIndex:0,matches:[],baselineScroll:this.scrollOffset},this.scrollbackHighlight=null,this.repaint())}updateScrollbackSearchTerm(e){if(this.scrollbackSearch===null)return;let n=e.toLowerCase(),s=[];if(n.length>0)for(let r=this.lines.length-1;r>=0;r--){let i=this.lines[r];if(!i||i.body.length===0||i.ansi)continue;let o=i.body.toLowerCase(),a=[],c=0;for(;c<o.length;){let d=o.indexOf(n,c);if(d===-1)break;a.push(d),c=d+n.length}for(let d=a.length-1;d>=0;d--)s.push({lineIdx:r,col:a[d]})}this.scrollbackSearch.term=e,this.scrollbackSearch.matches=s,this.scrollbackSearch.matchIndex=0,this.scrollbackHighlight=n.length>0?n:null,s.length>0&&this.scrollToMatch(s[0]),this.repaint()}advanceScrollbackSearch(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return;let e=Math.min(this.scrollbackSearch.matches.length-1,this.scrollbackSearch.matchIndex+1);e!==this.scrollbackSearch.matchIndex&&(this.scrollbackSearch.matchIndex=e,this.scrollToMatch(this.scrollbackSearch.matches[e]),this.repaint())}retreatScrollbackSearch(){this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0||this.scrollbackSearch.matchIndex!==0&&(this.scrollbackSearch.matchIndex-=1,this.scrollToMatch(this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex]),this.repaint())}acceptScrollbackSearch(){this.scrollbackSearch!==null&&(this.scrollbackSearch=null,this.scrollbackHighlight=null,this.repaint())}cancelScrollbackSearch(){if(this.scrollbackSearch===null)return;let e=this.scrollbackSearch.baselineScroll;this.scrollbackSearch=null,this.scrollbackHighlight=null,this.scrollOffset=e,this.repaint()}scrollbackSearchTerm(){return this.scrollbackSearch?.term??""}currentMatchInfo(){if(this.scrollbackSearch===null||this.scrollbackSearch.matches.length===0)return null;let e=this.scrollbackSearch.matches[this.scrollbackSearch.matchIndex];if(!e)return null;let n=this.lines[e.lineIdx];if(!n)return null;let s=this.lineIds.get(n);return s===void 0?null:{lineId:s,col:e.col,length:this.scrollbackSearch.term.length}}activeMatchCol(e,n){if(!e||n===null)return null;let s=this.wrapOrigin.get(e);if(!s||s.sourceLineId!==n.lineId)return null;let r=n.col-s.sourceColOffset;return r<0||r>=e.body.length?null:r}scrollToMatch(e){let n=this.term.width,s=this.scrollbackVisibleRows();if(s<=0)return;let r=0;for(let l=this.lines.length-1;l>e.lineIdx;l--){let u=this.lines[l];u&&(r+=this.wrapOne(u,n).length)}let i=this.lines[e.lineIdx],o=0;if(i){let l=this.wrapOne(i,n),u=0;for(let f=0;f<l.length;f++){let p=l[f];if(!p)continue;let m=p.body.length;if(e.col<u+m){o=l.length-1-f;break}u+=m}}let a=r+o,c=Math.max(0,a-Math.floor(s/2)),d=this.maxScrollOffset();this.scrollOffset=Math.min(d,c)}scrollPageSize(){return Math.max(1,this.scrollbackVisibleRows()-2)}scrollbackVisibleRows(){let n=this.term.height-this.promptRows()-qe-We-Ye-FR-this.chipRows()-this.queuedRows()-this.completionRows()-this.btwOverlayRows();return Math.max(0,n-1+1)}maxScrollOffset(){let{rows:e}=this.wrapTail(this.term.width,Number.POSITIVE_INFINITY);return Math.max(0,e.length-this.scrollbackVisibleRows())}scheduleRepaint(){this.scheduler.schedule()}paintRow(e,n,s){this.started&&this.painter.paintRow(e,n,s)}repaint(){if(!this.started)return;if(this.repaintPaused>0){this.repaintPending=!0;return}this.scheduler.noteRepaintStart();let e=this.term.width,n=this.term.height;e<20||n<8||(this.painter.ensureSize(e,n),Be(()=>{this.term.hideCursor(),this.drawScrollback(),this.drawBtwOverlay(),this.drawCompletionZone(),this.drawQueuedZone(),this.drawAttachmentChipZone();let s=this.promptRows(),r=n-s-Ye-We-qe;this.drawSeparator(r),this.drawPrompt(),this.drawBanner(),this.drawSessionbar(),this.placeCursor(),(this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.compactionPrompt||this.helpPrompt)&&this.term.hideCursor(!1),this.lastPromptRows=s}))}drawSessionbar(){let e=this.term.width,n=this.term.height,s=Gu(this.sessionbar.sessionId),r=this.sessionbar.title?.trim(),i=rg(this.sessionbar.agent,this.sessionbar.model),o=ze(this.sessionbar.cwd),a=Aw(this.sessionbar.usage),c=`sbar|${e}|${s}|${i}|${o}|${r??""}|${a??""}`;this.paintRow(n,c,()=>{let d=a?a.length+3:0,l=s.length+3+i.length+3+(r?3:0)+d,u=Math.max(8,e-l),f,p;if(r){let m=Math.min(r.length,8);f=Math.min(o.length,Math.max(8,u-m)),p=Math.max(0,u-f)}else p=0,f=u;if(this.term.yellow(s)(" \xB7 ").cyan.noFormat(i)(" \xB7 ").dim.noFormat(dt(o,f)),r&&this.term(" \xB7 ").bold.noFormat(dt(r,p)),this.term.eraseLineAfter(),a){let m=Nn(a),h=Math.max(1,e-m);this.term.moveTo(h,n).eraseLineAfter(),this.term.dim.noFormat(a)}})}drawSeparator(e){let n=this.term.width;this.paintRow(e,`sep|${n}`,()=>{this.term.dim("\u2500".repeat(n))})}buildBtwHeaderSegments(){let e=this.term.width,n="By the way",s="\u2500\u2500 ",r=this.btwOverlaySessionId?Gu(this.btwOverlaySessionId):"",i=r?" \xB7 ":" ",o=Aw(this.btwOverlayUsage),a=o?` ${o} `:"",c=o?"\u2500\u2500":"",d=s.length+Nn(n)+i.length+Nn(r)+Nn(a)+c.length,l="\u2500".repeat(Math.max(0,e-d)),u=`${e}|${r}|${this.btwOverlayStatus}|${o??""}`;return{left:s,label:n,sidSep:i,sid:r,middle:l,usage:a,right:c,signature:u}}paintBtwHeader(e){switch(this.term.dim(e.left),this.btwOverlayStatus){case"busy":this.term.brightYellow(e.label);break;case"done":this.term(e.label);break;case"cancelled":case"errored":this.term.brightRed(e.label);break;default:this.term(e.label)}this.term.dim(e.sidSep),e.sid&&this.term.yellow(e.sid),this.term.dim(e.middle),e.usage&&this.term.dim.noFormat(e.usage),this.term.dim(e.right)}drawScrollback(){let e=this.term.width,n=1,s=this.scrollbackVisibleRows();if(s<=0)return;let{rows:r,exhausted:i}=this.wrapTail(e,s+this.scrollOffset);if(i){let f=Math.max(0,r.length-s);this.scrollOffset>f&&(this.scrollOffset=f)}let o=r.length-this.scrollOffset,a=Math.max(0,o-s),c=r.slice(a,o),d=Math.max(0,s-c.length),l=this.currentMatchInfo(),u=l?.length??0;this.selectionRenderBounds=this.selectionLineBounds()?.byId??null;for(let f=0;f<s;f++){let p=n+f,m=f-d,h=m>=0?c[m]:void 0,y=this.activeMatchCol(h,l),b=h?this.selectionRangeForChunk(h):null,v=vw("sb",e,h,this.scrollbackHighlight,y,b);this.paintRow(p,v,()=>{h&&this.writeFormattedLine(h,e,y,u,b)})}if(this.onBlockVisible&&this.pendingVisibleKeys.size>0){let f=new Set;for(let m of c)m.blockKey!==void 0&&f.add(m.blockKey);let p=[];for(let m of this.pendingVisibleKeys)f.has(m)&&p.push(m);for(let m of p)this.pendingVisibleKeys.delete(m),this.onBlockVisible(m)}}notifyWhenVisible(e){this.onBlockVisible&&(this.pendingVisibleKeys.add(e),this.scheduleRepaint())}queuedRows(){return Math.min(Ku,this.queuedTexts.length)}chipRows(){return Math.min(Yu,this.attachments.length)}setAttachments(e){this.attachments.length===e.length&&this.attachments.every((n,s)=>n===e[s])||(this.attachments=[...e],this.repaint())}completionRows(){return this.permissionPrompt||this.optionsPrompt||this.confirmPrompt||this.helpPrompt?0:Math.min(Vu,this.completions.length)}drawCompletionZone(){let e=this.completionRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-qe-We-Ye,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>Vu,m=this.completions.length-Vu+1,h=f?p?`comp|${n}|overflow|${m}`:`comp|${n}|${d}|${f.name}|${f.description??""}`:`comp|${n}|empty`;this.paintRow(u,h,()=>{if(!f)return;if(p){this.term.dim(` + ${m} more match(es)`);return}let y=f.name.padEnd(d),b=f.description??"",v=n-y.length-4,S=v>0?dt(b,v):"";this.term(" ").brightCyan(y),S.length>0&&this.term(" ").dim(S)})}}drawAttachmentChipZone(){let e=this.chipRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),o=this.term.height-s-qe-We-Ye-1-e+1,a=this.isIterm2();for(let c=0;c<e;c++){let d=o+c,l=c===e-1&&this.attachments.length>Yu,u=this.attachments.length-Yu,f=this.attachments[c],p=f?`${f.name??"image"} \xB7 ${nn(f.sizeBytes)}`:"",m=l?`chip|${n}|overflow|${u}`:f?`chip|${n}|${a?"i":"t"}|${p}|${f.sizeBytes}`:`chip|${n}|empty`;this.paintRow(d,m,()=>{if(l){this.term.dim(` \u{1F4CE} + ${u+1} more attached`);return}f&&(this.term(" ").yellow(`\u{1F4CE} ${p}`),a&&(this.term(" "),this.writeIterm2Image(f.data,1)))})}}isIterm2(){let e=process.env;return e.LC_TERMINAL==="iTerm2"||e.TERM_PROGRAM==="iTerm.app"}writeIterm2Image(e,n){process.stdout.write(JR(e,n,!!process.env.TMUX))}drawQueuedZone(){let e=this.queuedRows();if(e===0)return;let n=this.term.width,s=this.promptRows(),r=this.term.height-s-qe-We-Ye,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>Ku,p=this.queuedTexts.length-Ku,m=u===void 0?"":f?`+ ${p+1} more queued`:dt(GR(u),n-4),h=!f&&d===c,y=u===void 0?`queued|${n}|empty`:`queued|${n}|${h?"edit":f?"ovf":"row"}|${m}`;this.paintRow(l,y,()=>{if(u===void 0)return;let b=`\u23F3 ${m}`,v=b+" ".repeat(Math.max(0,n-1-b.length));h?this.term.bgBlue.brightYellow("\u25B8"):this.term.bgBlue(" "),this.term.bgBlue.brightWhite.noFormat(v)})}}drawPrompt(){if(this.permissionPrompt){this.drawPermissionPrompt();return}if(this.optionsPrompt){this.drawOptionsPrompt();return}if(this.confirmPrompt){this.drawConfirmPrompt();return}if(this.compactionPrompt){this.drawCompactionPrompt();return}if(this.helpPrompt){this.drawHelpPrompt();return}if(this.readonly)return;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=as(s.buffer,n),i=Us(r,s,Ju),o=this.term.height-i.rendered-Ye-We-qe+1,a=!1;for(let c=0;c<i.rendered;c++){let d=r[i.windowStart+c],l=o+c,u="wrap",f="";d&&(d.bufferIdx===0&&d.startCol===0?u="first":d.startCol===0&&(u="newline"),f=(s.buffer[d.bufferIdx]??"").slice(d.startCol,d.endCol));let p=d?`prompt|${this.term.width}|${u}|${f}`:`prompt|${this.term.width}|empty`;this.paintRow(l,p,()=>{d&&(u==="first"?a?this.term.dim("> "):this.term.brightWhite("> "):u==="newline"?this.term.dim("\xB7 "):this.term(" "),a?this.term.dim(f):this.term.noFormat(f))})}}drawConfirmPrompt(){let e=this.confirmPrompt;if(!e)return;let n=this.term.width,s=this.term.height-Qu-Ye-We-qe+1;this.paintRow(s,`confirm|q|${n}|${e.question}`,()=>{this.term.brightYellow(` ? ${dt(e.question,n-4)}`)}),this.paintRow(s+1,`confirm|h|${n}|${e.hint}`,()=>{this.term.dim(` ${dt(e.hint,n-2)}`)})}drawCompactionPrompt(){let e=this.compactionPrompt;if(!e)return;let n=this.term.width,s=this.compactionRows(),r=this.term.height-s-Ye-We-qe+1,i=r,o=(a,c)=>{i>=r+s||(this.paintRow(i,a,c),i+=1)};o(`cpct|msg|${n}|${e.message}`,()=>{this.term.brightYellow(` ${dt(e.message,n-2)}`)}),o(`cpct|q|${n}`,()=>{this.term(" Compact now to reduce future per-turn token cost?")});for(let a=0;a<e.options.length&&!(i>=r+s-1);a++){let c=e.options[a];if(!c)continue;let d=a===e.selectedIndex,u=` ${d?"\u276F":" "} ${a+1}. ${dt(c.label,n-8)}`;o(`cpct|o|${n}|${a}|${d?"1":"0"}|${c.label}`,()=>{d?this.term.brightYellow(u):this.term.dim(u)})}o(`cpct|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 y/n quick-pick")})}compactionRows(){return this.compactionPrompt?3+this.compactionPrompt.options.length:0}drawHelpPrompt(){let e=this.helpPrompt;if(!e)return;let n=this.term.width,s=this.helpRows(),r=this.term.height-s-Ye-We-qe+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`help|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2753 ${dt(e.title,n-5)}`)});let a=Math.min(24,Math.max(...e.entries.map(c=>c===null?0:c[0].length),4));for(let c of e.entries){if(i>=r+s-1)break;if(c===null){o(`help|sep|${n}|${i}`,()=>{});continue}let[d,l]=c,u=d.padEnd(a);o(`help|e|${n}|${d}|${l}`,()=>{this.term(" "),this.term.brightCyan.noFormat(u),this.term.noFormat(` ${dt(l,n-2-a-1)}`)})}o(`help|hint|${n}|${e.hint}`,()=>{this.term.dim(` ${dt(e.hint,n-2)}`)})}helpRows(){return this.helpPrompt?Math.min(BR,2+this.helpPrompt.entries.length):0}drawPermissionPrompt(){let e=this.permissionPrompt;if(!e)return;let n=this.term.width,s=this.permissionRows(),r=this.term.height-s-Ye-We-qe+1,i=r,o=(c,d)=>{i>=r+s||(this.paintRow(i,c,d),i+=1)};o(`perm|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u{1F512} ${dt(e.title,n-5)}`)});let a=e.detail&&e.detail.length>0?e.detail:"This action requires approval";o(`perm|sub|${n}|${a}`,()=>{this.term.dim(` ${dt(a,n-2)}`)}),o(`perm|q|${n}`,()=>{this.term(" Do you want to proceed?")});for(let c=0;c<e.options.length&&!(i>=r+s-1);c++){let d=e.options[c];if(!d)continue;let l=c===e.selectedIndex,f=` ${l?"\u276F":" "} ${c+1}. ${dt(d.label,n-8)}`;o(`perm|o|${n}|${c}|${l?"1":"0"}|${d.label}`,()=>{l?this.term.brightYellow(f):this.term.dim(f)})}o(`perm|hint|${n}`,()=>{this.term.dim(" \u2191/\u2193 choose \xB7 Enter submit \xB7 Esc cancel \xB7 1\u20139 quick-pick")})}computeBannerPrefixText(e){let n=this.banner.status==="busy"?"\u25CF":"\u25CB",s="";if(this.banner.status==="busy"){let r=this.banner.stalled===!0;s+=`${n} ${r?"stalled":this.banner.status}`,e&&(s+=` ${e}`)}else s+=`${n} ${this.banner.status}`;return this.banner.queued>0&&(s+=` \xB7 ${this.banner.queued} queued`),this.scrollOffset>0&&(s+=` \xB7 \u2191 ${this.scrollOffset}`),s+=" \xB7 ",s}bannerHitAt(e,n){let s=this.bannerHits;if(!s||n!==s.row)return null;let r=i=>i!==null&&e>=i[0]&&e<=i[1];return r(s.mode)?"mode":r(s.pick)?"pick":r(s.guide)?"guide":r(s.detach)?"detach":null}drawBanner(){let e=this.term.height-qe-We,n=this.term.width,s=this.banner.status==="busy"&&this.banner.elapsedMs!==void 0&&this.banner.elapsedMs>=1e3?Ln(this.banner.elapsedMs):"",r=this.bannerRightContent(),i=r?`${r.kind}|${r.text}`:"",o=this.banner.status==="busy"&&this.banner.stalled===!0,a=`bnr|${n}|${this.banner.status}|${s}|${o?"1":"0"}|${this.banner.queued}|${this.scrollOffset}|${this.banner.currentMode??""}|${this.banner.hint}|`+i;this.paintRow(e,a,()=>{let c=this.banner.status==="busy"?"\u25CF":"\u25CB";this.banner.status==="busy"?(o?this.term.brightRed(`${c} stalled`):this.term.brightYellow(`${c} ${this.banner.status}`),s&&this.term(" ").dim(s)):this.banner.status==="disconnected"?this.term.brightRed(`${c} ${this.banner.status}`):this.banner.status==="cold"?this.term.brightMagenta(`${c} ${this.banner.status}`):this.term.brightGreen(`${c} ${this.banner.status}`),this.banner.queued>0&&this.term(" \xB7 ").brightYellow(`${this.banner.queued} queued`),this.scrollOffset>0&&this.term(" \xB7 ").brightCyan(`\u2191 ${this.scrollOffset}`);let d=this.banner.currentMode?this.banner.hint.replace("\u21E7\u21E5 mode",`\u21E7\u21E5 mode: ${this.banner.currentMode}`):this.banner.hint;this.term(" \xB7 ").dim(d);let l=this.computeBannerPrefixText(s),u=Nn(l)+1,f=d.split(" \xB7 "),p={mode:null,pick:null,guide:null,detach:null};for(let m=0;m<f.length;m++){let h=f[m]??"",y=Nn(h),b=[u,u+y-1];h.includes("mode")&&p.mode===null?p.mode=b:h.includes("pick")&&p.pick===null?p.pick=b:h.includes("guide")&&p.guide===null?p.guide=b:h.includes("detach")&&p.detach===null&&(p.detach=b),u+=y+Nn(" \xB7 ")}if(this.bannerHits={row:e,...p},this.term.eraseLineAfter(),r){let m=Nn(r.text),h=Math.max(1,n-m);this.term.moveTo(h,e).eraseLineAfter(),r.kind==="search"?this.term.brightCyan.noFormat(r.text):r.kind==="compaction"?this.term.brightYellow.noFormat(r.text):this.term.brightYellow.noFormat(r.text)}})}placeCursor(){if(!this.started)return;if(this.permissionPrompt){let l=this.permissionRows(),f=this.term.height-l-Ye-We-qe+1+3+this.permissionPrompt.selectedIndex,p=this.term.height-Ye-We-qe;this.term.moveTo(2,Math.min(f,p));return}if(this.optionsPrompt){let l=this.optionsRows(),f=this.term.height-l-Ye-We-qe+1+1+this.optionsPrompt.selectedIndex,p=this.term.height-Ye-We-qe;this.term.moveTo(2,Math.min(f,p));return}if(this.confirmPrompt){let l=this.term.height-Qu-Ye-We-qe+1;this.term.moveTo(2,l);return}if(this.compactionPrompt){let l=this.compactionRows(),f=this.term.height-l-Ye-We-qe+1+2+this.compactionPrompt.selectedIndex,p=this.term.height-Ye-We-qe;this.term.moveTo(2,Math.min(f,p));return}if(this.helpPrompt){let l=this.helpRows(),u=this.term.height-l-Ye-We-qe+1;this.term.moveTo(2,u);return}if(this.scrollbackSearch){this.term.hideCursor(!0);return}if(this.readonly){this.term.hideCursor(!0);return}this.term.hideCursor(!1);let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=as(s.buffer,n),i=Us(r,s,Ju),a=this.term.height-i.rendered-Ye-We-qe+1+Math.max(0,i.cursorVisualRow-i.windowStart),c=i.cursorVisualCol+3,d=this.term.height-Ye-We-qe;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 Qu;if(this.compactionPrompt)return this.compactionRows();if(this.helpPrompt)return this.helpRows();if(this.readonly)return 0;let e=this.term.width,n=Math.max(1,e-2),s=this.dispatcher.state(),r=as(s.buffer,n);return Math.min(Ju,Math.max(1,r.length))}permissionRows(){return this.permissionPrompt?Math.min(OR,4+this.permissionPrompt.options.length):0}optionsRows(){return this.optionsPrompt?Math.min(LR,2+this.optionsPrompt.options.length):0}drawOptionsPrompt(){let e=this.optionsPrompt;if(!e)return;let n=this.term.width,s=this.optionsRows(),r=this.term.height-s-Ye-We-qe+1,i=r,o=(d,l)=>{i>=r+s||(this.paintRow(i,d,l),i+=1)};o(`opts|t|${n}|${e.title}`,()=>{this.term.brightYellow(` \u2699 ${dt(e.title,n-5)}`)});let a=Math.max(...e.options.map(d=>d.label.length),0);for(let d=0;d<e.options.length&&!(i>=r+s-1);d++){let l=e.options[d];if(!l)continue;let u=d===e.selectedIndex,p=` ${u?"\u276F":" "} ${d+1}. `,m=l.label.padEnd(a),h=n-p.length-3,y=`${p}${dt(`${m} ${l.value}`,h)}`;o(`opts|o|${n}|${d}|${u?"1":"0"}|${l.value}|${l.label}`,()=>{u?this.term.brightYellow(y):this.term.dim(y)})}let c=e.hint??"\u2191/\u2193 choose \xB7 Enter this session \xB7 s save default \xB7 Esc close";o(`opts|hint|${n}|${c}`,()=>{this.term.dim(` ${c}`)})}btwOverlayRows(){if(!this.btwOverlayOpen||this.btwOverlayLines.length===0)return 0;let e=Math.max(0,this.btwOverlayMaxHeight-1),n=this.term.width,s=this.wrapBtwTail(n,e).length;return Math.min(this.btwOverlayMaxHeight,1+s)}wrapBtwTail(e,n){if(e<=4){let o=Math.min(n,this.btwOverlayLines.length);return this.btwOverlayLines.slice(this.btwOverlayLines.length-o)}if(n<=0||this.btwOverlayLines.length===0)return[];let s=[],r=0;for(let o=this.btwOverlayLines.length-1;o>=0;o--){let a=this.btwOverlayLines[o],c=this.wrapOne(a,e);if(s.push(c),r+=c.length,r>=n)break}let i=[];for(let o=s.length-1;o>=0;o--)i.push(...s[o]);return i.length>n?i.slice(i.length-n):i}drawBtwOverlay(){if(!this.btwOverlayOpen)return;let e=this.btwOverlayRows();if(e===0)return;let n=this.term.width,r=this.term.height-this.promptRows()-Ye-We-qe,i=this.chipRows()+this.queuedRows()+this.completionRows(),a=r-1-i-e+1,c=e-1,d=a,l=this.buildBtwHeaderSegments();this.paintRow(d,`btw|h|${l.signature}`,()=>{this.paintBtwHeader(l)});let u=this.wrapBtwTail(n,c);for(let f=0;f<c;f++){let p=d+1+f,m=u.length-c+f,h=m>=0?u[m]:void 0,y=vw(`btw|c${f}`,n,h);this.paintRow(p,y,()=>{h?this.writeFormattedLine(h,n):this.term.noFormat(" ".repeat(n))})}}wrapTail(e,n){let s=d=>d.collapsed===!0||this.hideThoughts&&d.bodyStyle==="thought";if(e<=4){let d=[];for(let u of this.lines)s(u)||d.push(u);let l=Math.min(n,d.length);return{rows:d.slice(d.length-l),exhausted:n>=d.length}}if(this.wrapCacheWidth!==e&&(this.wrapCache.clear(),this.wrapCacheWidth=e),n<=0||this.lines.length===0)return{rows:[],exhausted:!0};let r=[],i=0,o=0,a=!1;for(let d=this.lines.length-1;d>=0;d--){let l=this.lines[d];if(s(l)){d===0&&(a=!0);continue}let u=this.wrapOne(l,e);if(r.push(u),i+=u.length,o=d,i>=n)break}let c=[];for(let d=r.length-1;d>=0;d--)c.push(...r[d]);return{rows:c,exhausted:o===0||a}}wrapOne(e,n){let s=this.lineIds.get(e);if(s!==void 0){let u=this.wrapCache.get(s);if(u)return u}let r=e.prefix??"",i=Hs(r),o=Math.max(1,n-i),a=ta(e.bodyStyle),c=e.ansi?qR(e.body,o):KR(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.fillRow&&(p.fillRow=!0),e.ansi&&(p.ansi=!0),u===0&&e.iterm2Image&&(p.iterm2Image=e.iterm2Image),s!==void 0&&f.length>0){let m=e.body.indexOf(f,l),h=m===-1?l:m;this.wrapOrigin.set(p,{sourceLineId:s,sourceColOffset:h}),l=h+f.length}d.push(p)}return s!==void 0&&this.wrapCache.set(s,d),d}writeFormattedLine(e,n,s=null,r=0,i=null){e.prefix&&os(this.term,e.prefix,e.prefixStyle??e.bodyStyle);let o=Math.max(0,n-Hs(e.prefix??"")),a=ta(e.bodyStyle),c=e.ansi?e.body:dt(e.body,o,{stripMarkup:a}),d=(l,u)=>{if(l.length!==0)if(this.scrollbackHighlight!==null&&!e.ansi){let f=s!==null&&s>=u?s-u:null;Sw(this.term,l,e.bodyStyle,this.scrollbackHighlight,f,r)}else os(this.term,l,e.bodyStyle)};if(i!==null&&!e.ansi){let l=Math.max(0,Math.min(c.length,i.start)),u=Math.max(l,Math.min(c.length,i.end)),f=ta(e.bodyStyle);if(d(c.slice(0,l),0),u>l){let m=c.slice(l,u);f&&(m=Iw(m)),os(this.term,m,"selection-highlight")}let p=c.slice(u);if(f&&u>l){let m=zR(c.slice(0,u));m.length>0&&(p=m+p)}d(p,u)}else this.scrollbackHighlight!==null&&!e.ansi?Sw(this.term,c,e.bodyStyle,this.scrollbackHighlight,s,r):os(this.term,c,e.bodyStyle);if(e.fillRow){let l=e.ansi?Nn(c):Hs(c),u=o-l;if(u>0){let f=i!==null&&i.toEndOfLine?"selection-highlight":e.bodyStyle;os(this.term," ".repeat(u),f)}}(e.ansi||e.body.includes("^"))&&this.term.styleReset(),e.iterm2Image&&this.isIterm2()&&this.writeIterm2Image(e.iterm2Image.data,e.iterm2Image.heightCells)}};Tw=/[^\x20-\x7e]/,Xu=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ew=!1;WR=/[a-zA-Z+\-:_!#/]/;Gu=et});function XR(t,e,n=lc){if(e.kind==="cancel")return{kind:"cancel"};if(e.kind==="back")return{kind:"back"};if(e.kind==="enter"){let s=n[t];return s?{kind:"resolve",action:s.key}:{kind:"back"}}if(e.kind==="up")return{kind:"continue",selected:Math.max(0,t-1)};if(e.kind==="down")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(e.kind==="char"){let s=e.ch.toLowerCase();if(s==="n")return{kind:"continue",selected:Math.min(n.length-1,t+1)};if(s==="p")return{kind:"continue",selected:Math.max(0,t-1)};let r=n.findIndex(i=>i.hotkey.toLowerCase()===s);if(r>=0){let i=n[r];if(i)return{kind:"resolve",action:i.key}}}return{kind:"continue",selected:t}}async function Fw(t,e){ss();let n=et(e.sessionId),s=e.importedFromMachine??"another machine",r=ze(e.cwd),i=lc.findIndex(a=>a.key==="view");i<0&&(i=0);let o=()=>{let c=7+lc.length*2+2,d=rs(t,{contentHeight:c,title:"Imported session"}),l=d.contentW,u=[{label:"session: ",value:n},{label:"from: ",value:s},{label:"cwd: ",value:r}],f=0;for(let p of u)t.moveTo(d.contentX,d.contentY+f),t.dim.noFormat(` ${p.label}`),t.noFormat(nt(p.value,l-p.label.length-2)),f++;return f++,Ow(t,d,f,{intro:"What do you want to do?",choices:lc,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 f/v jump \xB7 Esc back"}),d};return Bs({term:t,render:o,onKey:(a,c,d,l)=>{let u=ZR(a,d);if(!u)return;let f=XR(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 Ow(t,e,n,s){let r=e.contentW,i=n;t.moveTo(e.contentX,e.contentY+i),t.noFormat(` ${s.intro}`),i+=2;for(let o=0;o<s.choices.length;o++){let a=s.choices[o];if(!a)continue;let d=` ${o===s.selected?"\u276F":" "} ${a.label}`;t.moveTo(e.contentX,e.contentY+i),o===s.selected?t.brightWhite.bgBlue.noFormat(zd(d,r)):t.noFormat(d),i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${a.description}`),i++}i++,t.moveTo(e.contentX,e.contentY+i),t.dim.noFormat(` ${s.footer}`)}function ZR(t,e){return t==="UP"?{kind:"up"}:t==="DOWN"?{kind:"down"}:t==="ENTER"||t==="KP_ENTER"?{kind:"enter"}:t==="ESCAPE"?{kind:"back"}:t==="CTRL_C"||t==="CTRL_D"?{kind:"cancel"}:e?.isCharacter?{kind:"char",ch:t}:null}async function Lw(t,e,n){let s=et(e.sessionId),r=e.title??ze(e.cwd),i=1,o=[{label:"Launch",hotkey:"l",description:"start a new agent session"},{label:"View transcript",hotkey:"v",description:"open read-only, no agent spawn"}],a=()=>{let c=rs(t,{contentHeight:11,title:"Open session"}),d=c.contentW,l=0;t.moveTo(c.contentX,c.contentY+l),t.dim.noFormat(" session: "),t.noFormat(nt(s,d-10)),l++,t.moveTo(c.contentX,c.contentY+l),t.noFormat(" "+nt(r,d-2)),l++,l++,Ow(t,c,l,{intro:"What do you want to do?",choices:o,selected:i,footer:"\u2191/\u2193 navigate \xB7 Enter select \xB7 l/v jump \xB7 Esc back"})};return a(),t.hideCursor(),await new Promise(c=>{let d=!1,l=()=>{d=!0},u=p=>{l(),n.pop(),c(p)},f=(p,m,h)=>{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(h?.isCharacter){let y=p.toLowerCase();if(y==="l"){u("launch");return}if(y==="v"){u("view");return}if(y==="n"){i<o.length-1&&(i++,a());return}if(y==="p"){i>0&&(i--,a());return}}};n.push({onKey:(p,m,h)=>{d||f(p,m,h)},onResize:()=>{d||a()}})})}var lc,tf=K(()=>{"use strict";he();En();zi();lc=[{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 na(t){if(t.length===0)return"";let e=t[0]??"";for(let n=1;n<t.length;n++){let s=t[n]??"",r=0;for(;r<e.length&&r<s.length&&e[r]===s[r];)r+=1;if(e=e.slice(0,r),e.length===0)break}return e}function Bw(t){let{matches:e,firstLine:n}=t;if(e.length===0)return null;let s=n.indexOf(" "),r=s===-1?n:n.slice(0,s),i=s===-1?"":n.slice(s);if(e.length===1){let a=e[0]??"",c=i.startsWith(" ")?"":" ";return a+c+i}let o=na(e);return o.length<=r.length?null:o+i}var uc=K(()=>{"use strict"});import*as Nw from"os";async function _r(t,e,n={}){let s=n.defaultCwd??(e?await Gy(e.cwd):void 0)??Nw.homedir();ss();let r=n.title??"Fork locally \u2014 choose cwd",i=n.intro??"Pick a local cwd for this session:",o=e?[{label:"session: ",value:et(e.sessionId)},...e.importedFromMachine?[{label:"from: ",value:e.importedFromMachine}]:[],{label:"cwd: ",value:ze(e.cwd)}]:[],a=s,c=null,d=!1,l=null,u=[],f=[],p=()=>{u.push(a),u.length>500&&u.shift(),f=[]},m=()=>{let x=u.pop();x!==void 0&&(f.push(a),a=x)},h=()=>{let x=f.pop();x!==void 0&&(u.push(a),a=x)},y=()=>{let x=o.length+6;l=rs(t,{contentHeight:x,title:r});let T=l.contentW,_=0;for(let F of o)t.moveTo(l.contentX,l.contentY+_),t.dim.noFormat(` ${F.label}`),t.noFormat(nt(F.value,T-F.label.length-2)),_++;_++,t.moveTo(l.contentX,l.contentY+_),t.noFormat(` ${i}`),_+=2,v(_),_+=2,c!==null?(t.moveTo(l.contentX,l.contentY+_),t.red.noFormat(` ${nt(c,T-2)}`)):(t.moveTo(l.contentX,l.contentY+_),t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear"))},b=()=>o.length+3,v=x=>{if(!l)return;let T=x??b();t.moveTo(l.contentX,l.contentY+T).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+T),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+T),t.bold.noFormat(" cwd: ");let _=l.contentW-6-2;t.noFormat(e0(a,_)),d||t.bgWhite(" ")},S=()=>{if(v(),!l)return;let x=b()+2;t.moveTo(l.contentX,l.contentY+x).eraseLineAfter(),t.moveTo(l.x+l.w-1,l.contentY+x),t.dim.noFormat("\u2502"),t.moveTo(l.contentX,l.contentY+x),c!==null?t.red.noFormat(` ${nt(c,l.contentW-2)}`):t.dim.noFormat(" Enter accept \xB7 Tab complete \xB7 Esc back \xB7 ^U clear")};return Bs({term:t,render:y,hideCursor:!1,onKey:(x,T,_,F)=>{if(!d){if(x==="ENTER"||x==="KP_ENTER"){let j=a;d=!0,c=null,S(),Go(j).then(J=>{if(d=!1,J.ok){F({kind:"ok",path:J.path});return}c=J.reason,S()});return}if(x==="ESCAPE"){F({kind:"back"});return}if(x==="CTRL_C"||x==="CTRL_D"){F({kind:"cancel"});return}if(x==="TAB"){d=!0,Xy(a).then(j=>{if(d=!1,j.matches.length===0)return;let J;if(j.matches.length===1)J=j.prefix+j.matches[0];else{let D=na(j.matches);if(D.length<=j.basePrefix.length)return;J=j.prefix+D}J!==a&&(p(),a=J,c=null,S())});return}if(x==="BACKSPACE"){a.length>0&&(p(),a=a.slice(0,-1),c=null,S());return}if(x==="CTRL_U"){a.length>0&&(p(),a="",c=null,S());return}if(x==="CTRL_W"){let j=a.replace(/[/\s]+$/,""),J=Math.max(j.lastIndexOf("/"),j.lastIndexOf(" ")),D=J>=0?j.slice(0,J+1):"";D!==a&&(p(),a=D,c=null,S());return}if(x===""){m(),c=null,S();return}if(x==="\x1B_"||x==="\x1B"){h(),c=null,S();return}if(_?.isCharacter){p(),a+=x,c=null,S();return}}}})}function e0(t,e){return e<=1?"":t.length<=e?t:"\u2026"+t.slice(t.length-(e-1))}var nf=K(()=>{"use strict";he();En();Mu();uc();zi()});function rf(){return{filters:{cwdOnly:!1,hostFilter:"__local",includeNonInteractive:!1}}}async function of(t,e){let n=()=>{process.stdout.write(Ar),process.stdout.write(ns),process.stdout.write(Rr),process.stdout.write(Tr),process.stdout.write(Ui),process.stdout.write(ji),process.stdout.write(qi),process.stdout.write(Cr),process.stdout.write("\x1B>")};n();let s=e.prefs??rf();e.prefs===void 0&&e.currentSessionId!==void 0&&e.sessions.find(M=>M.sessionId===e.currentSessionId)?.importedFromMachine&&(s.filters.hostFilter="__all");let r=e.cwd,i=pc(e.sessions,r),o=R=>{let M=R;return s.filters.cwdOnly&&(M=M.filter(N=>N.cwd===r)),s.filters.includeNonInteractive||(M=M.filter(N=>N.interactive===!0)),M=i0(M,s.filters.hostFilter),M},a=o(i),c={columns:e.config.tui.sessionColumns??_i,cwdMaxWidth:e.config.tui.cwdColumnMaxWidth},d=a.map(R=>Fi(R,Date.now())),l=Oi(d,c),u=1+a.length,f=0,p=0;if(e.currentSessionId!==void 0){let R=a.findIndex(M=>M.sessionId===e.currentSessionId);R>=0&&(f=R+1)}let m=!1,h="",y=120,b=!1,v=0,S="normal",x=null,T=!1,_="input",F=new is({history:[],collapsePastes:!1}),j=[],J=!1,D=0,L=0,U=null,Q=!1,V="",be=[],Y=[],ye=()=>{be.push(V),be.length>500&&be.shift(),Y=[]},Qe=()=>{let R=be.pop();R!==void 0&&(Y.push(V),V=R)},qs=()=>{let R=Y.pop();R!==void 0&&(be.push(V),V=R)},At=()=>{be=[],Y=[]},de=null,Z=!1,Oe=new is({history:[]});e.initialPrompt&&Oe.setBuffer(e.initialPrompt);let wn=e.config.tui.promptHistoryMaxEntries;Co($.globalTuiHistoryFile()).then(R=>{let M=R.length>wn?R.slice(R.length-wn):R;Oe.setHistory(M)}).catch(()=>{});let Te=new Yi(t),Dn=Er(t),Ge=yn(t),He=0,Fr="",sn=0,rn=[],Vt=1,ds=0,Se=0,Or=0,Lr="",Ws=[],on=1,zs=0,Br=[],ct=1,cs=0,Ce=0,an=0,yt=()=>{Dn=Er(t),Ge=yn(t);let R=Math.max(10,Ge-sf-1);sn=Math.max(10,Ge-Dw);let M=Math.max(10,Ge-8);Fr=r0(r,M);let N=Oe.state();rn=as(N.buffer,sn);let ee=Us(rn,N,fc);Vt=ee.rendered,ds=ee.windowStart,Se=ee.cursorVisualRow,Or=ee.cursorVisualCol;let ae=6+Vt,Xe=Math.max(3,Dn-ae);He=Math.min(a.length,Xe),Lr=Fs($i,l,R,c).padEnd(R),Ws=d.map(ve=>Fs(ve,l,R,c).padEnd(R))},Xi=()=>{d=a.map(R=>Fi(R,Date.now())),l=Oi(d,c),u=1+a.length,yt()},ot=()=>{let R=o(i);m&&h.length>0?a=R.filter(M=>a0(M,h)):a=R,Xi(),m?(p=0,f=a.length>0?1:0):f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),Yt()},ls=R=>{if(R!==void 0){let M=a.findIndex(N=>N.sessionId===R);if(M>=0){f=M+1,Yt();return}}f=a.length>0?1:0,p=0,Yt()},Yt=()=>{if(f===0)return;let R=f-1;R<p?p=R:R>=p+He?p=R-He+1:p+He>a.length&&(p=Math.max(0,a.length-He))},bn=()=>Math.max(2,Ge-3),wt=!1,Nr=()=>{let R=bn(),M=`\u2500 ${Fr} `,N=Math.max(1,R-M.length),ee="\u2500".repeat(N);f===0||wt?t.brightBlue.noFormat(`\u256D${M}${ee}\u256E`):t.dim.noFormat(`\u256D${M}${ee}\u256E`)},us=()=>{let R=bn(),M="\u2500".repeat(R);f===0||wt?t.brightBlue.noFormat(`\u2570${M}\u256F`):t.dim.noFormat(`\u2570${M}\u256F`)},Dr=R=>{let M=rn[R];return M?(Oe.state().buffer[M.bufferIdx]??"").slice(M.startCol,M.endCol):""},dn=R=>{let M=bn(),N=Dr(R),ee=Math.max(0,M-1-N.length),ae=" ".repeat(ee);f===0||wt?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${N}${ae}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${N}${ae}`),t.dim.noFormat("\u2502"))},Js=R=>{let M=Ws[R]??"",N=a[R],ee=N&&N.priority&&N.priority>0?"* ":" ";f===R+1&&!wt?t.brightWhite.bgBlue.noFormat(`${ee}${M}`):t.noFormat(`${ee}${M}`)},fs=()=>{let R=p,M=Math.max(0,a.length-p-He),N=[];return s.filters.cwdOnly&&N.push("cwd-only"),s.filters.hostFilter!=="__all"&&N.push(s.filters.hostFilter==="__local"?"host: local":`host: ${s.filters.hostFilter}`),s.filters.includeNonInteractive&&N.push("+non-interactive"),R>0&&N.push(`\u2191 ${R} above`),M>0&&N.push(`\u2193 ${M} below`),N.length===0?"":` ${N.join(" \xB7 ")}`},Ks=R=>et(R),Ot=()=>{let R=x?`${x.sessionId}|${x.status}`:"";return["ind",S,R,V,de??"",m?`1|${h}|${a.length}`:"0",fs()].join("")},me=()=>{Be(()=>{Te.paintRow(bt(),Ot(),()=>{if(S==="confirm-kill"&&x)t.brightYellow.noFormat(` kill ${Ks(x.sessionId)}? [y/N]`);else if(S==="confirm-delete"&&x)x.status==="live"?t.brightRed.noFormat(` kill + delete ${Ks(x.sessionId)}? [y/N]`):t.brightRed.noFormat(` delete ${Ks(x.sessionId)}? [y/N]`);else if(S==="busy"&&x)t.dim.noFormat(` working on ${Ks(x.sessionId)}\u2026`);else if(S==="rename"&&x)t.brightYellow.noFormat(` title: ${V}`),t.bgBrightYellow(" "),t.dim.noFormat(" Enter saves \xB7 Esc cancels");else if(de!==null)t.dim.noFormat(` ${de}`);else if(m){t.brightYellow.noFormat(` /${h}`),t.bgBrightYellow(" ");let R=a.length===0?" no matches":` ${a.length} match${a.length===1?"":"es"}`;t.dim.noFormat(`${R} \xB7 ^c clears`)}else t.dim.noFormat(fs())})})},Qt=R=>on+1+R,ke=()=>on+Vt+1,cn=()=>on+Vt+3,Vs=R=>cn()+1+(R-p),bt=()=>cn()+1+He,Lt=()=>{let R=Se-ds;if(R<0||R>=Vt)return;let M=3+Or;t.moveTo(M,Qt(R))},ps=()=>f===0?"f":wt?"h":"u",I=()=>`ct|${ps()}|${bn()}|${Fr}`,Zi=()=>`cb|${ps()}|${bn()}`,eo=R=>`cbb|${ps()}|${bn()}|${Dr(R)}`,to=()=>`h|${Lr}`,Hn=R=>{let M=a[R],N=M&&M.priority&&M.priority>0?"* ":" ",ee=Ws[R]??"";return`sr|${f===R+1&&!wt?"1":"0"}|${N}${ee}`},De=()=>{Be(()=>{t.hideCursor(),yt(),Yt(),on=1,Te.ensureSize(Ge,Dn),Te.paintRow(on,I(),()=>{Nr()});for(let R=0;R<Vt;R++){let M=ds+R;Te.paintRow(Qt(R),eo(M),()=>{dn(M)})}Te.paintRow(ke(),Zi(),()=>{us()}),Te.paintRow(ke()+1,"blank",()=>{}),Te.paintRow(cn(),to(),()=>{t.dim.noFormat(` ${Lr}`)});for(let R=0;R<He;R++){let M=p+R,N=cn()+1+R;M<a.length?Te.paintRow(N,Hn(M),()=>{Js(M)}):Te.paintRow(N,"blank",()=>{})}me();for(let R=bt()+1;R<=Dn;R++)Te.paintRow(R,"blank",()=>{});f===0&&(Lt(),t.hideCursor(!1))})},no=()=>{Te.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),De()},sa=()=>{Be(()=>{t.hideCursor(),Te.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(" Picker hotkeys")(`
164
164
 
165
- `);for(let R of OR){if(R===null){t(`
166
- `);continue}let[P,L]=R;t.brightCyan.noFormat(` ${P.padEnd($R)}`),t.noFormat(L)(`
165
+ `);for(let R of s0){if(R===null){t(`
166
+ `);continue}let[M,N]=R;t.brightCyan.noFormat(` ${M.padEnd(n0)}`),t.noFormat(N)(`
167
167
  `)}t(`
168
168
  `),t.dim.noFormat(" press any key to dismiss")(`
169
- `)})},At=()=>ut+4,nc=2,st=0,yn=()=>{$n=wr(t);let R=Math.max(2,$n-(ut+3)-nc);return Math.max(1,Math.floor(R/2))},Ln=()=>{let R=yn();B<st?st=B:B>=st+R&&(st=B-R+1),st+R>H.length&&(st=Math.max(0,H.length-R)),st<0&&(st=0)},Wi=R=>{Ke=fn(t);let P=Math.max(2,Ke-2),L="\u2500 Find sessions ",Z="\u2500".repeat(Math.max(1,P-L.length));R?t.brightBlue.noFormat(`\u256D${L}${Z}\u256E`):t.dim.noFormat(`\u256D${L}${Z}\u256E`),t.styleReset()},Ns=()=>{Ke=fn(t),$s=Math.max(10,Ke-vw);let R=$.state();Rr=Zn(R.buffer,$s);let P=Es(Rr,R,_R);ut=P.rendered,ts=P.windowStart,Pe=P.cursorVisualRow,Xt=P.cursorVisualCol},zi=(R,P)=>{Ke=fn(t);let L=Math.max(2,Ke-2),Z=Rr[R],re="";Z&&(re=($.state().buffer[Z.bufferIdx]??"").slice(Z.startCol,Z.endCol));let Ye=Math.max(0,L-1-re.length),Se=" ".repeat(Ye);P?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${re}${Se}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${re}${Se}`),t.dim.noFormat("\u2502")),t.styleReset()},Vo=R=>{Ke=fn(t);let P=Math.max(2,Ke-2),L="\u2500".repeat(P);R?t.brightBlue.noFormat(`\u2570${L}\u256F`):t.dim.noFormat(`\u2570${L}\u256F`),t.styleReset()},Ds=()=>3+Xt,Hs=()=>2+(Pe-ts),Ji=()=>{let R=F==="input";De(()=>{R&&t.hideCursor(),t.moveTo(1,1),Wi(R);for(let P=0;P<ut;P++)t.moveTo(1,2+P),zi(ts+P,R);t.moveTo(1,2+ut),Vo(R),R&&(t.moveTo(Ds(),Hs()),t.hideCursor(!1))})},_t=()=>{De(()=>{t.hideCursor();for(let R=0;R<ut;R++)t.moveTo(1,2+R),zi(ts+R,!0);t.moveTo(Ds(),Hs()),t.hideCursor(!1)})},wt={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Go=(R,P)=>{let L=H[R];if(!L)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let Z=fn(t),re=Math.max(20,Z-Ju),Ye=Ve(L.sessionId),Se=L.title??Ue(L.cwd),$t=P&&L.snippets.length>1?` [${N+1}/${L.snippets.length}]`:P&&L.totalMatches>L.snippets.length?` [${L.snippets.length} of ${L.totalMatches}]`:"",Tt=`${Ye} ${L.status==="live"?"live":"cold"}`,bt=Math.max(5,re-Tt.length-$t.length-2),Ot=Mo(Se,bt),bn=`${Tt} ${Ot}${$t}`.padEnd(re),dt=L.snippets[P?N:0],vt=dt?wt[dt.kind]??dt.kind:"",Ze=dt?.toolName?`${vt} \xB7 ${dt.toolName}`:vt,qs=Math.max(10,re-Ze.length-6),Ws=dt?Mo(dt.text,qs):"",Bn=dt?` ${Ze} ${Ws}`:" (no snippet)";return{rowBudget:re,line1:bn,line2:Bn.padEnd(re+Ju),focusedRow:P}},Mr=(R,P)=>{let{line1:L,focusedRow:Z}=Go(R,P);Z?t.brightWhite.bgBlue.noFormat(`\u276F ${L}`):t.noFormat(` ${L}`),t.styleReset()},Us=(R,P)=>{let{line2:L}=Go(R,P);t.dim.noFormat(L),t.styleReset()},wn=()=>{if(X)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(j!==null)t.brightRed.noFormat(` ${j}`),t.styleReset(),t.eraseLineAfter();else if(F==="input")H.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let R=H.length,P=J?" \xB7 truncated":"",L=R>0?` ${R} ${R===1?"session":"sessions"} match${P} \xB7 `:" ";t.dim.noFormat(`${L}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},tn=()=>{Ns();let R=F==="input",P=$.state().buffer.join(`
170
- `);De(()=>{t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),Wi(R);for(let Z=0;Z<ut;Z++)t.moveTo(1,2+Z),zi(ts+Z,R);t.moveTo(1,2+ut),Vo(R);let L=H.length;if(L===0)t.moveTo(1,At()),X||(j===null&&P.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):j===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,At()+1),wn();else{Ln();let Z=yn(),re=F!=="input";for(let Ye=0;Ye<Z;Ye++){let Se=st+Ye;t.moveTo(1,At()+Ye*2),Se<L?Mr(Se,re&&Se===B):t.eraseLineAfter(),t.moveTo(1,At()+Ye*2+1),Se<L?Us(Se,re&&Se===B):t.eraseLineAfter()}t.moveTo(1,At()+Z*2),wn()}R&&(t.moveTo(Ds(),Hs()),t.hideCursor(!1))})},rs=(R,P)=>{let L=R-st;L<0||L>=yn()||De(()=>{t.moveTo(1,At()+L*2),Mr(R,P),t.moveTo(1,At()+L*2+1),Us(R,P)})},_r=()=>{De(()=>{t.moveTo(1,At()+yn()*2),wn()})},Ki=()=>{De(()=>{let R=yn(),P=H.length,L=F!=="input";for(let Z=0;Z<R;Z++){let re=st+Z;t.moveTo(1,At()+Z*2),re<P?Mr(re,L&&re===B):t.eraseLineAfter(),t.moveTo(1,At()+Z*2+1),re<P?Us(re,L&&re===B):t.eraseLineAfter()}t.moveTo(1,At()+R*2),wn()})},$r=()=>$.state().buffer.join(`
171
- `),Qo=R=>{let P=ut;$.feed({type:"paste",text:R}),Ns(),ut!==P?tn():_t()},sc=async()=>{let R=$r().trim();if(R.length!==0){if(a.length===0){j="no sessions in view to search",tn();return}X=!0,j=null,tn();try{let P=await Uh(e.target,R,{sessionIds:a.map(L=>L.sessionId)});H=P.results,J=P.truncated,B=0,N=0,st=0,F=P.results.length>0?"results":"input",Ns()}catch(P){j=`search failed: ${P.message}`}finally{X=!1,tn()}}},Yi=()=>{},js=()=>{De(()=>{let R=u===0;R&&t.hideCursor(),Ce.paintRow(mn,Fs(),()=>{Tr()}),Ce.paintRow(en(),Ls(),()=>{Er()});for(let P=0;P<Ut;P++){let L=es+P;Ce.paintRow(yt(P),k(L),()=>{Os(L)})}R&&(Ge(),t.hideCursor(!1))})},qt=()=>{De(()=>{let R=$e.state();Qt=Zn(R.buffer,Gt);let P=Es(Qt,R,Zd);es=P.windowStart,ve=P.cursorVisualRow,Cr=P.cursorVisualCol;let L=u===0;L&&t.hideCursor();for(let Z=0;Z<Ut;Z++){let re=es+Z;Ce.paintRow(yt(Z),k(re),()=>{Os(re)})}L&&(Ge(),t.hideCursor(!1))})},rc=R=>{R<p||R>=p+Xe||De(()=>{Ce.paintRow(Yo(R),Pr(R),()=>{jt(R)})})},Vi=()=>{De(()=>{for(let R=0;R<Xe;R++){let P=me()+1+R,L=p+R;L<a.length?Ce.paintRow(P,Pr(L),()=>{jt(L)}):Ce.paintRow(P,"blank",()=>{})}ue()})},Xo=()=>{De(()=>{Ce.paintRow(me(),qi(),()=>{t.dim.noFormat(` ${Ar}`)});for(let R=0;R<Xe;R++){let P=me()+1+R,L=p+R;L<a.length?Ce.paintRow(P,Pr(L),()=>{jt(L)}):Ce.paintRow(P,"blank",()=>{})}ue(),u===0&&(Ge(),t.hideCursor(!1))})},nn=!1,is="",Rt=null,Gi=null,Zo=null,Or=R=>{let P=R.toString("binary");if(!nn&&P===""&&Gi){Gi();return}if(!nn&&(P===""||P==="\x1B_"||P==="\x1B")){Zo?.(P);return}if(nn){let Z=P.indexOf(Oo);if(Z===-1){is+=P;return}is+=P.slice(0,Z),nn=!1;let re=Buffer.from(is,"binary").toString("utf-8").replace(/\r\n?/g,`
172
- `);is="";let Ye=P.slice(Z+Oo.length);if(T)F==="input"&&!X&&Qo(re);else if(u===0&&!m){$e.feed({type:"paste",text:re});let Se=$e.state(),$t=Zn(Se.buffer,Gt);Es($t,Se,Zd).rendered!==Ut?Qe():qt()}Ye.length>0&&Rt&&Rt(Buffer.from(Ye,"binary"));return}let L=P.indexOf(Ei);if(L===-1){Rt?.(R);return}L>0&&Rt?.(Buffer.from(P.slice(0,L),"binary")),P=P.slice(L+Ei.length),nn=!0,P.length>0&&Or(Buffer.from(P,"binary"))};return Qe(),await new Promise(R=>{let P=!1,L=null,Z=!1,re=null,Ye=!1,Se=[],$t=E=>{Se.push(E)},Tt=()=>{Se.pop(),P||Se[Se.length-1]?.onResize()},bt={push:$t,pop:Tt},Ot=()=>({kind:"new",cwd:r}),bn=async()=>{Ks(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),$t({onKey:()=>{},onResize:()=>{}});let W;try{W=await kr(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Tt(),jn()}W.kind==="ok"&&W.path!==r&&(r=W.path,i=ec(i,r),at()),P||Qe()};Yi=()=>{$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,st=0,j=null,X=!1,F="input",T=!1,Tt()};let dt=(E,W,ie)=>{Ws(),Se[Se.length-1]?.onKey(E,W,ie)},vt=()=>{P||Se[Se.length-1]?.onResize()};Zo=E=>{P||Se[Se.length-1]?.onKey(E,null,{})};let Ze=()=>{if(P)return;P=!0,Se.length=0,L&&(clearInterval(L),L=null),re&&(re.abort(),re=null,Z=!1),t.off("key",dt),t.off("resize",vt),process.stdout.write(Yn);let E=t;E.stdin&&Rt&&(E.stdin.removeListener("data",Or),E.stdin.on("data",Rt),Rt=null),nn=!1,is="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,On()+1),t(`
173
- `)},qs=()=>{if(P||Se.length>1||S!=="normal"||m||Ye)return;Z&&re&&(re.abort(),re=null,Z=!1);let E=u>0?a[u-1]?.sessionId:void 0;Z=!0;let W=new AbortController;re=W,os(E,{silent:!0,signal:W.signal}).finally(()=>{re===W&&(re=null),Z=!1})},Ws=()=>{P||(L&&clearInterval(L),L=setInterval(qs,3e3))},Bn=()=>(Ze(),R({kind:ee?"exit":"abort"}),!0),ea=()=>{let E=d.map(W=>`${W.session}|${W.upstream}|${W.host}|${W.state}|${W.agent}|${W.model}|${W.age}|${W.title}|${W.cwd}|${W.cost}`).join(`
174
- `);return`${u}:${p}:${de??""}
175
- ${E}`},os=async(E,W={})=>{try{let ie=W.silent?ea():"",q=f,ne=await En(e.target,{includeNonInteractive:!0,signal:W.signal}),oe=E??(u>0?a[u-1]?.sessionId:void 0);if(i=ec(ne,r),at(),oe!==void 0){let Me=a.findIndex(He=>He.sessionId===oe);Me>=0?u=Me+1:u=0}if(u>f-1&&(u=Math.max(0,f-1)),p+Xe>a.length&&(p=Math.max(0,a.length-Xe)),Zt(),W.silent&&ea()===ie)return;f===q?Xo():Qe()}catch(ie){if(W.silent)return;de=`refresh failed: ${ie.message}`,Qe()}},Qi=async E=>{if(!x)return;let W=x;S="busy",ue();try{await Nh(e.target,W.sessionId,E),S="normal",x=null,Y="",await os(W.sessionId)}catch(ie){S="normal",x=null,Y="",de=`rename failed: ${ie.message}`,ue()}},rt=async E=>{try{await Hh(e.target,E.sessionId),de="title regen queued (press r to refresh)",ue()}catch(W){de=`regen failed: ${W.message}`,ue()}},Nn=async E=>{let ie=(E.priority&&E.priority>0?E.priority:0)>0?null:1,q=ie??0;for(let oe of i)oe.sessionId===E.sessionId&&(oe.priority=q>0?q:void 0);let ne=E.sessionId;i=ec(i,r),at(),ns(ne),Qe(),de=q>0?"priority: high":"priority: normal",ue();try{await Dh(e.target,E.sessionId,ie)}catch(oe){de=`priority failed: ${oe.message}`,ue()}},Dn=async()=>{if(Ye)return;Ye=!0;let E=u>0?a[u-1]?.sessionId:void 0;de="syncing agents\u2026",ue();try{let{synced:W,skipped:ie,agents:q}=await Bh(e.target);await os(E),de=`synced ${W} new (${ie} known) from ${q} agent${q===1?"":"s"}`,ue()}catch(W){de=`sync failed: ${W.message}`,ue()}finally{Ye=!1}},as=async E=>{if(!x)return;let W=x;S="busy",ue();try{E==="kill"?await Pn(e.target,W.sessionId):await jh(e.target,W.sessionId),S="normal",x=null,W.sessionId===e.currentSessionId&&(ee=!0);let ie;if(E==="kill")ie=W.sessionId;else{let q=a.findIndex(ne=>ne.sessionId===W.sessionId);q>=0&&(ie=a[q+1]?.sessionId??a[q-1]?.sessionId)}await os(ie)}catch(ie){S="normal",x=null,de=`${E} failed: ${ie.message}`,ue()}},Hn=(E,W)=>{E===0!=(W===0)&&(js(),W===0?(t.hideCursor(!1),Ge()):t.hideCursor())},ct=E=>{let W=Math.min(f-1,Math.max(0,u+E));if(W===u)return;let ie=u;u=W,Zt(),De(()=>{Vi(),Hn(ie,u)})},sn=()=>de===null?!1:(de=null,ue(),!0),Un=()=>{Fn(),$t({onKey:E=>{if(E==="CTRL_C"){Ze(),R({kind:"abort"});return}Tt()},onResize:()=>Fn()})},zs=E=>{let W=null,ie=null,q=!0,ne=()=>{De(()=>{if(t.hideCursor(),Ce.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${Ve(E.sessionId)}`)(`
169
+ `)})},Bt=()=>ct+4,ra=2,Ue=0,vn=()=>{Dn=Er(t);let R=Math.max(2,Dn-(ct+3)-ra);return Math.max(1,Math.floor(R/2))},ia=()=>{let R=vn();D<Ue?Ue=D:D>=Ue+R&&(Ue=D-R+1),Ue+R>j.length&&(Ue=Math.max(0,j.length-R)),Ue<0&&(Ue=0)},oa=R=>{Ge=yn(t);let M=Math.max(2,Ge-3),N="\u2500 Find sessions ",ee="\u2500".repeat(Math.max(1,M-N.length));R?t.brightBlue.noFormat(`\u256D${N}${ee}\u256E`):t.dim.noFormat(`\u256D${N}${ee}\u256E`),t.styleReset()},Ys=()=>{Ge=yn(t),zs=Math.max(10,Ge-Dw);let R=F.state();Br=as(R.buffer,zs);let M=Us(Br,R,t0);ct=M.rendered,cs=M.windowStart,Ce=M.cursorVisualRow,an=M.cursorVisualCol},so=(R,M)=>{Ge=yn(t);let N=Math.max(2,Ge-3),ee=Br[R],ae="";ee&&(ae=(F.state().buffer[ee.bufferIdx]??"").slice(ee.startCol,ee.endCol));let Xe=Math.max(0,N-1-ae.length),ve=" ".repeat(Xe);M?(t.brightBlue.noFormat("\u2502"),t.noFormat(` ${ae}${ve}`),t.brightBlue.noFormat("\u2502")):(t.dim.noFormat("\u2502"),t.noFormat(` ${ae}${ve}`),t.dim.noFormat("\u2502")),t.styleReset()},aa=R=>{Ge=yn(t);let M=Math.max(2,Ge-3),N="\u2500".repeat(M);R?t.brightBlue.noFormat(`\u2570${N}\u256F`):t.dim.noFormat(`\u2570${N}\u256F`),t.styleReset()},Qs=()=>3+an,lt=()=>2+(Ce-cs),at=()=>{let R=_==="input";Be(()=>{R&&t.hideCursor(),t.moveTo(1,1),oa(R);for(let M=0;M<ct;M++)t.moveTo(1,2+M),so(cs+M,R);t.moveTo(1,2+ct),aa(R),R&&(t.moveTo(Qs(),lt()),t.hideCursor(!1))})},da=()=>{Be(()=>{t.hideCursor();for(let R=0;R<ct;R++)t.moveTo(1,2+R),so(cs+R,!0);t.moveTo(Qs(),lt()),t.hideCursor(!1)})},ca={user:"user",agent:"agent",thought:"thought",tool:"tool","tool-input":"tool-input"},Hr=(R,M)=>{let N=j[R];if(!N)return{rowBudget:20,line1:"",line2:"",focusedRow:!1};let ee=yn(t),ae=Math.max(20,ee-sf),Xe=et(N.sessionId),ve=N.title??ze(N.cwd),St=M&&N.snippets.length>1?` [${L+1}/${N.snippets.length}]`:M&&N.totalMatches>N.snippets.length?` [${N.snippets.length} of ${N.totalMatches}]`:"",Ht=`${Xe} ${N.status==="live"?"live":"cold"}`,jr=Math.max(5,ae-Ht.length-St.length-2),nr=Uo(ve,jr),gs=`${Ht} ${nr}${St}`.padEnd(ae),Tt=N.snippets[M?L:0],ys=Tt?ca[Tt.kind]??Tt.kind:"",ut=Tt?.toolName?`${ys} \xB7 ${Tt.toolName}`:ys,zn=Math.max(10,ae-ut.length-6),kt=Tt?Uo(Tt.text,zn):"",Et=Tt?` ${ut} ${kt}`:" (no snippet)";return{rowBudget:ae,line1:gs,line2:Et.padEnd(ae+sf),focusedRow:M}},Un=(R,M)=>{let{line1:N,focusedRow:ee}=Hr(R,M);ee?t.brightWhite.bgBlue.noFormat(`\u276F ${N}`):t.noFormat(` ${N}`),t.styleReset()},Gs=(R,M)=>{let{line2:N}=Hr(R,M);t.dim.noFormat(N),t.styleReset()},Ur=()=>{if(Q)t.dim.noFormat(" searching\u2026"),t.styleReset(),t.eraseLineAfter();else if(U!==null)t.brightRed.noFormat(` ${U}`),t.styleReset(),t.eraseLineAfter();else if(_==="input")j.length>0?t.dim.noFormat(" Enter to search \xB7 \u2193 browse results \xB7 Esc cancel"):t.dim.noFormat(" Enter to search \xB7 Esc cancel"),t.styleReset(),t.eraseLineAfter();else{let R=j.length,M=J?" \xB7 truncated":"",N=R>0?` ${R} ${R===1?"session":"sessions"} match${M} \xB7 `:" ";t.dim.noFormat(`${N}\u2191 edit query \xB7 Up/Down sessions \xB7 n/p snippets \xB7 Enter open \xB7 Esc back`),t.styleReset(),t.eraseLineAfter()}},jn=()=>{Ys();let R=_==="input",M=F.state().buffer.join(`
170
+ `);Be(()=>{t.hideCursor(),Te.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),oa(R);for(let ee=0;ee<ct;ee++)t.moveTo(1,2+ee),so(cs+ee,R);t.moveTo(1,2+ct),aa(R);let N=j.length;if(N===0)t.moveTo(1,Bt()),Q||(U===null&&M.trim().length===0?(t.dim.noFormat(" type a query in the box above, then press Enter"),t.eraseLineAfter()):U===null&&(t.dim.noFormat(" no matches"),t.eraseLineAfter())),t.moveTo(1,Bt()+1),Ur();else{ia();let ee=vn(),ae=_!=="input";for(let Xe=0;Xe<ee;Xe++){let ve=Ue+Xe;t.moveTo(1,Bt()+Xe*2),ve<N?Un(ve,ae&&ve===D):t.eraseLineAfter(),t.moveTo(1,Bt()+Xe*2+1),ve<N?Gs(ve,ae&&ve===D):t.eraseLineAfter()}t.moveTo(1,Bt()+ee*2),Ur()}R&&(t.moveTo(Qs(),lt()),t.hideCursor(!1))})},qn=(R,M)=>{let N=R-Ue;N<0||N>=vn()||Be(()=>{t.moveTo(1,Bt()+N*2),Un(R,M),t.moveTo(1,Bt()+N*2+1),Gs(R,M)})},ms=()=>{Be(()=>{t.moveTo(1,Bt()+vn()*2),Ur()})},ro=()=>{Be(()=>{let R=vn(),M=j.length,N=_!=="input";for(let ee=0;ee<R;ee++){let ae=Ue+ee;t.moveTo(1,Bt()+ee*2),ae<M?Un(ae,N&&ae===D):t.eraseLineAfter(),t.moveTo(1,Bt()+ee*2+1),ae<M?Gs(ae,N&&ae===D):t.eraseLineAfter()}t.moveTo(1,Bt()+R*2),Ur()})},la=()=>F.state().buffer.join(`
171
+ `),gc=R=>{let M=ct;F.feed({type:"paste",text:R}),Ys(),ct!==M?jn():da()},Xs=async()=>{let R=la().trim();if(R.length!==0){if(a.length===0){U="no sessions in view to search",jn();return}Q=!0,U=null,jn();try{let M=await ng(e.target,R,{sessionIds:a.map(N=>N.sessionId)});j=M.results,J=M.truncated,D=0,L=0,Ue=0,_=M.results.length>0?"results":"input",Ys()}catch(M){U=`search failed: ${M.message}`}finally{Q=!1,jn()}}},Nt=()=>{},Dt=()=>{Be(()=>{let R=f===0;R&&t.hideCursor(),Te.paintRow(on,I(),()=>{Nr()}),Te.paintRow(ke(),Zi(),()=>{us()});for(let M=0;M<Vt;M++){let N=ds+M;Te.paintRow(Qt(M),eo(N),()=>{dn(N)})}R&&(Lt(),t.hideCursor(!1))})},hs=()=>{Be(()=>{let R=Oe.state();rn=as(R.buffer,sn);let M=Us(rn,R,fc);ds=M.windowStart,Se=M.cursorVisualRow,Or=M.cursorVisualCol;let N=f===0;N&&t.hideCursor();for(let ee=0;ee<Vt;ee++){let ae=ds+ee;Te.paintRow(Qt(ee),eo(ae),()=>{dn(ae)})}N&&(Lt(),t.hideCursor(!1))})},Zs=R=>{R<p||R>=p+He||Be(()=>{Te.paintRow(Vs(R),Hn(R),()=>{Js(R)})})},vt=()=>{Be(()=>{for(let R=0;R<He;R++){let M=cn()+1+R,N=p+R;N<a.length?Te.paintRow(M,Hn(N),()=>{Js(N)}):Te.paintRow(M,"blank",()=>{})}me()})},er=()=>{Be(()=>{Te.paintRow(cn(),to(),()=>{t.dim.noFormat(` ${Lr}`)});for(let R=0;R<He;R++){let M=cn()+1+R,N=p+R;N<a.length?Te.paintRow(M,Hn(N),()=>{Js(N)}):Te.paintRow(M,"blank",()=>{})}me(),f===0&&(Lt(),t.hideCursor(!1))})},Sn=!1,kn="",Rt=null,tr=null,ua=null,Wn=R=>{let M=R.toString("binary");if(!Sn&&M===""&&tr){tr();return}if(!Sn&&(M===""||M==="\x1B_"||M==="\x1B")){ua?.(M);return}if(Sn){let ee=M.indexOf(Wo);if(ee===-1){kn+=M;return}kn+=M.slice(0,ee),Sn=!1;let ae=Buffer.from(kn,"binary").toString("utf-8").replace(/\r\n?/g,`
172
+ `);kn="";let Xe=M.slice(ee+Wo.length);if(T)_==="input"&&!Q&&gc(ae);else if(f===0&&!m){Oe.feed({type:"paste",text:ae});let ve=Oe.state(),St=as(ve.buffer,sn);Us(St,ve,fc).rendered!==Vt?De():hs()}Xe.length>0&&Rt&&Rt(Buffer.from(Xe,"binary"));return}let N=M.indexOf(Hi);if(N===-1){Rt?.(R);return}N>0&&Rt?.(Buffer.from(M.slice(0,N),"binary")),M=M.slice(N+Hi.length),Sn=!0,M.length>0&&Wn(Buffer.from(M,"binary"))};return De(),await new Promise(R=>{let M=!1,N=null,ee=!1,ae=null,Xe=!1,ve=[],St=P=>{ve.push(P)},Ht=()=>{ve.pop(),M||ve[ve.length-1]?.onResize()},jr={push:St,pop:Ht},nr=()=>({kind:"new",cwd:r}),gs=async()=>{Gt(),Te.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),St({onKey:()=>{},onResize:()=>{}});let z;try{z=await _r(t,void 0,{defaultCwd:r,title:"Change cwd",intro:"New cwd for the picker and any new sessions:"})}finally{Ht(),Yn()}z.kind==="ok"&&z.path!==r&&(r=z.path,i=pc(i,r),ot()),M||De()};Nt=()=>{F=new is({history:[],collapsePastes:!1}),j=[],J=!1,D=0,L=0,Ue=0,U=null,Q=!1,_="input",T=!1,Ht()};let Tt=(P,z,ce)=>{kt(),ve[ve.length-1]?.onKey(P,z,ce)},ys=()=>{M||ve[ve.length-1]?.onResize()};ua=P=>{M||ve[ve.length-1]?.onKey(P,null,{})};let ut=()=>{if(M)return;M=!0,ve.length=0,N&&(clearInterval(N),N=null),ae&&(ae.abort(),ae=null,ee=!1),t.off("key",Tt),t.off("mouse",ln),t.off("resize",ys),process.stdout.write(ns);let P=t;P.stdin&&Rt&&(P.stdin.removeListener("data",Wn),P.stdin.on("data",Rt),Rt=null),Sn=!1,kn="",t.grabInput(!1),t.hideCursor(!1),t.moveTo(1,bt()+1),t(`
173
+ `)},zn=()=>{if(M||ve.length>1||S!=="normal"||m||Xe)return;ee&&ae&&(ae.abort(),ae=null,ee=!1);let P=f>0?a[f-1]?.sessionId:void 0;ee=!0;let z=new AbortController;ae=z,In(P,{silent:!0,signal:z.signal}).finally(()=>{ae===z&&(ae=null),ee=!1})},kt=()=>{M||(N&&clearInterval(N),N=setInterval(zn,3e3))},Et=()=>(ut(),R({kind:Z?"exit":"abort"}),!0),Jn=()=>{let P=d.map(z=>`${z.session}|${z.upstream}|${z.host}|${z.state}|${z.agent}|${z.model}|${z.age}|${z.title}|${z.cwd}|${z.cost}`).join(`
174
+ `);return`${f}:${p}:${de??""}
175
+ ${P}`},In=async(P,z={})=>{try{let ce=z.silent?Jn():"",q=u,te=await Fn(e.target,{includeNonInteractive:!0,signal:z.signal}),ie=P??(f>0?a[f-1]?.sessionId:void 0);if(i=pc(te,r),ot(),ie!==void 0){let se=a.findIndex(Ee=>Ee.sessionId===ie);se>=0?f=se+1:f=0}if(f>u-1&&(f=Math.max(0,u-1)),p+He>a.length&&(p=Math.max(0,a.length-He)),Yt(),z.silent&&Jn()===ce)return;u===q?er():De()}catch(ce){if(z.silent)return;de=`refresh failed: ${ce.message}`,De()}},xn=async P=>{if(!x)return;let z=x;S="busy",me();try{await Zh(e.target,z.sessionId,P),S="normal",x=null,V="",await In(z.sessionId)}catch(ce){S="normal",x=null,V="",de=`rename failed: ${ce.message}`,me()}},sr=async P=>{try{await tg(e.target,P.sessionId),de="title regen queued (press r to refresh)",me()}catch(z){de=`regen failed: ${z.message}`,me()}},fa=async P=>{let ce=(P.priority&&P.priority>0?P.priority:0)>0?null:1,q=ce??0;for(let ie of i)ie.sessionId===P.sessionId&&(ie.priority=q>0?q:void 0);let te=P.sessionId;i=pc(i,r),ot(),ls(te),De(),de=q>0?"priority: high":"priority: normal",me();try{await eg(e.target,P.sessionId,ce)}catch(ie){de=`priority failed: ${ie.message}`,me()}},io=async()=>{if(Xe)return;Xe=!0;let P=f>0?a[f-1]?.sessionId:void 0;de="syncing agents\u2026",me();try{let{synced:z,skipped:ce,agents:q}=await Xh(e.target);await In(P),de=`synced ${z} new (${ce} known) from ${q} agent${q===1?"":"s"}`,me()}catch(z){de=`sync failed: ${z.message}`,me()}finally{Xe=!1}},pa=async P=>{if(!x)return;let z=x;S="busy",me();try{P==="kill"?await On(e.target,z.sessionId):await sg(e.target,z.sessionId),S="normal",x=null,z.sessionId===e.currentSessionId&&(Z=!0);let ce;if(P==="kill")ce=z.sessionId;else{let q=a.findIndex(te=>te.sessionId===z.sessionId);q>=0&&(ce=a[q+1]?.sessionId??a[q-1]?.sessionId)}await In(ce)}catch(ce){S="normal",x=null,de=`${P} failed: ${ce.message}`,me()}},qr=(P,z)=>{P===0!=(z===0)&&(Dt(),z===0?(t.hideCursor(!1),Lt()):t.hideCursor())},Pt=P=>{let z=Math.min(u-1,Math.max(0,f+P));if(z===f)return;let ce=f;f=z,Yt(),Be(()=>{vt(),qr(ce,f)})},oo=()=>de===null?!1:(de=null,me(),!0),st=()=>{sa(),St({onKey:P=>{if(P==="CTRL_C"){ut(),R({kind:"abort"});return}Ht()},onResize:()=>sa()})},Kn=P=>{let z=null,ce=null,q=!0,te=()=>{Be(()=>{if(t.hideCursor(),Te.clearCache(),t.moveTo(1,1).eraseDisplayBelow(),t.brightWhite.bold.noFormat(` Session info \u2014 ${et(P.sessionId)}`)(`
176
176
 
177
177
  `),q)t.dim.noFormat(" loading\u2026")(`
178
- `);else if(ie!==null)t.brightRed.noFormat(` ${ie}`)(`
179
- `);else if(W!==null)for(let He of W)t.noFormat(` ${He}`)(`
178
+ `);else if(ce!==null)t.brightRed.noFormat(` ${ce}`)(`
179
+ `);else if(z!==null)for(let Ee of z)t.noFormat(` ${Ee}`)(`
180
180
  `);t(`
181
181
  `),t.dim.noFormat(" Esc / ^C to return")(`
182
- `)})};ne();let oe=new AbortController,Me={onKey:He=>{if(He==="ESCAPE"||He==="CTRL_C"){oe.abort(),Tt();return}},onResize:()=>ne()};$t(Me),(async()=>{try{let He=await Ht(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(E.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:oe.signal});if(!He.ok)throw new Error(`daemon returned HTTP ${He.status}`);let et=await He.json(),St=ln(et),Oe=iu(St,E.status);W=Ad(Oe,!1).replace(/\n$/,"").split(`
183
- `)}catch(He){if(oe.signal.aborted)return;ie=`failed to load info: ${He.message}`}finally{q=!1,!P&&Se[Se.length-1]===Me&&ne()}})()},Fr=()=>{if(a.length===0){de="no sessions to search",ue();return}$=new Qn({history:[],collapsePastes:!1}),H=[],J=!1,B=0,N=0,st=0,j=null,X=!1,F="input",T=!0,Ns(),tn(),$t({onKey:(W,ie,q)=>{if(F==="input"){if(X)return;if(W==="ESCAPE"||W==="CTRL_C"){Yi();return}if(W==="ENTER"||W==="KP_ENTER"){if($r().trim().length===0)return;sc();return}if((W==="DOWN"||W==="TAB"||W==="CTRL_N")&&H.length>0){F="results",B=0,N=0,De(()=>{Ji(),rs(0,!0),_r(),t.hideCursor()});return}let ne=$.state(),oe=null;if(W==="")oe={type:"key",name:"ctrl-underscore"};else if(W==="\x1B_"||W==="\x1B")oe={type:"key",name:"alt-underscore"};else if(q?.isCharacter)oe={type:"char",ch:W};else{let St=Gd(W);St!==null&&(oe={type:"key",name:St})}if(oe===null){t.moveTo(Ds(),Hs());return}$.feed(oe);let Me=$.state();if(ne.buffer.length===Me.buffer.length&&ne.buffer.every((St,Oe)=>St===Me.buffer[Oe])&&ne.row===Me.row&&ne.col===Me.col){t.moveTo(Ds(),Hs());return}let et=ut;Ns(),ut!==et?tn():_t();return}if(F==="results"){if(W==="ESCAPE"||W==="CTRL_C"){Yi();return}if(W==="CTRL_F"){F="input",Ki(),_r(),Ji();return}if(W==="ENTER"||W==="KP_ENTER"){let oe=H[B];if(!oe)return;let Me=a.find(et=>et.sessionId===oe.sessionId);if(!!Me?.importedFromMachine&&!Me.upstreamSessionId){Ze();let et={kind:"attach",sessionId:oe.sessionId};Me.agentId!==void 0&&(et.agentId=Me.agentId),R(et);return}(async()=>{let et=await yw(t,{sessionId:oe.sessionId,title:oe.title,cwd:oe.cwd},bt);if(et==="cancel"){Ze(),R({kind:"abort"});return}if(et==="back")return;Ze();let St={kind:"attach",sessionId:oe.sessionId,readonly:et==="view"};Me?.agentId!==void 0&&(St.agentId=Me.agentId),R(St)})();return}if(q?.isCharacter&&(W==="n"||W==="N")){let oe=H[B];if(!oe||oe.snippets.length<=1)return;N=(N+1)%oe.snippets.length,rs(B,!0);return}if(q?.isCharacter&&(W==="p"||W==="P")){let oe=H[B];if(!oe||oe.snippets.length<=1)return;N=(N-1+oe.snippets.length)%oe.snippets.length,rs(B,!0);return}let ne=oe=>{if(oe<0&&B===0){F="input",De(()=>{rs(0,!1),_r(),Ji()});return}let Me=Math.min(H.length-1,Math.max(0,B+oe));if(Me===B)return;let He=B,et=st;B=Me,N=0,Ln(),st!==et?Ki():(De(()=>{rs(He,!1),rs(B,!0)}),_r())};switch(W){case"UP":case"SHIFT_TAB":case"CTRL_P":ne(-1);return;case"DOWN":case"TAB":case"CTRL_N":ne(1);return;case"PAGE_UP":ne(-yn());return;case"PAGE_DOWN":ne(yn());return;case"HOME":ne(-B);return;case"END":ne(H.length);return}return}},onResize:()=>tn()})},Js=(E,W,ie)=>{if(S!=="busy"){if(E==="CTRL_O"){bn();return}if(E==="CTRL_L"){Bs();return}if(S==="rename"){if(E==="ENTER"||E==="KP_ENTER"){let q=Y.trim();if(q.length===0){S="normal",x=null,Y="",ue();return}Qi(q);return}if(E==="ESCAPE"||E==="CTRL_C"){S="normal",x=null,Y="",Ct(),ue();return}if(E==="BACKSPACE"){Y.length>0&&(ge(),Y=Y.slice(0,-1),ue());return}if(E==="CTRL_U"){Y.length>0&&(ge(),Y="",ue());return}if(E==="CTRL_W"){let q=Y.replace(/\s+$/,""),ne=q.lastIndexOf(" "),oe=ne>=0?q.slice(0,ne):"";oe!==Y&&(ge(),Y=oe,ue());return}if(E===""){Je(),ue();return}if(E==="\x1B_"||E==="\x1B"){Ms(),ue();return}if(ie?.isCharacter){ge(),Y+=E,ue();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ie?.isCharacter&&(E==="y"||E==="Y")){as(S==="confirm-kill"?"kill":"delete");return}if(E==="ESCAPE"||E==="CTRL_C"||E==="ENTER"||E==="KP_ENTER"||ie?.isCharacter&&(E==="n"||E==="N")){S="normal",x=null,ue();return}return}if(sn(),E==="CTRL_F"){Fr();return}if(u===0&&!m){if(E==="ESCAPE"){Bn();return}if(E==="ENTER"||E==="KP_ENTER"){Ze();let Oe=$e.expandedText(),Wt=Ot();Oe.trim().length>0&&(Wt.prompt=Oe),R(Wt);return}if(E==="UP"&&b){let Oe=Date.now(),Wt=Oe-v;if(v=Oe,Wt<w){Ge();return}b=!1}if(E==="DOWN"){let Oe=$e.state(),Wt=Oe.historyIndex!==-1||Oe.queueIndex!==-1,ic=Qt.length===0||ve===Qt.length-1;if(!Wt&&ic&&a.length>0){ct(1);return}}if(E==="PAGE_DOWN"&&(Qt.length===0||ve===Qt.length-1)&&a.length>0){ct(1);return}if(E==="CTRL_P"){a.length>0&&ct(1);return}b=!1;let q=$e.state(),ne=null;if(E==="")ne={type:"key",name:"ctrl-underscore"};else if(E==="\x1B_"||E==="\x1B")ne={type:"key",name:"alt-underscore"};else if(ie?.isCharacter)ne={type:"char",ch:E};else{let Oe=Gd(E);Oe!==null&&(ne={type:"key",name:Oe})}if(ne===null){Ge();return}let oe=$e.feed(ne),Me=$e.state(),He=q.buffer.length===Me.buffer.length&&q.buffer.every((Oe,Wt)=>Oe===Me.buffer[Wt])&&q.row===Me.row&&q.col===Me.col;if(oe.some(Oe=>Oe.type==="exit")){Bn();return}if(He){Ge();return}let et=Zn(Me.buffer,Gt);if(Es(et,Me,Zd).rendered!==Ut){Qe();return}qt();return}if(!m&&ie?.isCharacter&&E==="?"){Un();return}if(m){if(ie?.isCharacter){h+=E,at(),Qe();return}if(E==="BACKSPACE"){h.length>0?(h=h.slice(0,-1),at(),Qe()):(m=!1,at(),Qe());return}if(E==="ESCAPE"||E==="CTRL_C"){m=!1,h="",at(),Qe();return}}if(ie?.isCharacter){if(E==="/"){m=!0,h="",at(),Qe();return}if(E==="n"||E==="N"){ct(1);return}if(E==="p"||E==="P"){ct(-1);return}if(E==="c"||E==="C"){let q=u>0?a[u-1]:void 0,ne=Ot();q?.cwd&&(ne.cwd=q.cwd),Ze(),R(ne);return}if(E==="q"||E==="Q"){Bn();return}if(E==="o"||E==="O"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,at(),ns(q),Qe();return}if(E==="h"||E==="H"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.hostFilter=BR(s.filters.hostFilter,i),at(),ns(q),Qe();return}if(E==="i"&&u>0){let q=a[u-1];if(!q)return;zs(q);return}if(E==="I"){let q=u>0?a[u-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,at(),ns(q),Qe();return}if(E==="r"||E==="R"){let q=u>0?a[u-1]?.sessionId:void 0;os(q);return}if(E==="s"||E==="S"){Dn();return}if((E==="v"||E==="V")&&u>0){let q=a[u-1];if(!q)return;Ze();let ne={kind:"attach",sessionId:q.sessionId,readonly:!0};q.agentId!==void 0&&(ne.agentId=q.agentId),R(ne);return}if((E==="f"||E==="F")&&u>0){let q=a[u-1];if(!q)return;Ze();let ne={kind:"fork",sourceSessionId:q.sessionId,sourceCwd:q.cwd};q.agentId!==void 0&&(ne.sourceAgentId=q.agentId),q.importedFromMachine!==void 0&&(ne.sourceImportedFromMachine=q.importedFromMachine),q.upstreamSessionId!==void 0&&(ne.sourceUpstreamSessionId=q.upstreamSessionId),R(ne);return}if((E==="k"||E==="K")&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-kill",ue();return}if(E==="t"&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},Y=q.title??"",S="rename",ue();return}if(E==="T"&&u>0){let q=a[u-1];if(!q)return;rt({sessionId:q.sessionId});return}if(E==="*"&&u>0){let q=a[u-1];if(!q)return;Nn(q);return}if((E==="d"||E==="D")&&u>0){let q=a[u-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-delete",ue();return}return}switch(E){case"UP":case"SHIFT_TAB":case"CTRL_P":E==="UP"&&(u===1&&(b=!0),v=Date.now()),ct(-1);return;case"DOWN":case"TAB":case"CTRL_N":ct(1);return;case"PAGE_UP":ct(-Xe);return;case"PAGE_DOWN":ct(Xe);return;case"HOME":ct(1-u);return;case"END":ct(f);return;case"ENTER":case"KP_ENTER":{if(Ze(),u===0){R(Ot());return}let q=a[u-1];if(!q){R({kind:"abort"});return}let ne={kind:"attach",sessionId:q.sessionId};q.agentId!==void 0&&(ne.agentId=q.agentId),R(ne);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Bn();return}}};$t({onKey:(E,W,ie)=>Js(E,W,ie),onResize:()=>{P||Qe()}});let jn=()=>{t.grabInput({});let E=t;E.stdin&&typeof E.onStdin=="function"&&(Rt=E.onStdin,E.stdin.removeListener("data",E.onStdin),E.stdin.on("data",Or),process.stdout.write(Ed)),t.on("key",dt),t.on("resize",vt)},Ks=()=>{process.stdout.write(Yn);let E=t;E.stdin&&Rt&&(E.stdin.removeListener("data",Or),E.stdin.on("data",Rt),Rt=null),nn=!1,is="",t.off("key",dt),t.off("resize",vt),t.grabInput(!1),t.hideCursor(!1)};if(jn(),process.platform!=="win32"){let E=!1,W=()=>{E&&(E=!1,t.fullscreen(!0),n(),t.hideCursor(),jn(),P||Bs())};Gi=()=>{E||P||(E=!0,Ks(),t.fullscreen(!1),process.stdout.write(`${Fo}${Pd}
184
- `),process.once("SIGCONT",W),process.kill(process.pid,"SIGTSTP"))}}L=setInterval(qs,3e3)})}function FR(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+Mo(Ue(t),s)}function ec(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="live",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function LR(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function BR(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function NR(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[Ve(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,Ue(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var Ju,Zd,_R,vw,$R,OR,Sw=K(()=>{"use strict";Sd();pe();xn();Po();La();xu();qu();Wu();zu();Oi();Cu();Mu();Lo();or();ou();Ju=2,Zd=4,_R=4,vw=4,$R=20,OR=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected live session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});function jR(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function kw(t,e,n){Vn();let s=jR(e,n??DR),r=0,i=()=>{let l=wr(t)-8;return Math.max(1,Math.min(HR,e.length,l))},o=()=>{let l=i();s<r?r=s:s>=r+l&&(r=s-l+1);let f=Math.max(0,e.length-l);r>f&&(r=f),r<0&&(r=0)},a=()=>{o();let l=i(),f=l+4,u=Math.min(UR,Math.max(40,fn(t)-8)),p=Gn(t,{contentHeight:f,contentWidth:u,title:"Select agent"}),m=p.contentW,h=0;t.moveTo(p.contentX,p.contentY+h),t.noFormat(" Which agent should this session use?"),h+=2;let w=Math.min(e.length,r+l);for(let v=r;v<w;v++){let S=e[v];if(!S)continue;let x=v===s?"\u276F":" ",T=S.description??S.name,F=` ${x} ${S.id}`;if(t.moveTo(p.contentX,p.contentY+h),v===s){let $=`${F} ${T}`;t.brightWhite.bgBlue.noFormat(_d(nt($,m),m))}else{t.noFormat(F);let $=m-F.length-2;$>1&&t.dim.noFormat(` ${nt(T,$)}`)}h++}h++,t.moveTo(p.contentX,p.contentY+h);let b=e.length>l?` (${s+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${b}`),p},c=()=>{s<e.length-1&&(s++,a())},d=()=>{s>0&&(s--,a())};return Cs({term:t,render:a,onKey:(l,f,u,p)=>{if(l==="CTRL_C"||l==="CTRL_D"){p({kind:"cancel"});return}if(l==="ESCAPE"){p({kind:"back"});return}if(l==="ENTER"||l==="KP_ENTER"){let m=e[s];m&&p({kind:"select",agentId:m.id,persist:!1});return}if(l==="UP"||l==="SHIFT_TAB"){d();return}if(l==="DOWN"||l==="TAB"){c();return}if(u?.isCharacter){let m=l.toLowerCase();if(m==="s"){let h=e[s];h&&p({kind:"select",agentId:h.id,persist:!0});return}if(m==="j"){c();return}if(m==="k"){d();return}}}})}var DR,HR,UR,Iw=K(()=>{"use strict";Oi();DR="opencode",HR=20,UR=88});import*as Cw from"fs";import*as Aw from"os";import*as tc from"path";function Rw(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function qR(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function WR(t){return t.replace(/\\ /g," ")}function xw(t){return t.replace(/ /g,"\\ ")}function zR(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function JR(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=Aw.homedir()+n.slice(1)),tc.isAbsolute(n)?n:tc.resolve(e,n)}function KR(t){let e;try{e=Cw.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Tw(t,e,n=KR){if(!qR(t))return null;let s=WR(t),{dirPrefix:r,base:i}=zR(s),o=JR(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(u=>u.name.startsWith(i)&&(c||!u.name.startsWith(".")));if(d.length===0)return null;let l=d.map(u=>u.isDir?u.name+"/":u.name);if(d.length===1){let u=d[0],p=u.isDir?u.name+"/":u.name;return{replacement:xw(r+p),candidates:l}}let f=Jo(d.map(u=>u.name));return{replacement:xw(r+f),candidates:l}}var Ew=K(()=>{"use strict";Xd()});function Pw(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Mw(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function _w(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var $w=K(()=>{"use strict"});import{appendFileSync as YR,readFileSync as VR,statSync as GR,renameSync as QR}from"fs";import{nanoid as Ow}from"nanoid";import XR from"terminal-kit";import Vu from"fs/promises";import Ir from"path";function Fw(t){if(!Array.isArray(t))return;let e=Rn({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function Lw(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function t0(t,e){e.has(t)?e.delete(t):e.add(t)}async function Dw(t){let e=await ye(),n=t.target??await Et(e);jw=e.tui.logMaxBytes,n.isLocal&&!t.target&&await vs(e);let s=XR.terminal;mw(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:hf(e),defaultEnterAction:e.tui.defaultEnterAction},o=Ku(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
185
- `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let f=t;try{for(;f!==null;)f=await s0(s,e,n,f,r,i,o)}finally{d(),process.off("exit",l)}let u=await No();if(u&&process.stderr.write(`\u2728 ${Do(u)}
186
- `),process.stdout.isTTY){let p=await cr(e);if(p?.version!==void 0){let m=p.version!==fe,h=gs(e),w=p.configDigest!==void 0&&p.configDigest!==h;if(m||w){let b=m?`daemon ${p.version} \u2260 cli ${fe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${vn()} daemon restart\` to apply.`)+`
187
- `)}}}if(r.sessionId&&process.stdout.isTTY){let p=Ve(r.sessionId),m=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${vn()} --session ${p}${m}
188
- `)}}function n0(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let J=Math.max(0,c-a),B=e.slice(J),N=[];for(let j=0;j<J;j++){let X=e[j];if(X===void 0)continue;let Y=n.get(X);Y&&!eu(Y.status)&&N.push(X)}l=[...N,...B]}let f=c-l.length,u=r===null,p=r??Date.now(),m=p-s,h=!u&&i!==null&&i!=="end_turn"?i:null,w=h==="amended",b=w?`amended \xB7 ${Mn(m)}`:`stopped (${h}) \xB7 ${Mn(m)}`,v;if(c===0)h!==null?v=b:v=u?`thinking \xB7 ${Mn(m)}`:`thought \xB7 ${Mn(m)}`;else{let J=c===1?"tool":"tools",B=h!==null?b:u?Mn(m):`took ${Mn(m)}`,N=[`${c} ${J}`,B];u&&d&&f>0&&N.push(`${f} hidden`),v=N.join(" \xB7 ")}let S=c===0&&u,x=w?"tool-status-cancelled":"tool-status-fail",$=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":h!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":h!==null?x:"dim"}],H=[null];for(let J of l){let B=n.get(J);if(B){let N=$o(B,p);if($.push(...N),H.push(...N.map(()=>J)),o?.has(J)){let j=cg(B);$.push(...j),H.push(...j.map(()=>J))}}}return{lines:$,rowOwners:H}}async function s0(t,e,n,s,r,i,o){let a=await r0(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",d=a0(t,c);d.write(c);let l=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,f=["acp.v1",`hydra-acp-token.${n.token}`],u=null,p=null,m=new Fi({url:l,subprotocols:f,onConnect:async g=>{g||u&&await u()},onDisconnect:g=>{p&&p(g)},log:()=>{}}),h=new Pt(m);await m.start(),h.onNotification(ka,g=>{let y=vp.safeParse(g);y.success&&d.applyProgress(y.data)});let w=[],b=null,v=!1,S=!1,x=(g,y)=>{g&&(b?b(g,y):w.push({event:g,rawUpdate:y}))},T,F=g=>{g!==T&&(T=g,g!==void 0&&k.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},$=null,H=null,J=!1,B=0,N=0,j=!1,X=!1,Y,be=null,V=null,ge=null,Je=()=>setInterval(()=>{if(be===null||de===null)return;let g=ge===null?0:Date.now()-ge;de.setBanner({elapsedMs:Date.now()-be,stalled:g>=ZR}),rn()},1e3),Ms=!1,Ct=g=>{let y=N;N=Math.max(0,N+g);let I=typeof de<"u"&&de!==null;y===0&&N>0?(X=!1,be=Date.now(),ge=Date.now(),ee?.setTurnRunning(!0),I&&de.setBanner({status:"busy",elapsedMs:0,stalled:!1}),V===null&&I&&(V=Je())):y>0&&N===0?(X=!1,be=null,ge=null,ee?.setTurnRunning(!1),V!==null&&(clearInterval(V),V=null),I&&de.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):N>0&&X&&(X=!1,I&&de.setBanner({status:"busy",stalled:!1}))},de=null,ee=null,$e,pn=null,Ce=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]),$n=g=>{let{update:y}=g??{},I=Rn(y,{cwd:gt});i0(y,I),ge=Date.now();let C=y?.sessionUpdate;if(typeof C=="string"&&!Ce.has(C)){let A=y??{};typeof A.messageId=="string"&&($e=A.messageId)}if(C==="prompt_received"?Ct(1):I?.kind==="turn-complete"&&(Ct(-1),J=!0),C==="permission_resolved"){es(y);return}if(C==="hydra_compaction"){Ut(y);return}x(I,y),Ar(y)};h.onNotification("session/update",g=>{if(!v){if(pn!==null){pn.push(g);return}$n(g)}}),h.onNotification("hydra-acp/session/closed",()=>{if(v)return;N>0&&Ct(-N),typeof de<"u"&&de!==null&&de.setBanner({status:"cold",elapsedMs:void 0})});let Ke=new Map,Xe=200,xr=0,Gt=!1,Qt=4e3;h.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;if(typeof y._meta?.["hydra-acp"]?.amending=="string"){let C=y.messageId,A=y.prompt,M=setTimeout(()=>{v||(Ke.delete(C),bt.set(C,Tt(C,A)),de&&ee&&Ze())},Xe);Ke.set(C,M)}else bt.set(y.messageId,Tt(y.messageId,y.prompt)),de&&ee&&Ze();if(at!==void 0&&y.originator?.clientId===at){let C=Ot.shift();C&&(C.messageId=y.messageId,bn.set(y.messageId,C))}}),h.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string"||!bt.has(y.messageId))return;bt.set(y.messageId,Tt(y.messageId,y.prompt));let I=bn.get(y.messageId);if(I){let C=Array.isArray(y.prompt)?y.prompt:[],A="",M=[];for(let U of C){if(!U||typeof U!="object")continue;let O=U;O.type==="text"&&typeof O.text=="string"?A+=O.text:O.type==="image"&&typeof O.data=="string"&&typeof O.mimeType=="string"&&M.push({data:O.data,mimeType:O.mimeType,sizeBytes:Math.floor(O.data.length*3/4)})}I.text=A,I.attachments=M}de&&ee&&Ze()}),h.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let y=g??{};if(typeof y.messageId!="string")return;y.reason==="started"&&(Y=y.messageId);let I=Ke.get(y.messageId);I!==void 0&&(clearTimeout(I),Ke.delete(y.messageId)),bt.delete(y.messageId)&&de&&ee&&Ze();let A=bn.get(y.messageId);A&&(bn.delete(y.messageId),y.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),vt=A))}),h.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let y=g??{};if(!(typeof de<"u"&&de!==null))return;xr=Date.now(),Gt=!0;let C=typeof y.code=="number"?` (${y.code})`:"",A=typeof y.message=="string"&&y.message.length>0?`: ${y.message}`:"";de.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let y=g??{};if(typeof y.cancelledMessageId!="string")return;let I=y.cancelledMessageId;dt.add(I),vt!==null&&vt.messageId!==void 0&&vt.messageId===I&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),vt=null,dt.delete(I))});let Ut=g=>{let y=g??{},I=typeof y.phase=="string"?y.phase:void 0;if(I==="started")k.setCompactionIndicator("compacting...");else if(I==="iteration")k.setCompactionIndicator("compacting...");else if(I==="deferred")k.setCompactionIndicator("compaction queued (waiting for idle)");else if(I==="swapped")k.setCompactionIndicator(null),k.notify("compacted",2e3);else if(I==="rolled_back")k.setCompactionIndicator(null),k.notify("rolled back",2e3);else if(I==="failed"){k.setCompactionIndicator(null);let C=typeof y.error=="string"?y.error:"unknown error",A=C.length>40?C.slice(0,40)+"...":C;k.notify(`compaction failed: ${A}`,5e3)}},es=g=>{let y=g??{},I=typeof y.toolCallId=="string"?y.toolCallId:void 0,C;y.outcome&&typeof y.outcome=="object"?C=y.outcome:typeof y.chosenOptionId=="string"&&(C={kind:"selected",optionId:y.chosenOptionId}),Cr(I,C?{outcome:C}:void 0)},ve=null,Cr=(g,y)=>{if(!ve||ve.toolCallId&&g&&ve.toolCallId!==g)return;let I=ve.resolve;ve=null,k.setPermissionPrompt(null),I(y??{outcome:{outcome:"cancelled"}})},Ar=g=>{if(!ve?.toolCallId)return;let y=g??{};y.sessionUpdate!=="tool_call"&&y.sessionUpdate!=="tool_call_update"||y.toolCallId===ve.toolCallId&&(!y.status||y.status==="pending"||Cr(y.toolCallId,void 0))},_s=()=>{if(!ve){k.setPermissionPrompt(null);return}k.setPermissionPrompt({title:ve.title,detail:ve.detail,options:ve.options.map(g=>({label:g.name})),selectedIndex:ve.selectedIndex})},mn=g=>{if(!ve)return;let{options:y,resolve:I}=ve;if(ve=null,k.setPermissionPrompt(null),g===null){I({outcome:{outcome:"cancelled"}});return}I({outcome:{outcome:"selected",optionId:g}})};h.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return br(g);let y=g??{},C=(Array.isArray(y.options)?y.options:[]).map(G=>({optionId:G.optionId,name:Ie(G.name??""),...G.kind!==void 0?{kind:G.kind}:{}})),A=y.toolCall?.title??y.toolCall?.name??"tool",M=Ie(A),U=Ie(hy(my(g))),O=y.toolCall?.toolCallId;return C.length===0?(k.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${M} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(G=>{ve={title:M,detail:U,options:C,selectedIndex:0,resolve:G,toolCallId:O},_s()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let $s,Rr,ut=!0,ts=!1;try{let g=await h.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}});Rr=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ut=!1),ts=Bt(g?._meta??void 0).prompt?.amending===!0}catch{}let Pe=a.sessionId,Xt=a.agentId,gt=a.cwd,Ui,at,ns,Zt,hn,Tr,Er,ss,Os,jt,ji=!1;if(a.sessionId==="__new__"){let g={};s.agentId&&(g.agentId=s.agentId),s.name&&(g.title=s.name),s.model&&(g.model=s.model);let y={cwd:a.cwd,...Object.keys(g).length>0?{_meta:{[mt]:g}}:{}},I=await iy({request:()=>h.request("session/new",y),showBanner:(M,U,O)=>oy(t,M,U,O,{authenticate:G=>h.request("authenticate",{methodId:G})}),resolveOnboarding:async M=>{if(M)try{return(await Wl(n)).find(G=>G.id===M)?.onboarding}catch{return}},fallbackAgentId:s.agentId});if(I.kind==="cancel")return t.grabInput(!1),m.close().catch(()=>{}),null;if(I.kind==="back"){t.grabInput(!1),m.close().catch(()=>{});let M={...s};return delete M.sessionId,delete M.forceNew,delete M.resume,delete M.agentId,M}let C=I.result;d.write(c),Pe=C.sessionId,r.sessionId=Pe,r.readonly=!1;let A=Bt(C._meta??void 0);A.clientId&&(at=A.clientId),$s=A.upstreamSessionId,A.agentId&&(Xt=A.agentId),A.cwd&&(gt=A.cwd),A.title&&(Ui=A.title),ns=A.currentModel,Zt=A.currentMode,Os=A.currentUsage,jt=A.turnStartedAt,A.availableCommands&&(hn=Xa(A.availableCommands)),A.availableModes&&(Tr=A.availableModes),Er=Fw(C.configOptions),ss=A.queue}else{let g={};s.readonly===!0&&(g.readonly=!0),e.tui.toolContent==="references"&&(g.toolContent="references"),s.drip===!0&&(g.replayMode="drip",s.dripSpeed!==void 0&&(g.dripSpeed=s.dripSpeed)),a.resumeHint!==void 0&&(g.resume={upstreamSessionId:a.resumeHint.upstreamSessionId,agentId:a.resumeHint.agentId,cwd:a.resumeHint.cwd});let y=await h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:fe},...Object.keys(g).length>0?{_meta:{[mt]:g}}:{}});Pe=y.sessionId,y.clientId&&(at=y.clientId),r.sessionId=Pe,r.readonly=s.readonly===!0;let I=Bt(y._meta??void 0);ji=I.resurrected===!0,$s=I.upstreamSessionId,I.agentId&&(Xt=I.agentId),I.cwd&&(gt=I.cwd),I.title&&(Ui=I.title),ns=I.currentModel,Zt=I.currentMode,Os=I.currentUsage,jt=I.turnStartedAt,I.availableCommands&&(hn=Xa(I.availableCommands)),I.availableModes&&(Tr=I.availableModes),Er=Fw(y.configOptions),ss=I.queue}let gn=_.tuiHistoryFile(Pe),Ko=_.globalTuiHistoryFile(),ue=await ho(gn).catch(()=>[]),yt=await ho(Ko).catch(()=>[]);yt.length>e.tui.promptHistoryMaxEntries&&(yt=yt.slice(yt.length-e.tui.promptHistoryMaxEntries));let en=[...ue],me=new Qn({history:Fa(yt,en)});ee=me;let Yo=!1,On=(g,y)=>{let I=g.replace(/\n+$/,"");if(I.length===0)return;let C=(y??g).replace(/\n+$/,""),A=go(ue,I),M=A!==ue;ue=A,en=go(en,C);let U=go(yt,I,e.tui.promptHistoryMaxEntries),O=U!==yt;yt=U,me.setHistory(Fa(yt,en)),M&&ir(gn,ue).catch(()=>{}),O&&gm(Ko,I).catch(()=>{})};N>0&&me.setTurnRunning(!0);let Ge=null,Fs=null;uw(fw(e.tui.ambiguousWidth,process.env)),ug(e.tui.diffContextLines);let Ls=!1,k,qi=()=>{Ls&&(Ls=!1,k.start())},Pr=()=>{Ls||(Ls=!0,k.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",qi),k=new Vd({term:t,dispatcher:me,repaintThrottleMs:e.tui.repaintThrottleMs,maxScrollbackLines:e.tui.maxScrollbackLines,mouse:i.mouseEnabled,inAppSelection:i.inAppSelectionEnabled,selectionClipboard:e.tui.selectionClipboard,openFileCommand:e.tui.openFileCommand,progressIndicator:e.tui.progressIndicator,readonly:s.readonly===!0,onSuspend:process.platform!=="win32"?Pr:void 0,onBlockClick:(g,y)=>{ub(g,y)},onBlockDoubleClick:(g,y)=>lb(g,y),onBlockVisible:g=>{ab(g)},onMouse:g=>{if(g.kind!=="press"||g.button!=="middle")return;let y={type:"attachment-request",source:"primary"};s.readonly===!0&&Lw(y)||re(y)},onKey:g=>{for(let y of g){if(j&&sc(y)||ve&&Hs(y)||Yi(y)||Zo(y)||Ds(y)||Ns(y)||Vo(y))continue;if(y.type==="key"&&y.name==="escape"&&k.isScrolledBack()){k.scrollToBottom();continue}if(y.type==="attachment-paths"){Ye(y.paths);continue}let I=me.feed(y);for(let C of I)s.readonly===!0&&Lw(C)||re(C)}Wi(),k.setBannerSearchIndicator(me.state().historySearchQuery),k.setAttachments(me.state().attachments),k.refreshPrompt()}}),de=k,k.setStickyBottomKey("plan");let Qe=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt>"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],Bs=hn??[],Fn=Tr??[],At=Er??[],nc=()=>At.find(g=>g.id==="agent"),st=()=>{let g=new Set,y=[];for(let I of[...Qe,...Bs])g.has(I.name)||(g.add(I.name),y.push(I));return y},yn=()=>{let g=me.state().buffer,y=g[0]??"";if(!y.startsWith("/"))return[];if(g.length>1)return[];let I=y.indexOf(" "),C=I===-1?y:y.slice(0,I);if(C.lastIndexOf("/")>0)return[];let A=st().filter(M=>M.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Ln=[],Wi=()=>{let g=yn();if(g.length>0){Ln=[],k.setCompletions(g);return}k.setCompletions(Ln)},Ns=g=>{if(g.type!=="key"||g.name!=="tab")return Ln.length>0&&(Ln=[]),!1;let y=yn();if(k.isOverlayOpen()&&y.length===0)return k.toggleFocusedPane(),!0;if(y.length>0){Ln=[];let I=me.state().buffer[0]??"",C=ww({matches:y.map(A=>A.name),firstLine:I});return C===null||me.replaceFirstLine(C),!0}return zi()},zi=()=>{let g=me.state(),y=g.buffer[g.row]??"",I=Rw(y,g.col);if(I===null)return!1;let C=Tw(I.token,gt);return C===null?!1:(C.replacement!==I.token&&me.replaceRangeOnCurrentLine(I.start,g.col,C.replacement),Ln=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},Vo=g=>!k.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:($&&($.cancel(),$=null,H=null),k.closeBtwOverlay(),!0),Ds=g=>{if(!k.isScrollbackSearchActive())return g.type==="key"&&g.name==="ctrl-r"&&k.isScrolledBack()?(k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(""),!0):!1;if(g.type==="char"){let y=k.scrollbackSearchTerm()+g.ch;return k.updateScrollbackSearchTerm(y),!0}if(g.type==="paste"){let y=k.scrollbackSearchTerm()+g.text.replace(/\n/g," ");return k.updateScrollbackSearchTerm(y),!0}if(g.type==="key")switch(g.name){case"ctrl-r":return k.advanceScrollbackSearch(),!0;case"ctrl-s":return k.retreatScrollbackSearch(),!0;case"backspace":{let y=k.scrollbackSearchTerm();return y.length===0?k.cancelScrollbackSearch():k.updateScrollbackSearchTerm(y.slice(0,-1)),!0}case"enter":return k.acceptScrollbackSearch(),!0;case"escape":case"ctrl-c":return k.cancelScrollbackSearch(),!0;default:return!0}return!0},Hs=g=>{if(!ve)return!1;let y=ve.options;if(g.type==="key")switch(g.name){case"up":return ve.selectedIndex=Math.max(0,ve.selectedIndex-1),_s(),!0;case"down":return ve.selectedIndex=Math.min(y.length-1,ve.selectedIndex+1),_s(),!0;case"enter":{let I=y[ve.selectedIndex];return I&&mn(I.optionId),!0}case"escape":case"ctrl-c":return mn(null),!0;default:return!0}if(g.type==="char"&&/^[1-9]$/.test(g.ch)){let I=parseInt(g.ch,10)-1,C=y[I];return C&&mn(C.optionId),!0}return!0},Ji=Xt||Rr||"?",_t={...Os??{}};d.finalize(),k.start({skipFullscreen:!0}),k.setHideThoughts(!i.showThoughts),k.setSessionbar({agent:Ji,cwd:gt,sessionId:Pe,title:Ui,model:ns,usage:{..._t}}),Zt&&k.setBanner({currentMode:Zt}),No().then(g=>{g&&k.notify(`\u2728 ${Do(g)}`,3e4)}).catch(()=>{});let wt=null,Go=new Promise(g=>{wt=g}),Mr=()=>{h.notify("session/cancel",{sessionId:Pe}).catch(()=>{})},Us=()=>{de!==null&&N===1&&(X=!0,de.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},wn=()=>{if(Ge){Ge.cancel(),Us();return}if(N>0){Mr(),Us();return}tn()},tn=()=>{R(0)},rs=()=>{let g="enqueue prompt (sends now, or queues during a turn)",y="amend the in-flight turn (cancel + replace)";return[...i.defaultEnterAction==="amend"?[["Enter",y],["Ctrl+Enter / Shift+Enter / ^S",g]]:[["Enter",g],["Ctrl+Enter / Shift+Enter / ^S",y]],...e0]},_r=()=>{if(k.isHelpPromptActive()){k.setHelpPrompt(null);return}k.setHelpPrompt({title:"Hotkeys",entries:rs(),hint:"any key dismisses \xB7 /help lists commands"})},Ki=()=>{j=!1,k.setCompactionPrompt(null),k.setCompactionIndicator("compaction queued...");let g=Pe;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},$r=()=>{j=!1,k.setCompactionPrompt(null)},Qo=g=>{let y=k.compactionPromptSpec();if(!y)return;let I=y.options.length;if(I===0)return;let C=((y.selectedIndex+g)%I+I)%I;C!==y.selectedIndex&&k.setCompactionPrompt({...y,selectedIndex:C})},sc=g=>{if(!j)return!1;if(g.type==="key"){if(g.name==="escape")return $r(),!0;if(g.name==="up")return Qo(-1),!0;if(g.name==="down")return Qo(1),!0;if(g.name==="enter"){let y=k.compactionPromptSpec();return y?.options[y.selectedIndex]?.key==="y"?Ki():$r(),!0}}if(g.type==="char"){let y=g.ch.toLowerCase();if(y==="y"||y==="1")return Ki(),!0;if(y==="n"||y==="2")return $r(),!0}return!0},Yi=g=>k.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",k.setHelpPrompt(null),!0):!1,js=["tools","plan","thoughts","diffs","mouse","enter"],qt=0,rc=g=>{switch(g){case"tools":return i.toolsExpanded?"expanded":"collapsed";case"plan":return i.planExpanded?"expanded":"collapsed";case"thoughts":return i.showThoughts?"shown":"hidden";case"diffs":return i.showFileUpdates;case"mouse":return i.mouseEnabled?"on":"off";case"enter":return i.defaultEnterAction}},Vi=g=>{switch(g){case"tools":return"Tools";case"plan":return"Plan";case"thoughts":return"Thoughts";case"diffs":return"File updates";case"mouse":return"Mouse capture";case"enter":return"Enter key"}},Xo=()=>({title:"Session options",options:js.map(g=>({label:Vi(g),value:rc(g)})),selectedIndex:qt}),nn=()=>{k.isOptionsPromptActive()&&k.setOptionsPrompt(Xo())},is=()=>{if(k.isOptionsPromptActive()){k.setOptionsPrompt(null);return}qt=0,k.setOptionsPrompt(Xo())},Rt=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,zs.clear(),Fr.clear(),sb();break;case"plan":i.planExpanded=!i.planExpanded,ne=null,et();break;case"thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Dn.clear(),db();break;case"mouse":{let y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}nn()},Gi=g=>{(async()=>{try{switch(g){case"tools":case"plan":k.notify(`${Vi(g)} is session-only \u2014 not saved`);return;case"thoughts":await Zi("showThoughts",i.showThoughts);break;case"diffs":await Zi("showFileUpdates",i.showFileUpdates);break;case"mouse":await Zi("mouse",i.mouseEnabled);break;case"enter":await Zi("defaultEnterAction",i.defaultEnterAction);break}k.notify(`saved default: ${Vi(g)} ${rc(g)}`)}catch(y){k.notify(`save failed: ${y instanceof Error?y.message:String(y)}`)}})()},Zo=g=>{if(!k.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return qt=Math.max(0,qt-1),nn(),!0;case"down":return qt=Math.min(js.length-1,qt+1),nn(),!0;case"enter":{let y=js[qt];return y&&Rt(y),!0}case"ctrl-o":case"escape":case"ctrl-c":return k.setOptionsPrompt(null),!0;case"ctrl-d":return k.setOptionsPrompt(null),!1;default:return!0}if(g.type==="char"){if(/^[1-9]$/.test(g.ch)){let y=parseInt(g.ch,10)-1,I=js[y];return I&&(qt=y,Rt(I)),!0}if(g.ch==="s"||g.ch==="S"){let y=js[qt];return y&&Gi(y),!0}}return!0},Or=()=>{v=!0,$?($.cancel(),$=null,H=null):H!==null&&(Pn(n,H).catch(()=>{}),H=null),process.off("SIGINT",wn),process.platform!=="win32"&&process.off("SIGCONT",qi),V!==null&&(clearInterval(V),V=null);for(let g of Ke.values())clearTimeout(g);Ke.clear(),k.clearWindowTitle(),k.stop({keepFullscreen:!0}),ir(gn,ue).catch(()=>{}),m.close().catch(()=>{})},R=(g=0)=>{Or(),wt&&(wt(null),wt=null),g!==0&&process.exit(g)},P=async()=>{if(!wt)return;$?($.cancel(),$=null,H=null):H!==null&&(Pn(n,H).catch(()=>{}),H=null);let g=me.state().buffer.join(`
189
- `);g.replace(/\s+$/,"").length>0&&On(g),k.pauseRepaint(),k.stop({keepFullscreen:!0}),ir(gn,ue).catch(()=>{});let y=null,I=null;for(;y===null;){let U=await En(n,{includeNonInteractive:!0}),O=await Yu(t,{cwd:gt,sessions:U,config:e,target:n,currentSessionId:Pe,prefs:o});if(O.kind==="abort"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(O.kind==="exit"){R(0);return}if(O.kind==="new"){y={choice:O,sessions:U};break}if(O.kind==="fork"){let le=await Uw(t,n,O,U);if(le.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(le.kind==="back")continue;y={choice:{kind:"attach",sessionId:le.ctx.sessionId,...le.ctx.agentId?{agentId:le.ctx.agentId}:{}},sessions:U},I={readonly:!1,cwd:le.ctx.cwd},le.ctx.resumeHint!==void 0&&(I.resumeHint=le.ctx.resumeHint);break}let G=U.find(le=>le.sessionId===O.sessionId);if(!(G!==void 0&&!!G.importedFromMachine&&!G.upstreamSessionId&&O.readonly!==!0)){if(n.isLocal&&G&&!G.importedFromMachine&&O.readonly!==!0&&!(await Uo(G.cwd)).ok){let _e=await kr(t,G,{defaultCwd:je(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(_e.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}if(_e.kind==="back")continue;y={choice:O,sessions:U},I={readonly:!1,cwd:_e.path,resumeHint:{agentId:O.agentId??G.agentId??"",cwd:_e.path,upstreamSessionId:""}};break}y={choice:O,sessions:U};break}let Ae={...s,readonly:!1},ce=await Hw(t,G,O,Ae);if(ce.kind==="cancel"){k.start({skipFullscreen:!0}),k.resumeRepaint();return}ce.kind!=="back"&&(y={choice:O,sessions:U},I={readonly:Ae.readonly===!0,cwd:ce.ctx.cwd},ce.ctx.resumeHint!==void 0&&(I.resumeHint=ce.ctx.resumeHint))}let{choice:C}=y,A=wt;if(wt=null,process.off("SIGINT",wn),m.close().catch(()=>{}),C.kind==="new"){let{sessionId:U,...O}=s,G={...O,cwd:C.cwd??gt,forceNew:!0,readonly:!1};C.prompt!==void 0&&(G.initialPrompt=C.prompt),A(G);return}if(C.kind!=="attach")return;let M={...s,sessionId:C.sessionId,cwd:I?.cwd??gt,readonly:I?.readonly??C.readonly===!0};C.agentId!==void 0&&(M.agentId=C.agentId),I?.resumeHint!==void 0?M.resumeHint=I.resumeHint:delete M.resumeHint,A(M)},L=async(g="next")=>{if(!wt)return;let I=(await En(n)).filter(Ae=>Ae.status==="live");if(I.length<=1)return;let C=I.findIndex(Ae=>Ae.sessionId===Pe),U=((C===-1?0:C)+(g==="prev"?-1:1)+I.length)%I.length,O=I[U],G=wt;wt=null,process.off("SIGINT",wn),m.close().catch(()=>{});let Fe={...s,sessionId:O.sessionId,cwd:gt,readonly:!1};O.agentId!==void 0&&(Fe.agentId=O.agentId),G(Fe)},Z=async g=>{if(!wt)return;let y=await En(n,{includeNonInteractive:!0}),I=g.trim();if(!I){k.notify("usage: /session <id|next|prev>");return}let C=I.startsWith(Jt)?[I]:[I,Jt+I],A=y.find(O=>C.includes(O.sessionId));if(!A){let O=y.filter(G=>C.some(Fe=>G.sessionId.startsWith(Fe)));if(O.length===1)A=O[0];else if(O.length>1){k.notify(`ambiguous session id: ${I} (${O.length} matches)`);return}}if(!A){k.notify(`no session matches: ${I}`);return}if(A.sessionId===Pe){k.notify("already on that session");return}let M=wt;wt=null,process.off("SIGINT",wn),m.close().catch(()=>{});let U={...s,sessionId:A.sessionId,cwd:A.cwd??gt,readonly:A.status!=="live"};A.agentId!==void 0&&(U.agentId=A.agentId),delete U.resumeHint,M(U)},re=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?Bn(g.text,g.attachments,g.displayText):Ws(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?Ws(g.text,g.attachments,g.displayText):Bn(g.text,g.attachments,g.displayText);return;case"queue-edit":{let y=qs(g.index);if(!y)return;let I=[];g.text.length>0&&I.push({type:"text",text:g.text});for(let C of g.attachments)I.push({type:"image",data:C.data,mimeType:C.mimeType});h.request("hydra-acp/prompt/update",{sessionId:Pe,messageId:y,prompt:I}).then(C=>{let A=C;!A.updated&&A.reason!=="ok"&&k.notify(`queue edit skipped (${A.reason})`)}).catch(C=>{k.notify(`queue edit failed: ${C.message}`)});return}case"queue-remove":{let y=qs(g.index);if(!y)return;h.request("hydra-acp/prompt/cancel",{sessionId:Pe,messageId:y}).then(I=>{let C=I;!C.cancelled&&C.reason!=="ok"&&k.notify(`queue cancel skipped (${C.reason})`)}).catch(I=>{k.notify(`queue cancel failed: ${I.message}`)});return}case"cancel":{if(k.isOverlayOpen()){$&&($.cancel(),$=null,H=null),k.closeBtwOverlay();return}if(g.prefill&&Ge){let y=bt.size===0,I=me.state().buffer.every(C=>C==="");y&&I&&(Fs={text:Ge.text,attachments:Ge.attachments})}Ge?Ge.cancel():N>0&&Mr(),Us();return}case"exit":tn();return;case"plan-toggle":ea(g.on);return;case"redraw-banner":k.setBanner({});return;case"redraw":k.fullRedraw();return;case"scroll-to-top":k.scrollToTop();return;case"scroll-to-bottom":k.scrollToBottom();return;case"switch-session":P().catch(()=>{});return;case"next-live-session":L().catch(()=>{});return;case"toggle-options":is();return;case"toggle-thoughts":i.showThoughts=!i.showThoughts,k.setHideThoughts(!i.showThoughts),k.notify(i.showThoughts?"thoughts shown":"thoughts hidden");return;case"toggle-mouse":{let y=!k.isMouseEnabled();k.setMouseEnabled(y),i.mouseEnabled=y,k.notify(y?"mouse capture on \u2014 wheel scrolls; shift+drag to select text":"mouse capture off \u2014 click-drag selects text; PgUp/PgDn scrolls");return}case"show-help":_r();return;case"escalate-search":k.enterScrollbackSearch(),k.updateScrollbackSearchTerm(g.query);return;case"attachment-request":Se(g.source);return}},Ye=async g=>{if(!ut){k.notify("agent does not accept image attachments");return}let y=0;for(let I of g){if(I.startsWith("data:")){let A=Au(I);if(!A){k.notify("unsupported data: URI");continue}if(A.sizeBytes>_n){k.notify(`image too large (${Vt(A.sizeBytes)}, max ${Vt(_n)})`);continue}me.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),y++;continue}let C=jo(I);if(!C){k.notify(`unsupported image type: ${Ir.basename(I)}`);continue}try{let A=await Vu.readFile(I);if(A.length>_n){k.notify(`image too large (${Vt(A.length)}, max ${Vt(_n)})`);continue}me.addAttachment({mimeType:C,data:A.toString("base64"),name:Ir.basename(I),sizeBytes:A.length}),y++}catch(A){k.notify(`cannot read ${Ir.basename(I)}: ${A.message}`)}}y>0&&(k.setAttachments(me.state().attachments),k.refreshPrompt())},Se=async(g="clipboard")=>{let y=g==="primary"?await Vy():await Yy();if(!y.ok){k.notify(y.reason);return}if(y.kind==="image"){if(!ut){k.notify("agent does not accept image attachments");return}me.addAttachment(y.attachment),k.setAttachments(me.state().attachments),k.refreshPrompt();return}let I=me.feed({type:"paste",text:y.text});for(let C of I)re(C);k.refreshPrompt()},$t=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,Tt=(g,y)=>{let I=Array.isArray(y)?y:[],C="",A=0;for(let M of I){if(!M||typeof M!="object")continue;let U=M;U.type==="text"&&typeof U.text=="string"?C+=U.text:U.type==="image"&&(A+=1)}return{messageId:g,text:Ie(C),attachmentCount:A}},bt=new Map,Ot=[],bn=new Map,dt=new Set,vt=null,Ze=()=>{let g=[...bt.values()],y=g.map($t);k.setQueuedPrompts(y),k.setBanner({queued:g.length}),me.setQueue(g.map(I=>I.text))},qs=g=>[...bt.values()][g]?.messageId;if(ss&&ss.length>0){for(let g of ss){if(g.position===0){Y=g.messageId;continue}bt.set(g.messageId,Tt(g.messageId,g.prompt))}bt.size>0&&Ze()}let Ws=(g,y,I)=>{k.scrollToBottom(),!os(g)&&(On(g,I),Qi(g,y,I))},Bn=(g,y,I)=>{if(k.scrollToBottom(),os(g))return;if(On(g,I),!ts||Y===void 0){Qi(g,y,I);return}let C=Y,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of y)A.push({type:"image",data:O.data,mimeType:O.mimeType});let M={text:g,displayText:I??g,attachments:y,flushed:!1};Ot.push(M);let U=()=>{let O=Ot.indexOf(M);O>=0&&Ot.splice(O,1),M.messageId!==void 0&&bn.delete(M.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Pe,targetMessageId:C,prompt:A}).then(O=>{let G=O;if(G.amended&&G.reason==="ok"){Ct(1);return}if(U(),G.reason==="target_completed"){k.notify("previous response finished \u2014 press Enter to send as a new turn"),me.setBuffer(g,y),k.refreshPrompt();return}if(G.reason==="target_cancelled"){k.notify("amend skipped \u2014 previous turn was cancelled"),me.setBuffer(g,y),k.refreshPrompt();return}if(G.reason==="target_not_found"){k.notify("amend skipped \u2014 no matching prompt"),me.setBuffer(g,y),k.refreshPrompt();return}}).catch(O=>{U(),k.notify(`amend failed: ${O.message}`),me.setBuffer(g,y),k.refreshPrompt()})},ea=async g=>{if(Fn.length===0){k.notify("no modes advertised by agent");return}let y=k.currentModeId(),I=Fn.findIndex(M=>M.id===y),C=I===-1?0:(I+1)%Fn.length,A=Fn[C]?.id;if(A){k.setBanner({currentMode:A});try{await h.request("session/set_mode",{sessionId:Pe,modeId:A})}catch(M){k.notify(`set_mode failed: ${M.message}`)}}},os=g=>{let y=g.replace(/\s+$/,"");if(!y.startsWith("/")||y.includes(`
190
- `))return!1;let I=y.indexOf(" ");switch(I===-1?y:y.slice(0,I)){case"/quit":case"/exit":return tn(),!0;case"/clear":return rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null,Nn.clear(),Dn.clear(),Un.clear(),zs.clear(),jn.clear(),Ks.clear(),k.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let M of Qe)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"});if(Bs.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let M of Bs)A.push({prefix:" ",body:` ${M.name.padEnd(12)} ${M.description??""}`,bodyStyle:"info"})}return k.appendLines(A),!0}case"/agent":{let A=I===-1?"":y.slice(I+1).trim(),M=nc();if(!M)return k.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let U=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of M.options){let G=O.value===M.currentValue?"* ":" ";U.push({prefix:" ",body:`${G}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return k.appendLines(U),!0}return M.options.some(U=>U.value===A)?A===M.currentValue?(k.notify(`already on agent ${A}`),!0):(k.notify(`switching to ${A}\u2026`),h.request("session/set_config_option",{sessionId:Pe,configId:"agent",value:A}).catch(U=>{k.notify(`set_config_option failed: ${U.message}`)}),!0):(k.notify(`unknown agent: ${A}`),!0)}case"/sessions":return k.appendLines([{prefix:" ",body:"Run `hydra-acp sessions` (or `hydra sessions`) for the full list.",bodyStyle:"info"}]),!0;case"/resume":return P().catch(()=>{}),!0;case"/session":{let A=I===-1?"":y.slice(I+1).trim();return A?A==="next"||A==="prev"?(L(A).catch(M=>{k.notify(`session ${A} failed: ${M.message}`)}),!0):(Z(A).catch(M=>{k.notify(`session switch failed: ${M.message}`)}),!0):(P().catch(()=>{}),!0)}case"/rename":{let A=I===-1?"":y.slice(I+1).trim(),M=A.length>0?`/hydra title ${A}`:"/hydra title";return On(y,y),Qi(M,[],y),!0}case"/btw":{let A=I===-1?"":y.slice(I+1).trim();if(!A)return k.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(Pe==="__new__")return k.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;B+=1;let M=B;$&&($.cancel(),$=null);let U=null;H!==null&&!J?U=H:H!==null&&(Pn(n,H).catch(()=>{}),H=null),J=!1,k.openBtwOverlay(),k.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new Ud({getMaxWidth:()=>{let ce=k.width();return ce>0?ce:void 0}});O.on("changed",()=>{k.setBtwOverlayContent(O.getLines())});let G={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Fe=ce=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:ce}})},Ae={};return U!==null&&(Ae.reuseSessionId=U),Ny(n,Pe,A,Ae).then(ce=>{if(M!==B){ce.cancel();return}$=ce,H=ce.sessionId,k.setBtwOverlayMeta({sessionId:ce.sessionId}),ce.on("event",le=>{if(M===B)if(le.kind==="update"){O.append(le.update);let _e=Rn(le.update);if(_e&&_e.kind==="usage-update"){let Vs=!1;_e.used!==void 0&&G.used!==_e.used&&(G.used=_e.used,Vs=!0),_e.size!==void 0&&G.size!==_e.size&&(G.size=_e.size,Vs=!0),_e.costAmount!==void 0&&G.costAmount!==_e.costAmount&&(G.costAmount=_e.costAmount,Vs=!0),_e.costCurrency!==void 0&&G.costCurrency!==_e.costCurrency&&(G.costCurrency=_e.costCurrency,Vs=!0),Vs&&k.setBtwOverlayMeta({usage:{...G}})}}else le.kind==="completed"?(k.setBtwOverlayStatus({label:"done",style:"done"}),$=null):le.kind==="cancelled"?(k.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),$=null,H=null):le.kind==="errored"&&(k.setBtwOverlayStatus({label:"errored",style:"errored"}),Fe(`btw errored: ${le.error.message}`),H!==null&&Pn(n,H).catch(()=>{}),$=null,H=null)})}).catch(ce=>{if(M!==B)return;let le=ce instanceof Error?ce.message:String(ce);k.setBtwOverlayStatus({label:"errored",style:"errored"}),Fe(`btw startup failed: ${le}`),k.appendLines([{prefix:" ",body:`btw startup failed: ${le}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Pe==="__new__")return k.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=I===-1?"":y.slice(I+1).trim(),M=Pe;return(async()=>{try{let U=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(M)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!U.ok){let le=await U.text().catch(()=>"");k.appendLines([{prefix:" ",body:`/export failed: HTTP ${U.status} ${le}`.trim(),bodyStyle:"info"}]);return}let O=await U.text(),G=new Date().toISOString().replace(/[:.]/g,"-"),Fe=`hydra-${Ve(M)}-${G}.md`,Ae=A.length>0?je(A):Fe,ce=Ir.resolve(Ae);await Vu.mkdir(Ir.dirname(ce),{recursive:!0}),await Vu.writeFile(ce,O,{encoding:"utf8",mode:384}),k.appendLines([{prefix:" ",body:`Wrote ${ce}`,bodyStyle:"system"}])}catch(U){k.appendLines([{prefix:" ",body:`/export failed: ${U.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},Qi=async(g,y,I)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Ae of y)C.push({type:"image",data:Ae.data,mimeType:Ae.mimeType});Ct(1);let A={text:g,displayText:I??g,attachments:y,flushed:!1};Ot.push(A),Gt=!1;let M=!1,U=null,O=Ae=>{typeof de<"u"&&de!==null&&de.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Ae,bodyStyle:"tool-status-fail"}])},G=!1;Ge={text:g,attachments:y,cancel:()=>{if(Gt){Gt=!1,G=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Pe}).catch(ce=>{O(`force-stop failed: ${ce.message}`)});return}if(M)return;M=!0,h.notify("session/cancel",{sessionId:Pe}).catch(()=>{});let Ae=Date.now();U=setTimeout(()=>{Ge!==null&&(xr>=Ae||(Gt=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},Qt)}};let Fe;try{let Ae=await h.request("session/prompt",{sessionId:Pe,prompt:C});Ae&&typeof Ae.stopReason=="string"&&(Fe=Ae.stopReason)}catch(Ae){let ce=Ot.indexOf(A);ce>=0&&Ot.splice(ce,1),A.messageId!==void 0&&bn.delete(A.messageId),G?k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):k.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Ae.message,bodyStyle:"tool-status-fail"}])}finally{if(Ge=null,U!==null&&(clearTimeout(U),U=null),Ct(-1),A.flushed&&vt===A){let Ae=A.messageId!==void 0&&dt.has(A.messageId);Ae&&A.messageId!==void 0&&dt.delete(A.messageId);let ce={kind:"turn-complete"};Fe!==void 0&&(ce.stopReason=Fe),Ae&&(ce.amended=!0),x(ce),vt=null}if(Fs!==null){let{text:Ae,attachments:ce}=Fs;Fs=null,me.state().buffer.every(_e=>_e==="")&&(me.setBuffer(Ae,ce),k.refreshPrompt())}}},rt=new Map,Nn=new Map,Dn=new Map,as=new Map,Hn=[],ct=0,sn=`tools:${ct}`,Un=new Map,zs=new Map,Fr=new Set,Js=new Map,jn=new Map,Ks=new Map,E=null,W=null,ie=null,q=null,ne=null,oe=e.tui.maxToolItems,Me=e.tui.maxPlanItems,He=()=>({maxPlanItems:ne??i.planExpanded?1/0:Me}),et=()=>{if(q===null)return;let g=Is(q,He());g.length>0&&k.upsertLines("plan",[{body:""},...g])},St="",Oe=null,Wt=0,ic=()=>{if(Oe===null)return;let g=k.width(),y=xs(St,g>0?{maxWidth:g}:void 0);y.length!==0&&k.upsertLines(Oe,y)},Xw=g=>{g.length!==0&&(Oe===null&&(k.ensureSeparator(),Oe=`agent:${Wt}`,Wt+=1,St=""),St+=g,ic())},ds=()=>{Oe=null,St=""},Lr="",Ys=null,Zu=0,Zw=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),eb=()=>{if(Ys===null||Lr.length===0)return;let g=Ai(Lr);g.length!==0&&k.upsertLines(Ys,g)},tb=g=>{let y=jn.get(g);if(y===void 0)return[];let I=Ai(y.text);return y.workerTaskId&&I.unshift({prefix:" ",body:`[T${y.workerTaskId}] `,bodyStyle:"dim"}),I},nb=(g,y)=>{g.length!==0&&(Ys===null&&(k.ensureSeparator("thought"),Ys=`thought:${Zu}`,Zu+=1,Lr=""),Lr+=g,jn.set(Ys,{text:Lr,workerTaskId:y}),eb())},cs=()=>{Ys=null,Lr=""},ef=g=>n0({...g,collapsedLimit:oe}),tf=g=>zs.get(g)??i.toolsExpanded,rn=()=>{if(E===null)return;let{lines:g,rowOwners:y}=ef({order:Hn,states:rt,startedAt:E,endedAt:W,stopReason:ie,expanded:tf(sn),perToolExpanded:Fr});k.upsertLines(sn,g),Js.set(sn,y)},ta=g=>{let y=Un.get(g);if(!y)return;let{lines:I,rowOwners:C}=ef({order:y.order,states:y.states,startedAt:y.startedAt,endedAt:y.endedAt,stopReason:y.stopReason,expanded:tf(g),perToolExpanded:Fr});k.upsertLines(g,I),Js.set(g,C)},sb=()=>{E!==null&&!Un.has(sn)&&rn();for(let g of Un.keys())ta(g)},oc=()=>{E!==null&&Un.set(sn,{order:[...Hn],states:new Map(rt),startedAt:E,endedAt:W??Date.now(),stopReason:ie,rowOwners:Js.get(sn)??[]})},nf=()=>{ct+=1,sn=`tools:${ct}`,E=Date.now(),W=null,ie=null,rn()};function rb(g){if(!g||typeof g!="object")return null;let y=g,I=Array.isArray(y.content)?y.content:void 0;if(!I)return null;let C=[],A=M=>{if(typeof M=="string"){C.push({text:tt(M)});return}if(M&&typeof M=="object"){let U=M;typeof U.__hydraBlob=="string"&&C.push({hash:U.__hydraBlob})}};for(let M of I){if(!M||typeof M!="object")continue;let U=M;if(U.type==="content"&&U.content&&typeof U.content=="object"){let O=U.content;if(O.text!==void 0){A(O.text);continue}}if(U.type==="text"&&U.text!==void 0){A(U.text);continue}U.text!==void 0&&A(U.text)}return C.length>0?C:null}let sf=(g,y)=>{let I=y.map(M=>"text"in M?M.text:"").join(`
191
- `);if(I.length===0)return;let{text:C,truncated:A}=dg(I);g.resultText=C,g.resultTruncated=A},na=new Set,ib=(g,y)=>{!y.some(C=>"hash"in C)||na.has(g)||(na.add(g),(async()=>{let C=await Promise.all(y.map(async M=>"text"in M?M:{text:await ac(M.hash)??""}));na.delete(g);let A=rt.get(g);if(!A)for(let M of Un.values()){let U=M.states.get(g);if(U){A=U;break}}if(A){sf(A,C),rt.has(g)&&rn();for(let[M,U]of Un)U.states.has(g)&&ta(M);k.repaintNow()}})().catch(()=>{na.delete(g)}))},rf=(g,y,I,C,A,M,U,O,G,Fe)=>{let Ae=!rt.has(g),ce=rt.get(g),le=ce??{initialTitle:y??"tool",latestTitle:y??"tool",status:I??"pending",startedAt:Date.now()};if(!ce&&G!==void 0&&(le.workerTaskId=G),ce&&y!==void 0&&(le.latestTitle=y),M!==void 0&&le.detail===void 0&&(le.detail=M),U!==void 0&&le.detailFull===void 0&&(le.detailFull=U),O!==void 0&&O.length>0&&(le.locations=O),ce&&I!==void 0&&(le.status=I),ce||(le.status=I??"pending"),le.endedAt===void 0&&eu(le.status)&&(le.endedAt=Date.now()),C!==void 0&&(le.errorText=C),A!==void 0&&(le.editDiff=A),Fe!==void 0){let _e=rb(Fe);_e!==null&&(sf(le,_e),_e.some(Vs=>"hash"in Vs)&&ib(g,_e))}rt.set(g,le),Ae&&(E===null&&(ct+=1,sn=`tools:${ct}`,E=Date.now(),W=null,ie=null),Hn.push(g))},ac=async g=>{try{let y=await h.request("hydra-acp/session/tool_content",{sessionId:Pe,hash:g});return typeof y?.content=="string"?y.content:null}catch{return null}},sa=new Set,ob=(g,y)=>{sa.has(g)||y.oldRef===void 0&&y.newRef===void 0||(sa.add(g),(async()=>{let[I,C]=await Promise.all([y.oldRef?ac(y.oldRef.hash):Promise.resolve(y.oldText),y.newRef?ac(y.newRef.hash):Promise.resolve(y.newText)]);if(y.oldRef!==void 0&&I===null||y.newRef!==void 0&&C===null){sa.delete(g);let Fe=Xl(y,"diff",{deferredStatus:"error"});Fe.length>0&&(k.upsertLines(`editdiff:${g}`,Fe),k.repaintNow());return}let M={...y.path!==void 0?{path:y.path}:{},oldText:I??"",newText:C??""};Nn.set(g,M);let U=rt.get(g);U?.editDiff&&(U.editDiff=M),sa.delete(g);let O=Dn.get(g),G=O===void 0?i.showFileUpdates:O?"diff":"edit";G!=="none"&&(ra(g,M,G==="diff"?"diff":"edit"),k.repaintNow())})())},ra=(g,y,I)=>{let C=`editdiff:${g}`,A=Xl(y,I);if(A.length===0){k.removeKey(C);return}k.upsertLines(C,A),I==="diff"&&(y.oldRef!==void 0||y.newRef!==void 0)&&k.notifyWhenVisible(C)},ab=g=>{if(!g.startsWith("editdiff:"))return;let y=g.slice(9),I=Nn.get(y);I&&(I.oldRef!==void 0||I.newRef!==void 0)&&ob(y,I)},of=g=>{let y=`editdiff:${g}`,I=i.showFileUpdates,C=rt.get(g),A;if(I==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let U=Dn.get(g);A=U!==void 0?U?"diff":"edit":I==="diff"?"diff":"edit"}if(A===null){k.removeKey(y);return}let M=C.editDiff;Nn.set(g,M),ra(g,M,A)},db=()=>{let g=i.showFileUpdates;for(let[y,I]of Nn){let C=`editdiff:${y}`,A=Dn.get(y),M=A===void 0?g:A?"diff":"edit";if(M==="none"){k.removeKey(C);continue}ra(y,I,M==="diff"?"diff":"edit")}},cb=g=>{if(!g.path)return null;let y=tt(g.oldText).split(`
192
- `),I=tt(g.newText).split(`
193
- `),C=0,A=Math.min(y.length,I.length);for(;C<A&&y[C]===I[C];)C++;let M=I[C];if(!M)return null;let U=Ir.isAbsolute(g.path)?g.path:Ir.resolve(gt,g.path),O;try{O=VR(U,"utf8")}catch{return null}let G=O.split(`
194
- `);for(let Fe=0;Fe<G.length;Fe++)if(G[Fe]===M)return Fe+1;return null},lb=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=Nn.get(I),M=rt.get(I)?.locations?.[0],U=M?.path??C?.path;if(!U)return!1;let O=null;M?.line!==void 0?O=M.line:C&&(O=cb(C));let G=O===null?"":`:${O}`;return k.tryOpenPathString(U+G)}if(g.startsWith("tools:")){if(y===0)return!1;let I=Js.get(g),C=I?I[y]:void 0;if(!C)return!1;let A=rt.get(C),M=A?.locations?.[0];if(M){let O=M.line===void 0?"":`:${M.line}`;if(k.tryOpenPathString(M.path+O))return!0}let U=A?.detailFull??A?.detail;if(U)return k.tryOpenPathString(U)}return!1},ub=(g,y)=>{if(g.startsWith("editdiff:")){let I=g.slice(9),C=Nn.get(I);if(!C)return;let A=Dn.get(I)??i.showFileUpdates==="diff";Dn.set(I,!A),ra(I,C,A?"edit":"diff"),k.repaintNow();return}if(g==="plan"){if(q===null)return;ne=!(ne??i.planExpanded),et(),k.repaintNow();return}if(g.startsWith("tools:")){if(y===0){let A=zs.get(g)??i.toolsExpanded;zs.set(g,!A),g===sn&&E!==null?rn():ta(g),k.repaintNow();return}let I=Js.get(g);if(!I)return;let C=I[y];if(!C)return;t0(C,Fr),ta(g),k.repaintNow();return}if(g.startsWith("thought:")){if(!jn.has(g))return;let I=Ks.get(g);if(I!==void 0){Ks.delete(g),k.setRunCollapsed(I,!1,tb(g)),k.repaintNow();return}let C=k.contiguousRun(g,new Set(jn.keys()));if(C.length===0)return;let A=C[0];Ks.set(A,C),k.setRunCollapsed(C,!0,[Zw()]),k.repaintNow();return}};b=(g,y)=>{if(g.kind==="available-commands"){Bs=g.commands,Wi();return}if(g.kind==="available-modes"){Fn=g.modes;return}if(g.kind==="config-options"){At=g.options;let C=g.options.find(M=>M.id==="agent");C&&C.currentValue&&C.currentValue!==Xt&&(Xt=C.currentValue,k.setSessionbar({agent:C.currentValue}));let A=g.options.find(M=>M.id==="mode");A&&(Fn=A.options.map(M=>({id:M.value,name:M.name??M.value,...M.description!==void 0?{description:M.description}:{}})));return}if(g.kind==="mode-changed"){k.setBanner({currentMode:g.mode||void 0});return}if(g.kind==="session-info"){g.title!==void 0&&k.setSessionbar({title:g.title}),g.agentId!==void 0&&g.agentId!==Xt&&(Xt=g.agentId,k.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&_t.used!==g.used&&(_t.used=g.used,C=!0),g.size!==void 0&&_t.size!==g.size&&(_t.size=g.size,C=!0),g.costAmount!==void 0&&_t.costAmount!==g.costAmount&&(_t.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&_t.costCurrency!==g.costCurrency&&(_t.costCurrency=g.costCurrency,C=!0),C&&k.setSessionbar({usage:{..._t}});return}if(g.kind==="user-text"){Yo&&On(g.text),ds(),cs(),E!==null&&(W=Date.now(),rn()),vt=null,k.ensureSeparator();let C=Is(g);C.length>0&&k.appendLines(C),oc(),k.clearKey("plan"),q=null,ne=null,rt.clear(),as.clear(),Hn.length=0,W=null,nf(),k.redraw();return}if(g.kind==="agent-text"){cs(),Oe===null&&F(g.workerTaskId),Xw(g.text);return}if(g.kind==="agent-thought"){ds(),Ys===null&&F(g.workerTaskId),nb(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){ds(),cs();let C=as.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(as.set(g.toolCallId,A),A.plan.length===0)return;let M=mg(A);M.length>0&&k.upsertLines(g.toolCallId,M);return}if(g.kind==="tool-call"){ds(),cs(),rt.has(g.toolCallId)||F(g.workerTaskId),rf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),rn(),of(g.toolCallId);return}if(g.kind==="plan"){ds(),cs(),q=g;let C=Is(g,He());C.length>0&&k.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(M=>(M.status??"pending")==="completed");k.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){ds(),cs(),rf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,y),g.upstreamInterrupted&&(Ms=!0),rn(),of(g.toolCallId);return}g.kind==="model-changed"&&k.setSessionbar({model:g.model});let I=Is(g);if(I.length>0&&k.appendLines(I),g.kind==="turn-complete"){Y=void 0,ds(),cs();let C=g.amended?"amended":g.stopReason;if(!g.amended&&Ms&&(C===void 0||C==="end_turn")&&(C="error"),q!==null&&C!==void 0&&C!=="end_turn"){let A=Is({...q,stopped:!0,amended:g.amended===!0},He());A.length>0&&k.upsertLines("plan",[{body:""},...A])}q=null,ne=null,k.clearKey("plan"),k.setStickyBottomKey("plan"),E!==null?(W=Date.now(),ie=C??null,rn(),oc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null,Ms=!1,k.ensureSeparator(),Mw({pendingTurns:N,queueSize:bt.size,ownTurnInFlight:Ge!==null,hasInFlightHead:Y!==void 0,replayDraining:S,amended:g.amended===!0})&&Ct(-N)}};let af=w;w=[];let ia=[];for(let{event:g}of af)g.kind==="user-text"&&typeof g.text=="string"&&ia.push(g.text);k.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:y}of af)b(g,y)}finally{S=!1,k.resumeRepaint()}if(ia.length>0){let g=gl(ue,ia);g!==ue&&(ue=g,en=gl(en,ia),me.setHistory(Fa(yt,en)),ir(gn,ue).catch(()=>{}))}Yo=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Pe)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let y=await g.json(),I=y.compactionState?.status;if(I==="requested"||I==="running"?k.setCompactionIndicator("compacting..."):(I==="swap_pending"||I==="swap_deferred")&&k.setCompactionIndicator("compaction queued (waiting for idle)"),!ji||y.shouldCompact!==!0)return;let C=y.approxTokens??0;j=!0,k.setCompactionPrompt({message:`This session has ~${Lm(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),jt!==void 0&&N>0?(be=jt,k.setBanner({status:"busy",elapsedMs:Date.now()-jt}),V===null&&(V=Je()),E===null&&nf(),E=jt,rn()):jt===void 0&&N>0&&Ct(-N);let fb=()=>{if(ve){let g=ve.resolve;ve=null,k.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}ds(),cs()},df=()=>{E!==null&&(W=Date.now(),ie="reconnect-recovery-failed",rn(),oc(),rt.clear(),as.clear(),Hn.length=0,E=null,W=null,ie=null)};return p=()=>{k.setBanner({status:"disconnected",elapsedMs:void 0})},u=async()=>{fb();let g={jsonrpc:"2.0",id:`tui-reinit-${Ow()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:fe}}};try{await m.request(g)}catch{}let y=$e!==void 0,I={jsonrpc:"2.0",id:`tui-reattach-${Ow()}`,method:"session/attach",params:{sessionId:Pe,historyPolicy:y?"after_message":"none",...y?{afterMessageId:$e}:{},clientInfo:{name:"hydra-acp-tui",version:fe},...(()=>{let O={};return $s!==void 0&&(O.resume={upstreamSessionId:$s,agentId:Xt,cwd:gt}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[mt]:O}}:{}})()}};pn=[];let C,A,M;try{let O=await m.request(I);if(O.error)throw new Error(O.error.message);M=Pw(O.result),C=M.appliedPolicy,M.clientId!==void 0&&(at=M.clientId)}catch(O){A=O}let U=pn??[];if(pn=null,A)df(),k.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(y&&C!=="after_message")df(),k.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{S=!0;try{for(let O of U)$n(O)}finally{S=!1}}if(M){let O=_w({daemonTurnStartedAt:M.turnStartedAt,pendingTurns:N});O.pendingTurnsDelta!==0&&Ct(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(be=O.busySince,k.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),V===null&&(V=Je())):k.setBanner({status:"ready",elapsedMs:void 0})}else k.setBanner({status:N>0?"busy":"ready",elapsedMs:N>0?0:void 0})},h.onClose(g=>{g&&t.red(`
182
+ `)})};te();let ie=new AbortController,se={onKey:Ee=>{if(Ee==="ESCAPE"||Ee==="CTRL_C"){ie.abort(),Ht();return}},onResize:()=>te()};St(se),(async()=>{try{let Ee=await Kt(`${e.target.baseUrl}/v1/sessions/${encodeURIComponent(P.sessionId)}/export`,{headers:{Authorization:`Bearer ${e.target.token}`},signal:ie.signal});if(!Ee.ok)throw new Error(`daemon returned HTTP ${Ee.status}`);let Me=await Ee.json(),Ze=gn(Me),Ae=gu(Ze,P.status);z=Dd(Ae,!1).replace(/\n$/,"").split(`
183
+ `)}catch(Ee){if(ie.signal.aborted)return;ce=`failed to load info: ${Ee.message}`}finally{q=!1,!M&&ve[ve.length-1]===se&&te()}})()},Vn=()=>{if(a.length===0){de="no sessions to search",me();return}F=new is({history:[],collapsePastes:!1}),j=[],J=!1,D=0,L=0,Ue=0,U=null,Q=!1,_="input",T=!0,Ys(),jn(),St({onKey:(z,ce,q)=>{if(_==="input"){if(Q)return;if(z==="ESCAPE"||z==="CTRL_C"){Nt();return}if(z==="ENTER"||z==="KP_ENTER"){if(la().trim().length===0)return;Xs();return}if((z==="DOWN"||z==="TAB"||z==="CTRL_N")&&j.length>0){_="results",D=0,L=0,Be(()=>{at(),qn(0,!0),ms(),t.hideCursor()});return}let te=F.state(),ie=null;if(z==="")ie={type:"key",name:"ctrl-underscore"};else if(z==="\x1B_"||z==="\x1B")ie={type:"key",name:"alt-underscore"};else if(q?.isCharacter)ie={type:"char",ch:z};else{let Ze=cc(z);Ze!==null&&(ie={type:"key",name:Ze})}if(ie===null){t.moveTo(Qs(),lt());return}F.feed(ie);let se=F.state();if(te.buffer.length===se.buffer.length&&te.buffer.every((Ze,Ae)=>Ze===se.buffer[Ae])&&te.row===se.row&&te.col===se.col){t.moveTo(Qs(),lt());return}let Me=ct;Ys(),ct!==Me?jn():da();return}if(_==="results"){if(z==="ESCAPE"||z==="CTRL_C"){Nt();return}if(z==="CTRL_F"){_="input",ro(),ms(),at();return}if(z==="ENTER"||z==="KP_ENTER"){let ie=j[D];if(!ie)return;let se=a.find(Me=>Me.sessionId===ie.sessionId);if(!!se?.importedFromMachine&&!se.upstreamSessionId){ut();let Me={kind:"attach",sessionId:ie.sessionId};se.agentId!==void 0&&(Me.agentId=se.agentId),R(Me);return}(async()=>{let Me=await Lw(t,{sessionId:ie.sessionId,title:ie.title,cwd:ie.cwd},jr);if(Me==="cancel"){ut(),R({kind:"abort"});return}if(Me==="back")return;ut();let Ze={kind:"attach",sessionId:ie.sessionId,readonly:Me==="view"};se?.agentId!==void 0&&(Ze.agentId=se.agentId),R(Ze)})();return}if(q?.isCharacter&&(z==="n"||z==="N")){let ie=j[D];if(!ie||ie.snippets.length<=1)return;L=(L+1)%ie.snippets.length,qn(D,!0);return}if(q?.isCharacter&&(z==="p"||z==="P")){let ie=j[D];if(!ie||ie.snippets.length<=1)return;L=(L-1+ie.snippets.length)%ie.snippets.length,qn(D,!0);return}let te=ie=>{if(ie<0&&D===0){_="input",Be(()=>{qn(0,!1),ms(),at()});return}let se=Math.min(j.length-1,Math.max(0,D+ie));if(se===D)return;let Ee=D,Me=Ue;D=se,L=0,ia(),Ue!==Me?ro():(Be(()=>{qn(Ee,!1),qn(D,!0)}),ms())};switch(z){case"UP":case"SHIFT_TAB":case"CTRL_P":te(-1);return;case"DOWN":case"TAB":case"CTRL_N":te(1);return;case"PAGE_UP":te(-vn());return;case"PAGE_DOWN":te(vn());return;case"HOME":te(-D);return;case"END":te(j.length);return}return}},onResize:()=>jn()})},ws=(P,z,ce)=>{if(S!=="busy"){if(P==="CTRL_O"){gs();return}if(P==="CTRL_L"){no();return}if(S==="rename"){if(P==="ENTER"||P==="KP_ENTER"){let q=V.trim();if(q.length===0){S="normal",x=null,V="",me();return}xn(q);return}if(P==="ESCAPE"||P==="CTRL_C"){S="normal",x=null,V="",At(),me();return}if(P==="BACKSPACE"){V.length>0&&(ye(),V=V.slice(0,-1),me());return}if(P==="CTRL_U"){V.length>0&&(ye(),V="",me());return}if(P==="CTRL_W"){let q=V.replace(/\s+$/,""),te=q.lastIndexOf(" "),ie=te>=0?q.slice(0,te):"";ie!==V&&(ye(),V=ie,me());return}if(P===""){Qe(),me();return}if(P==="\x1B_"||P==="\x1B"){qs(),me();return}if(ce?.isCharacter){ye(),V+=P,me();return}return}if(S==="confirm-kill"||S==="confirm-delete"){if(ce?.isCharacter&&(P==="y"||P==="Y")){pa(S==="confirm-kill"?"kill":"delete");return}if(P==="ESCAPE"||P==="CTRL_C"||P==="ENTER"||P==="KP_ENTER"||ce?.isCharacter&&(P==="n"||P==="N")){S="normal",x=null,me();return}return}if(oo(),P==="CTRL_F"){Vn();return}if(f===0&&!m){if(P==="ESCAPE"){Et();return}if(P==="ENTER"||P==="KP_ENTER"){ut();let Ae=Oe.expandedText(),ft=nr();Ae.trim().length>0&&(ft.prompt=Ae),R(ft);return}if(P==="UP"&&b){let Ae=Date.now(),ft=Ae-v;if(v=Ae,ft<y){Lt();return}b=!1}if(P==="DOWN"){let Ae=Oe.state(),ft=Ae.historyIndex!==-1||Ae.queueIndex!==-1,Wr=rn.length===0||Se===rn.length-1;if(!ft&&Wr&&a.length>0){Pt(1);return}}if(P==="PAGE_DOWN"&&(rn.length===0||Se===rn.length-1)&&a.length>0){Pt(1);return}if(P==="CTRL_P"){a.length>0&&Pt(1);return}b=!1;let q=Oe.state(),te=null;if(P==="")te={type:"key",name:"ctrl-underscore"};else if(P==="\x1B_"||P==="\x1B")te={type:"key",name:"alt-underscore"};else if(ce?.isCharacter)te={type:"char",ch:P};else{let Ae=cc(P);Ae!==null&&(te={type:"key",name:Ae})}if(te===null){Lt();return}let ie=Oe.feed(te),se=Oe.state(),Ee=q.buffer.length===se.buffer.length&&q.buffer.every((Ae,ft)=>Ae===se.buffer[ft])&&q.row===se.row&&q.col===se.col;if(ie.some(Ae=>Ae.type==="exit")){Et();return}if(Ee){Lt();return}let Me=as(se.buffer,sn);if(Us(Me,se,fc).rendered!==Vt){De();return}hs();return}if(!m&&ce?.isCharacter&&P==="?"){st();return}if(m){if(ce?.isCharacter){h+=P,ot(),De();return}if(P==="BACKSPACE"){h.length>0?(h=h.slice(0,-1),ot(),De()):(m=!1,ot(),De());return}if(P==="ESCAPE"||P==="CTRL_C"){m=!1,h="",ot(),De();return}}if(ce?.isCharacter){if(P==="/"){m=!0,h="",ot(),De();return}if(P==="n"||P==="N"){Pt(1);return}if(P==="p"||P==="P"){Pt(-1);return}if(P==="c"||P==="C"){let q=f>0?a[f-1]:void 0,te=nr();q?.cwd&&(te.cwd=q.cwd),ut(),R(te);return}if(P==="q"||P==="Q"){Et();return}if(P==="o"||P==="O"){let q=f>0?a[f-1]?.sessionId:void 0;s.filters.cwdOnly=!s.filters.cwdOnly,ot(),ls(q),De();return}if(P==="h"||P==="H"){let q=f>0?a[f-1]?.sessionId:void 0;s.filters.hostFilter=o0(s.filters.hostFilter,i),ot(),ls(q),De();return}if(P==="i"&&f>0){let q=a[f-1];if(!q)return;Kn(q);return}if(P==="I"){let q=f>0?a[f-1]?.sessionId:void 0;s.filters.includeNonInteractive=!s.filters.includeNonInteractive,ot(),ls(q),De();return}if(P==="r"||P==="R"){let q=f>0?a[f-1]?.sessionId:void 0;In(q);return}if(P==="s"||P==="S"){io();return}if((P==="v"||P==="V")&&f>0){let q=a[f-1];if(!q)return;ut();let te={kind:"attach",sessionId:q.sessionId,readonly:!0};q.agentId!==void 0&&(te.agentId=q.agentId),R(te);return}if((P==="f"||P==="F")&&f>0){let q=a[f-1];if(!q)return;ut();let te={kind:"fork",sourceSessionId:q.sessionId,sourceCwd:q.cwd};q.agentId!==void 0&&(te.sourceAgentId=q.agentId),q.importedFromMachine!==void 0&&(te.sourceImportedFromMachine=q.importedFromMachine),q.upstreamSessionId!==void 0&&(te.sourceUpstreamSessionId=q.upstreamSessionId),R(te);return}if((P==="k"||P==="K")&&f>0){let q=a[f-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-kill",me();return}if(P==="t"&&f>0){let q=a[f-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},V=q.title??"",S="rename",me();return}if(P==="T"&&f>0){let q=a[f-1];if(!q)return;sr({sessionId:q.sessionId});return}if(P==="*"&&f>0){let q=a[f-1];if(!q)return;fa(q);return}if((P==="d"||P==="D")&&f>0){let q=a[f-1];if(!q)return;x={sessionId:q.sessionId,cwd:q.cwd,status:q.status},S="confirm-delete",me();return}return}switch(P){case"UP":case"SHIFT_TAB":case"CTRL_P":P==="UP"&&(f===1&&(b=!0),v=Date.now()),Pt(-1);return;case"DOWN":case"TAB":case"CTRL_N":Pt(1);return;case"PAGE_UP":Pt(-He);return;case"PAGE_DOWN":Pt(He);return;case"HOME":Pt(1-f);return;case"END":Pt(u);return;case"ENTER":case"KP_ENTER":{if(ut(),f===0){R(nr());return}let q=a[f-1];if(!q){R({kind:"abort"});return}let te={kind:"attach",sessionId:q.sessionId};q.agentId!==void 0&&(te.agentId=q.agentId),R(te);return}case"ESCAPE":case"CTRL_C":case"CTRL_D":Et();return}}};St({onKey:(P,z,ce)=>ws(P,z,ce),onResize:()=>{M||De()}});let ln=(P,z)=>{if(M||ve.length!==1||S!=="normal")return;let ce=P==="MOUSE_MOTION",q=P==="MOUSE_LEFT_BUTTON_PRESSED",te=P==="MOUSE_WHEEL_UP";if(te||P==="MOUSE_WHEEL_DOWN"){if(a.length===0)return;let bs=te?-3:3,Jr=Math.max(0,a.length-He),Qn=Math.min(Jr,Math.max(0,p+bs));if(Qn===p)return;if(p=Qn,f>0){let ao=f-1;ao<p?f=p+1:ao>=p+He&&(f=p+He)}vt();return}if(!ce&&!q)return;let se=z?.y;if(typeof se!="number")return;if(se>=on&&se<=ke()){if(q){if(wt=!1,f!==0){let bs=f;f=0,Be(()=>{vt(),qr(bs,f)})}return}!wt&&f!==0&&(wt=!0,Be(()=>{Dt(),vt()}));return}wt&&(wt=!1,Be(()=>{Dt(),vt()}));let Me=cn()+1,Ze=Me+He-1;if(se<Me||se>Ze)return;let Ae=p+(se-Me);if(Ae<0||Ae>=a.length)return;let ft=a[Ae];if(!ft)return;let Wr=Ae+1;if(f!==Wr){let bs=f;f=Wr,Yt(),Be(()=>{vt(),qr(bs,f)})}if(!q)return;ut();let zr={kind:"attach",sessionId:ft.sessionId};ft.agentId!==void 0&&(zr.agentId=ft.agentId),R(zr)},Yn=()=>{t.grabInput({mouse:"motion"});let P=t;P.stdin&&typeof P.onStdin=="function"&&(Rt=P.onStdin,P.stdin.removeListener("data",P.onStdin),P.stdin.on("data",Wn),process.stdout.write(jd)),t.on("key",Tt),t.on("mouse",ln),t.on("resize",ys)},Gt=()=>{process.stdout.write(ns);let P=t;P.stdin&&Rt&&(P.stdin.removeListener("data",Wn),P.stdin.on("data",Rt),Rt=null),Sn=!1,kn="",t.off("key",Tt),t.off("mouse",ln),t.off("resize",ys),t.grabInput(!1),t.hideCursor(!1)};if(Yn(),process.platform!=="win32"){let P=!1,z=()=>{P&&(P=!1,t.fullscreen(!0),n(),t.hideCursor(),Yn(),M||no())};tr=()=>{P||M||(P=!0,Gt(),t.fullscreen(!1),process.stdout.write(`${zo}${qd}
184
+ `),process.once("SIGCONT",z),process.kill(process.pid,"SIGTSTP"))}}N=setInterval(zn,3e3)})}function r0(t,e){let n="Create new session in ",s=Math.max(1,e-n.length);return n+Uo(ze(t),s)}function pc(t,e){let n=r=>r.priority&&r.priority>0?r.priority:0,s=r=>{let i=r.status==="live",o=n(r)>0;return i&&r.awaitingInput?5:i&&r.busy?4:i&&o?3:i?2:o?1:0};return[...t].sort((r,i)=>{let o=s(i)-s(r);if(o!==0)return o;let a=n(i)-n(r);return a!==0?a:i.updatedAt.slice(0,16).localeCompare(r.updatedAt.slice(0,16))})}function i0(t,e){return e==="__all"?t:e==="__local"?t.filter(n=>!n.importedFromMachine||!!n.upstreamSessionId):t.filter(n=>n.importedFromMachine===e&&!n.upstreamSessionId)}function o0(t,e){let n=new Set;for(let i of e)i.importedFromMachine&&!i.upstreamSessionId&&n.add(i.importedFromMachine);let s=["__local",...[...n].sort(),"__all"],r=s.indexOf(t);return r===-1?"__local":s[(r+1)%s.length]??"__local"}function a0(t,e){if(e.length===0)return!0;let n=e.toLowerCase(),s=[et(t.sessionId),t.upstreamSessionId??"",t.agentId??"",t.title??"",t.cwd,ze(t.cwd)];for(let r of s)if(r.toLowerCase().includes(n))return!0;return!1}var sf,fc,t0,Dw,n0,s0,Hw=K(()=>{"use strict";Fd();he();En();Ho();Ya();Ou();ef();tf();nf();zi();Lu();ju();Jo();yr();yu();sf=2,fc=4,t0=4,Dw=4,n0=20,s0=[["Composer","type prompt for new session; Enter creates + submits"],["\u2193 from composer","drop focus into session list"],null,["\u2191 / \u2193, n / p, ^p / ^n","navigate sessions"],["PgUp / PgDn","page up / page down"],["Home / End","first / last"],["Enter","open selected session"],["v","view-only (open transcript without spawning the agent)"],null,["/","search sessions (metadata)"],["^f","find in session history (content + tool inputs)"],["o","toggle cwd-only filter"],["h","cycle host filter (local / <peer> / all)"],["^o","change cwd (for the picker and any new sessions)"],["i","show info for the selected session"],["I","toggle include-cat filter"],["r","refresh from daemon"],["s","sync sessions from installed agents"],null,["k","kill the selected live session"],["d","delete the selected session (kills first if live)"],["t","retitle the selected session"],["T","regenerate title + synopsis via agent"],["*","toggle high priority on the selected session (floats to top)"],null,["?","toggle this help"],["q / Esc / ^C / ^D","quit picker (detach)"]]});function u0(t,e){let n=t.findIndex(s=>s.id===e);return n===-1?0:n}async function Uw(t,e,n){ss();let s=u0(e,n??d0),r=0,i=()=>{let l=Er(t)-8;return Math.max(1,Math.min(c0,e.length,l))},o=()=>{let l=i();s<r?r=s:s>=r+l&&(r=s-l+1);let u=Math.max(0,e.length-l);r>u&&(r=u),r<0&&(r=0)},a=()=>{o();let l=i(),u=l+4,f=Math.min(l0,Math.max(40,yn(t)-8)),p=rs(t,{contentHeight:u,contentWidth:f,title:"Select agent"}),m=p.contentW,h=0;t.moveTo(p.contentX,p.contentY+h),t.noFormat(" Which agent should this session use?"),h+=2;let y=Math.min(e.length,r+l);for(let v=r;v<y;v++){let S=e[v];if(!S)continue;let x=v===s?"\u276F":" ",T=S.description??S.name,_=` ${x} ${S.id}`;if(t.moveTo(p.contentX,p.contentY+h),v===s){let F=`${_} ${T}`;t.brightWhite.bgBlue.noFormat(zd(nt(F,m),m))}else{t.noFormat(_);let F=m-_.length-2;F>1&&t.dim.noFormat(` ${nt(T,F)}`)}h++}h++,t.moveTo(p.contentX,p.contentY+h);let b=e.length>l?` (${s+1}/${e.length})`:"";return t.dim.noFormat(` \u2191/\u2193 navigate \xB7 Enter this session \xB7 s set default \xB7 Esc back${b}`),p},c=()=>{s<e.length-1&&(s++,a())},d=()=>{s>0&&(s--,a())};return Bs({term:t,render:a,onKey:(l,u,f,p)=>{if(l==="CTRL_C"||l==="CTRL_D"){p({kind:"cancel"});return}if(l==="ESCAPE"){p({kind:"back"});return}if(l==="ENTER"||l==="KP_ENTER"){let m=e[s];m&&p({kind:"select",agentId:m.id,persist:!1});return}if(l==="UP"||l==="SHIFT_TAB"){d();return}if(l==="DOWN"||l==="TAB"){c();return}if(f?.isCharacter){let m=l.toLowerCase();if(m==="s"){let h=e[s];h&&p({kind:"select",agentId:h.id,persist:!0});return}if(m==="j"){c();return}if(m==="k"){d();return}}}})}var d0,c0,l0,jw=K(()=>{"use strict";zi();d0="opencode",c0=20,l0=88});import*as Ww from"fs";import*as zw from"os";import*as mc from"path";function Jw(t,e){let n=e;for(;n>0;){let s=t[n-1]??"";if(/\s/.test(s)){if(s===" "&&t[n-2]==="\\"){n-=2;continue}break}n-=1}return n===e?null:{token:t.slice(n,e),start:n}}function f0(t){return t.length===0?!1:t.includes("/")?!0:t==="~"||t==="."||t===".."}function p0(t){return t.replace(/\\ /g," ")}function qw(t){return t.replace(/ /g,"\\ ")}function m0(t){let e=t.lastIndexOf("/");return e===-1?{dirPrefix:"",base:t}:{dirPrefix:t.slice(0,e+1),base:t.slice(e+1)}}function h0(t,e){let n=t.length===0?".":t;return(n==="~"||n.startsWith("~/"))&&(n=zw.homedir()+n.slice(1)),mc.isAbsolute(n)?n:mc.resolve(e,n)}function g0(t){let e;try{e=Ww.readdirSync(t,{withFileTypes:!0})}catch{return null}return e.map(n=>({name:n.name,isDir:n.isDirectory()}))}function Kw(t,e,n=g0){if(!f0(t))return null;let s=p0(t),{dirPrefix:r,base:i}=m0(s),o=h0(r,e),a=n(o);if(a===null)return null;let c=i.startsWith("."),d=a.filter(f=>f.name.startsWith(i)&&(c||!f.name.startsWith(".")));if(d.length===0)return null;let l=d.map(f=>f.isDir?f.name+"/":f.name);if(d.length===1){let f=d[0],p=f.isDir?f.name+"/":f.name;return{replacement:qw(r+p),candidates:l}}let u=na(d.map(f=>f.name));return{replacement:qw(r+u),candidates:l}}var Vw=K(()=>{"use strict";uc()});function Yw(t){let e={};if(!t||typeof t!="object")return e;let n=t;typeof n.historyPolicy=="string"&&(e.appliedPolicy=n.historyPolicy),typeof n.clientId=="string"&&n.clientId.length>0&&(e.clientId=n.clientId);let s=n._meta;if(s&&typeof s=="object"){let r=s["hydra-acp"];if(r&&typeof r=="object"){let i=r.turnStartedAt;typeof i=="number"&&(e.turnStartedAt=i)}}return e}function Qw(t){return!t.replayDraining&&!t.amended&&t.pendingTurns>0&&t.queueSize===0&&!t.ownTurnInFlight&&!t.hasInFlightHead}function Gw(t){return t.daemonTurnStartedAt!==void 0?{pendingTurnsDelta:t.pendingTurns===0?1:0,banner:"busy",busySince:t.daemonTurnStartedAt}:{pendingTurnsDelta:t.pendingTurns>0?-t.pendingTurns:0,banner:"ready"}}var Xw=K(()=>{"use strict"});import{appendFileSync as y0,readFileSync as w0,statSync as b0,renameSync as v0}from"fs";import{nanoid as Zw}from"nanoid";import S0 from"terminal-kit";import af from"fs/promises";import $r from"path";function k0(t){return t.filter(e=>e.status==="open"||e.status==="pending-delivery")}function I0(t){let e=hc(t);if(t.status==="pending-delivery"&&t.userAnswer){let n=e.indexOf(t.userAnswer);if(n!==-1)return n}return 0}function x0(t){let e=new Map,n=[];for(let s of t){let r=s.question,i=e.get(r);i?i.ids.push(s.id):(e.set(r,{representative:s,ids:[s.id]}),n.push(r))}return n.map(s=>e.get(s))}function hc(t){if(t.options&&t.options.length>0){let e=t.options.filter(n=>n!==t.defaultAnswer);return t.options.includes(t.defaultAnswer)?[t.defaultAnswer,...e]:[t.defaultAnswer,...t.options]}return[t.defaultAnswer]}function C0(t,e){return t.length<=e?t:e<=1?"\u2026":t.slice(0,e-1)+"\u2026"}function A0(t,e,n,s,r=60){let i=t.map((o,a)=>{let c=hc(o.representative),d=e[a]??0,l=n[a]?cf:c[d]??c[0]??"";return{label:C0(o.representative.question,r),value:l}});return{title:`Open questions (${t.length})`,options:i,selectedIndex:Math.max(0,Math.min(t.length-1,s)),hint:"\u2191/\u2193 row \xB7 \u2190/\u2192 cycle \xB7 d dismiss \xB7 1-9 jump \xB7 \u23CE/Esc save \xB7 ^C discard"}}function R0(t,e,n){return t===cf?{type:"dismiss",method:tw,params:{sessionId:n,questionId:e.id}}:{type:"answer",method:ew,params:{sessionId:n,questionId:e.id,answer:t}}}function T0(t,e,n,s,r){let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(!a||!n[o])continue;let c=s[o]?cf:hc(a.representative)[e[o]??0]??"";if(c)for(let d of a.ids){let l={...a.representative,id:d},u=R0(c,l,r);u!==null&&i.push(u)}}return i}function E0(t,e,n,s,r,i,o,a){if(!e||n===null||n.length===0)return{type:"noop"};if(t.type==="char"){if(t.ch==="d"||t.ch==="D")return{type:"dismiss-toggle",selectedRow:o};if(/^[1-9]$/.test(t.ch)){let d=parseInt(t.ch,10)-1;if(d<n.length)return{type:"row",selectedRow:d}}return{type:"noop"}}if(t.type!=="key")return{type:"noop"};let c=d=>{let l=n[o];if(!l)return{type:"noop"};let u=hc(l.representative);if(u.length===0)return{type:"noop"};let p=((s[o]??0)+d+u.length)%u.length;return{type:"cycle",selectedRow:o,newValueIndex:p}};switch(t.name){case"up":return{type:"row",selectedRow:Math.max(0,o-1)};case"down":return{type:"row",selectedRow:Math.min(n.length-1,o+1)};case"right":return c(1);case"left":return c(-1);case"enter":case"escape":case"ctrl-q":return{type:"save",dispatches:T0(n,s,r,i,a)};case"ctrl-c":return{type:"discard"};default:return{type:"noop"}}}function eb(t){if(!Array.isArray(t))return;let e=_n({sessionUpdate:"config_option_update",configOptions:t});return e&&e.kind==="config-options"?e.options:void 0}function df(t){switch(t.type){case"send":case"amend":case"queue-edit":case"queue-remove":case"plan-toggle":case"attachment-request":return!0;default:return!1}}function _0(t,e){e.has(t)?e.delete(t):e.add(t)}async function sb(t){let e=await we(),n=t.target??await Mt(e);ob=e.tui.logMaxBytes,n.isLocal&&!t.target&&await _s(e);let s=S0.terminal;$w(s);let r={},i={showThoughts:e.tui.showThoughts,toolsExpanded:!1,planExpanded:!1,showFileUpdates:e.tui.showFileUpdates,mouseEnabled:e.tui.mouse,inAppSelectionEnabled:Tf(e),defaultEnterAction:e.tui.defaultEnterAction},o=rf(),a=!1,c=()=>{a||(s.fullscreen(!0),a=!0)},d=()=>{a&&(s.fullscreen(!1),a=!1,process.stdout.write(`
185
+ `))};c();let l=()=>{a&&(s.fullscreen(!1),a=!1)};process.once("exit",l);let u=t;try{for(;u!==null;)u=await F0(s,e,n,u,r,i,o)}finally{d(),process.off("exit",l)}let f=await Vo();if(f&&process.stderr.write(`\u2728 ${Yo(f)}
186
+ `),process.stdout.isTTY){let p=await vr(e);if(p?.version!==void 0){let m=p.version!==pe,h=Ts(e),y=p.configDigest!==void 0&&p.configDigest!==h;if(m||y){let b=m?`daemon ${p.version} \u2260 cli ${pe}`:"config changed since daemon started",v=S=>`\x1B[33m${S}\x1B[0m`;process.stderr.write(v(`! ${b} \u2014 run \`${Cn()} daemon restart\` to apply.`)+`
187
+ `)}}}if(r.sessionId&&process.stdout.isTTY){let p=et(r.sessionId),m=r.readonly?" --readonly":"";process.stdout.write(`Continue: ${Cn()} --session ${p}${m}
188
+ `)}}function $0(t){let{order:e,states:n,startedAt:s,endedAt:r,stopReason:i,perToolExpanded:o,collapsedLimit:a=20}=t,c=e.length,d=a>0,l;if(!d||t.expanded)l=e;else{let J=Math.max(0,c-a),D=e.slice(J),L=[];for(let U=0;U<J;U++){let Q=e[U];if(Q===void 0)continue;let V=n.get(Q);V&&!uu(V.status)&&L.push(Q)}l=[...L,...D]}let u=c-l.length,f=r===null,p=r??Date.now(),m=p-s,h=!f&&i!==null&&i!=="end_turn"?i:null,y=h==="amended",b=y?`amended \xB7 ${Ln(m)}`:`stopped (${h}) \xB7 ${Ln(m)}`,v;if(c===0)h!==null?v=b:v=f?`thinking \xB7 ${Ln(m)}`:`thought \xB7 ${Ln(m)}`;else{let J=c===1?"tool":"tools",D=h!==null?b:f?Ln(m):`took ${Ln(m)}`,L=[`${c} ${J}`,D];f&&d&&u>0&&L.push(`${u} hidden`),v=L.join(" \xB7 ")}let S=c===0&&f,x=y?"tool-status-cancelled":"tool-status-fail",F=[{prefix:"\u2699 ",prefixStyle:S?"tool-status-running":h!==null?x:"tool",body:v,bodyStyle:S?"tool-status-running":h!==null?x:"dim"}],j=[null];for(let J of l){let D=n.get(J);if(D){let L=qo(D,p);if(F.push(...L),j.push(...L.map(()=>J)),o?.has(J)){let U=xg(D);F.push(...U),j.push(...U.map(()=>J))}}}return{lines:F,rowOwners:j}}async function F0(t,e,n,s,r,i,o){let a=await O0(t,e,n,s,o);if(!a)return t.grabInput(!1),null;let c=a.sessionId==="__new__"?"Starting new session\u2026":"Resuming session\u2026",d=B0(t,c);d.write(c);let l=n.isLocal?async()=>(await Mt(await we())).wsUrl:n.wsUrl,u=["acp.v1",`hydra-acp-token.${n.token}`],f=null,p=null,m=new Ji({url:l,subprotocols:u,onConnect:async g=>{g||f&&await f()},onDisconnect:g=>{p&&p(g)},log:g=>Ft({src:"resilient-ws",line:g})}),h=new _t(m);await m.start(),h.onNotification(Oa,g=>{let w=$p.safeParse(g);w.success&&d.applyProgress(w.data)});let y=[],b=null,v=!1,S=!1,x=(g,w)=>{g&&(b?b(g,w):y.push({event:g,rawUpdate:w}))},T,_=g=>{g!==T&&(T=g,g!==void 0&&I.appendLines([{prefix:" ",body:`\u2500\u2500 T${g} \u2500\u2500`,bodyStyle:"dim"}]))},F=null,j=null,J=!1,D=0,L=0,U=!1,Q=!1,V,be=null,Y=null,ye=null,Qe=()=>setInterval(()=>{if(be===null||de===null)return;let g=ye===null?0:Date.now()-ye;de.setBanner({elapsedMs:Date.now()-be,stalled:g>=P0}),un()},1e3),qs=!1,At=g=>{let w=L;L=Math.max(0,L+g);let k=typeof de<"u"&&de!==null;w===0&&L>0?(Q=!1,be=Date.now(),ye=Date.now(),Z?.setTurnRunning(!0),k&&de.setBanner({status:"busy",elapsedMs:0,stalled:!1}),Y===null&&k&&(Y=Qe())):w>0&&L===0?(Q=!1,be=null,ye=null,Z?.setTurnRunning(!1),Y!==null&&(clearInterval(Y),Y=null),k&&de.setBanner({status:"ready",elapsedMs:void 0,stalled:!1})):L>0&&Q&&(Q=!1,k&&de.setBanner({status:"busy",stalled:!1}))},de=null,Z=null,Oe,wn=null,Te=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"]),Dn=g=>{let{update:w}=g??{},k=_n(w,{cwd:yt});L0(w,k),ye=Date.now();let C=w?.sessionUpdate;if(typeof C=="string"&&!Te.has(C)){let A=w??{};typeof A.messageId=="string"&&(Oe=A.messageId)}if(C==="prompt_received"?At(1):k?.kind==="turn-complete"&&(At(-1),J=!0),C==="permission_resolved"){ds(w);return}if(C==="hydra_compaction"){Vt(w);return}if(C==="clarifier_question_asked"){let A=w,E=typeof A.question?.question=="string"?A.question.question:"",B=E.length>50?E.slice(0,49)+"\u2026":E;I.notify(B?`new question: ${B} \u2014 ^Q to view`:"new clarifier question \u2014 ^Q to view");return}C==="clarifier_question_answered"||C==="clarifier_question_dismissed"||(x(k,w),Lr(w))};h.onNotification("session/update",g=>{if(!v){if(wn!==null){wn.push(g);return}Dn(g)}}),h.onNotification("hydra-acp/session/closed",()=>{if(v)return;L>0&&At(-L),typeof de<"u"&&de!==null&&de.setBanner({status:"cold",elapsedMs:void 0}),f&&f().catch(w=>{Ft({src:"reconnect",step:"auto-resurrect-fail",message:w.message})})});let Ge=new Map,He=200,Fr=0,sn=!1,rn=4e3;h.onNotification("hydra-acp/prompt_queue/added",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;if(typeof w._meta?.["hydra-acp"]?.amending=="string"){let C=w.messageId,A=w.prompt,E=setTimeout(()=>{v||(Ge.delete(C),kt.set(C,zn(C,A)),de&&Z&&sr())},He);Ge.set(C,E)}else kt.set(w.messageId,zn(w.messageId,w.prompt)),de&&Z&&sr();if(ot!==void 0&&w.originator?.clientId===ot){let C=Et.shift();C&&(C.messageId=w.messageId,Jn.set(w.messageId,C))}}),h.onNotification("hydra-acp/prompt_queue/updated",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string"||!kt.has(w.messageId))return;kt.set(w.messageId,zn(w.messageId,w.prompt));let k=Jn.get(w.messageId);if(k){let C=Array.isArray(w.prompt)?w.prompt:[],A="",E=[];for(let B of C){if(!B||typeof B!="object")continue;let O=B;O.type==="text"&&typeof O.text=="string"?A+=O.text:O.type==="image"&&typeof O.data=="string"&&typeof O.mimeType=="string"&&E.push({data:O.data,mimeType:O.mimeType,sizeBytes:Math.floor(O.data.length*3/4)})}k.text=A,k.attachments=E}de&&Z&&sr()}),h.onNotification("hydra-acp/prompt_queue/removed",g=>{if(v)return;let w=g??{};if(typeof w.messageId!="string")return;w.reason==="started"&&(V=w.messageId);let k=Ge.get(w.messageId);k!==void 0&&(clearTimeout(k),Ge.delete(w.messageId)),kt.delete(w.messageId)&&de&&Z&&sr();let A=Jn.get(w.messageId);A&&(Jn.delete(w.messageId),w.reason==="started"&&(A.flushed=!0,x({kind:"user-text",text:A.displayText,attachments:A.attachments}),xn=A))}),h.onNotification("hydra-acp/cancel_failed",g=>{if(v)return;let w=g??{};if(!(typeof de<"u"&&de!==null))return;Fr=Date.now(),sn=!0;let C=typeof w.code=="number"?` (${w.code})`:"",A=typeof w.message=="string"&&w.message.length>0?`: ${w.message}`:"";de.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`cancel rejected by agent${C}${A} \u2014 this agent build may not support cancellation. Cancel again to force-stop (restarts the agent).`,bodyStyle:"tool-status-fail"}])}),h.onNotification("hydra-acp/prompt/amended",g=>{if(v)return;let w=g??{};if(typeof w.cancelledMessageId!="string")return;let k=w.cancelledMessageId;In.add(k),xn!==null&&xn.messageId!==void 0&&xn.messageId===k&&(x({kind:"turn-complete",stopReason:"cancelled",amended:!0}),xn=null,In.delete(k))});let Vt=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)}},ds=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}),Or(k,C?{outcome:C}:void 0)},Se=null,Or=(g,w)=>{if(!Se||Se.toolCallId&&g&&Se.toolCallId!==g)return;let k=Se.resolve;Se=null,I.setPermissionPrompt(null),k(w??{outcome:{outcome:"cancelled"}})},Lr=g=>{if(!Se?.toolCallId)return;let w=g??{};w.sessionUpdate!=="tool_call"&&w.sessionUpdate!=="tool_call_update"||w.toolCallId===Se.toolCallId&&(!w.status||w.status==="pending"||Or(w.toolCallId,void 0))},Ws=()=>{if(!Se){I.setPermissionPrompt(null);return}I.setPermissionPrompt({title:Se.title,detail:Se.detail,options:Se.options.map(g=>({label:g.name})),selectedIndex:Se.selectedIndex})},on=g=>{if(!Se)return;let{options:w,resolve:k}=Se;if(Se=null,I.setPermissionPrompt(null),g===null){k({outcome:{outcome:"cancelled"}});return}k({outcome:{outcome:"selected",optionId:g}})};h.onRequest("session/request_permission",async g=>{if(v)return{outcome:{outcome:"cancelled"}};if(s.dangerouslySkipPermissions)return Pr(g);let w=g??{},C=(Array.isArray(w.options)?w.options:[]).map(G=>({optionId:G.optionId,name:xe(G.name??""),...G.kind!==void 0?{kind:G.kind}:{}})),A=w.toolCall?.title??w.toolCall?.name??"tool",E=xe(A),B=xe(Py(Ey(g))),O=w.toolCall?.toolCallId;return C.length===0?(I.appendLines([{prefix:"\u{1F512} ",body:`Permission requested \xB7 ${E} \xB7 (no options offered, cancelling)`,bodyStyle:"tool-status-fail"}]),{outcome:{outcome:"cancelled"}}):new Promise(G=>{Se={title:E,detail:B,options:C,selectedIndex:0,resolve:G,toolCallId:O},Ws()})}),h.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}}));let zs,Br,ct=!0,cs=!1;try{let g=await h.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}});Br=g?.agentInfo?.name,g?.agentCapabilities?.promptCapabilities?.image===!1&&(ct=!1),cs=qt(g?._meta??void 0).prompt?.amending===!0}catch{}let Ce=a.sessionId,an=a.agentId,yt=a.cwd,Xi,ot,ls,Yt,bn,wt,Nr,us,Dr,dn,Js=!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:{[ht]:g}}:{}},k=await vy({request:()=>h.request("session/new",w),showBanner:(E,B,O)=>Sy(t,E,B,O,{authenticate:G=>h.request("authenticate",{methodId:G})}),resolveOnboarding:async E=>{if(E)try{return(await tu(n)).find(G=>G.id===E)?.onboarding}catch{return}},fallbackAgentId:s.agentId});if(k.kind==="cancel")return t.grabInput(!1),m.close().catch(()=>{}),null;if(k.kind==="back"){t.grabInput(!1),m.close().catch(()=>{});let E={...s};return delete E.sessionId,delete E.forceNew,delete E.resume,delete E.agentId,E}let C=k.result;d.write(c),Ce=C.sessionId,r.sessionId=Ce,r.readonly=!1;let A=qt(C._meta??void 0);A.clientId&&(ot=A.clientId),zs=A.upstreamSessionId,A.agentId&&(an=A.agentId),A.cwd&&(yt=A.cwd),A.title&&(Xi=A.title),ls=A.currentModel,Yt=A.currentMode,Dr=A.currentUsage,dn=A.turnStartedAt,A.availableCommands&&(bn=ud(A.availableCommands)),A.availableModes&&(wt=A.availableModes),Nr=eb(C.configOptions),us=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 h.request("session/attach",{sessionId:a.sessionId,historyPolicy:"full",clientInfo:{name:"hydra-acp-tui",version:pe},...Object.keys(g).length>0?{_meta:{[ht]:g}}:{}});Ce=w.sessionId,w.clientId&&(ot=w.clientId),r.sessionId=Ce,r.readonly=s.readonly===!0;let k=qt(w._meta??void 0);Js=k.resurrected===!0,zs=k.upstreamSessionId,k.agentId&&(an=k.agentId),k.cwd&&(yt=k.cwd),k.title&&(Xi=k.title),ls=k.currentModel,Yt=k.currentMode,Dr=k.currentUsage,dn=k.turnStartedAt,k.availableCommands&&(bn=ud(k.availableCommands)),k.availableModes&&(wt=k.availableModes),Nr=eb(w.configOptions),us=k.queue}let fs=$.tuiHistoryFile(Ce),Ks=$.globalTuiHistoryFile(),Ot=await Co(fs).catch(()=>[]),me=await Co(Ks).catch(()=>[]);me.length>e.tui.promptHistoryMaxEntries&&(me=me.slice(me.length-e.tui.promptHistoryMaxEntries));let Qt=[...Ot],ke=new is({history:Va(me,Qt)});Z=ke;let cn=!1,Vs=(g,w)=>{let k=g.replace(/\n+$/,"");if(k.length===0)return;let C=(w??g).replace(/\n+$/,""),A=Ao(Ot,k),E=A!==Ot;Ot=A,Qt=Ao(Qt,C);let B=Ao(me,k,e.tui.promptHistoryMaxEntries),O=B!==me;me=B,ke.setHistory(Va(me,Qt)),E&&gr(fs,Ot).catch(()=>{}),O&&Mm(Ks,k).catch(()=>{})};L>0&&ke.setTurnRunning(!0);let bt=null,Lt=null;Pw(Mw(e.tui.ambiguousWidth,process.env)),Ag(e.tui.diffContextLines);let ps=!1,I,Zi=()=>{ps&&(ps=!1,I.start())},eo=()=>{ps||(ps=!0,I.stop(),process.kill(process.pid,"SIGTSTP"))};process.platform!=="win32"&&process.on("SIGCONT",Zi),I=new dc({term:t,dispatcher:ke,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"?eo:void 0,onBlockClick:(g,w)=>{Pb(g,w)},onBlockDoubleClick:(g,w)=>Eb(g,w),onBlockVisible:g=>{Ab(g)},onMouse:g=>{if(g.kind==="press"&&g.button==="left"){let k=I.bannerHitAt(g.x,g.y);if(k!==null){if(k==="mode"){qr(!0);return}let C=k==="pick"?{type:"switch-session"}:k==="detach"?{type:"exit"}:{type:"show-help"};if(s.readonly===!0&&df(C))return;gs(C);return}}if(g.kind!=="press"||g.button!=="middle")return;let w={type:"attachment-request",source:"primary"};s.readonly===!0&&df(w)||gs(w)},onKey:g=>{for(let w of g){if(U&&la(w)||Se&&aa(w)||gc(w)||Xe(w)||ae(w)||so(w)||ia(w)||Ys(w))continue;if(w.type==="key"&&w.name==="escape"&&I.isScrolledBack()){I.scrollToBottom();continue}if(w.type==="attachment-paths"){Tt(w.paths);continue}let k=ke.feed(w);for(let C of k)s.readonly===!0&&df(C)||gs(C)}vn(),I.setBannerSearchIndicator(ke.state().historySearchQuery),I.setAttachments(ke.state().attachments),I.refreshPrompt()}}),de=I,I.setStickyBottomKey("plan");let to=[{name:"/help",description:"Show TUI built-in commands"},{name:"/quit",description:"Exit the TUI"},{name:"/clear",description:"Clear scrollback"},{name:"/sessions",description:"List sessions"},{name:"/resume",description:"Switch sessions (open the picker)"},{name:"/session",description:"Switch session: /session <id|next|prev> (no arg opens picker)"},{name:"/rename",description:"Rename this session (alias for /hydra title): /rename [title]"},{name:"/model",description:"Switch model: /model <model-id>"},{name:"/agent",description:"Switch agent via config option: /agent <agent-id>"},{name:"/btw",description:"Run an ancillary forked session: /btw <prompt>"},{name:"/export",description:"Export this session as a markdown transcript: /export [path]"}],Hn=bn??[],De=wt??[],no=Nr??[],sa=()=>no.find(g=>g.id==="agent"),Bt=()=>{let g=new Set,w=[];for(let k of[...to,...Hn])g.has(k.name)||(g.add(k.name),w.push(k));return w},ra=()=>{let g=ke.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=Bt().filter(E=>E.name.startsWith(C));return A.length===1&&A[0]?.name===C?[]:A},Ue=[],vn=()=>{let g=ra();if(g.length>0){Ue=[],I.setCompletions(g);return}I.setCompletions(Ue)},ia=g=>{if(g.type!=="key"||g.name!=="tab")return Ue.length>0&&(Ue=[]),!1;let w=ra();if(I.isOverlayOpen()&&w.length===0)return I.toggleFocusedPane(),!0;if(w.length>0){Ue=[];let k=ke.state().buffer[0]??"",C=Bw({matches:w.map(A=>A.name),firstLine:k});return C===null||ke.replaceFirstLine(C),!0}return oa()},oa=()=>{let g=ke.state(),w=g.buffer[g.row]??"",k=Jw(w,g.col);if(k===null)return!1;let C=Kw(k.token,yt);return C===null?!1:(C.replacement!==k.token&&ke.replaceRangeOnCurrentLine(k.start,g.col,C.replacement),Ue=C.candidates.length>1?C.candidates.map(A=>({name:A})):[],!0)},Ys=g=>!I.isOverlayOpen()||g.type!=="key"||g.name!=="escape"&&g.name!=="ctrl-c"?!1:(F&&(F.cancel(),F=null,j=null),I.closeBtwOverlay(),!0),so=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},aa=g=>{if(!Se)return!1;let w=Se.options;if(g.type==="key")switch(g.name){case"up":return Se.selectedIndex=Math.max(0,Se.selectedIndex-1),Ws(),!0;case"down":return Se.selectedIndex=Math.min(w.length-1,Se.selectedIndex+1),Ws(),!0;case"enter":{let k=w[Se.selectedIndex];return k&&on(k.optionId),!0}case"escape":case"ctrl-c":return on(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&&on(C.optionId),!0}return!0},Qs=an||Br||"?",lt={...Dr??{}};d.finalize(),I.start({skipFullscreen:!0}),I.setHideThoughts(!i.showThoughts),I.setSessionbar({agent:Qs,cwd:yt,sessionId:Ce,title:Xi,model:ls,usage:{...lt}}),Yt&&I.setBanner({currentMode:Yt}),Vo().then(g=>{g&&I.notify(`\u2728 ${Yo(g)}`,3e4)}).catch(()=>{});let at=null,da=new Promise(g=>{at=g}),ca=()=>{h.notify("session/cancel",{sessionId:Ce}).catch(()=>{})},Hr=()=>{de!==null&&L===1&&(Q=!0,de.setBanner({status:"cancelling",elapsedMs:void 0,stalled:!1}))},Un=()=>{if(bt){bt.cancel(),Hr();return}if(L>0){ca(),Hr();return}Gs()},Gs=()=>{St(0)},Ur=()=>{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]],...M0]},jn=()=>{if(I.isHelpPromptActive()){I.setHelpPrompt(null);return}I.setHelpPrompt({title:"Hotkeys",entries:Ur(),hint:"any key dismisses \xB7 /help lists commands"})},qn=()=>{U=!1,I.setCompactionPrompt(null),I.setCompactionIndicator("compaction queued...");let g=Ce;fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(g)}/compact`,{method:"POST",headers:{Authorization:`Bearer ${n.token}`}}).catch(()=>{})},ms=()=>{U=!1,I.setCompactionPrompt(null)},ro=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})},la=g=>{if(!U)return!1;if(g.type==="key"){if(g.name==="escape")return ms(),!0;if(g.name==="up")return ro(-1),!0;if(g.name==="down")return ro(1),!0;if(g.name==="enter"){let w=I.compactionPromptSpec();return w?.options[w.selectedIndex]?.key==="y"?qn():ms(),!0}}if(g.type==="char"){let w=g.ch.toLowerCase();if(w==="y"||w==="1")return qn(),!0;if(w==="n"||w==="2")return ms(),!0}return!0},gc=g=>I.isHelpPromptActive()?(g.type==="key"&&g.name==="ctrl-g",I.setHelpPrompt(null),!0):!1,Xs=["tools","plan","thoughts","diffs","mouse","enter"],Nt=0,Dt=null,hs=[],Zs=[],vt=[],er=0,Sn=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}},kn=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"}},Rt=()=>({title:"Session options",options:Xs.map(g=>({label:kn(g),value:Sn(g)})),selectedIndex:Nt}),tr=()=>{I.isOptionsPromptActive()&&Dt===null&&I.setOptionsPrompt(Rt())},ua=()=>{if(I.isOptionsPromptActive()){I.setOptionsPrompt(null);return}Nt=0,I.setOptionsPrompt(Rt())},Wn=()=>{if(Dt===null)return;let g=A0(Dt,hs,vt,er);I.setOptionsPrompt(g)},R=()=>{Dt=null,hs=[],Zs=[],vt=[],er=0,I.setOptionsPrompt(null)},M=async()=>{if(Dt!==null){R();return}try{let w=await h.request(Zy,{sessionId:Ce}),k=k0(w.questions??[]);if(k.length===0){I.notify("no open questions");return}let C=x0(k);Dt=C,er=0,hs=C.map(A=>I0(A.representative)),Zs=C.map(()=>!1),vt=C.map(()=>!1),Wn()}catch(g){I.notify("clarifier unavailable"),Ft({src:"questions",step:"list_failed",error:g.message})}},N=g=>{switch(g){case"tools":i.toolsExpanded=!i.toolsExpanded,z.clear(),ce.clear(),kb();break;case"plan":i.planExpanded=!i.planExpanded,Ae=null,bs();break;case"thoughts":i.showThoughts=!i.showThoughts,I.setHideThoughts(!i.showThoughts);break;case"diffs":i.showFileUpdates=i.showFileUpdates==="diff"?"edit":"diff",Vn.clear(),Rb();break;case"mouse":{let w=!I.isMouseEnabled();I.setMouseEnabled(w),i.mouseEnabled=w;break}case"enter":i.defaultEnterAction=i.defaultEnterAction==="amend"?"enqueue":"amend";break}tr()},ee=g=>{(async()=>{try{switch(g){case"tools":case"plan":I.notify(`${kn(g)} is session-only \u2014 not saved`);return;case"thoughts":await lo("showThoughts",i.showThoughts);break;case"diffs":await lo("showFileUpdates",i.showFileUpdates);break;case"mouse":await lo("mouse",i.mouseEnabled);break;case"enter":await lo("defaultEnterAction",i.defaultEnterAction);break}I.notify(`saved default: ${kn(g)} ${Sn(g)}`)}catch(w){I.notify(`save failed: ${w instanceof Error?w.message:String(w)}`)}})()},ae=g=>{if(Dt!==null||!I.isOptionsPromptActive())return!1;if(g.type==="key")switch(g.name){case"up":return Nt=Math.max(0,Nt-1),tr(),!0;case"down":return Nt=Math.min(Xs.length-1,Nt+1),tr(),!0;case"enter":{let w=Xs[Nt];return w&&N(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=Xs[w];return k&&(Nt=w,N(k)),!0}if(g.ch==="s"||g.ch==="S"){let w=Xs[Nt];return w&&ee(w),!0}}return!0},Xe=g=>{if(Dt===null)return!1;let w=E0(g,!0,Dt,hs,Zs,vt,er,Ce);switch(w.type){case"noop":return!0;case"row":return er=w.selectedRow,Wn(),!0;case"cycle":return hs[w.selectedRow]=w.newValueIndex,Zs[w.selectedRow]=!0,vt[w.selectedRow]=!1,Wn(),!0;case"dismiss-toggle":{let k=w.selectedRow;return vt[k]?(vt[k]=!1,Zs[k]=!1):(vt[k]=!0,Zs[k]=!0),Wn(),!0}case"discard":return R(),!0;case"save":{let k=w.dispatches;return R(),k.length===0||(async()=>{let C=0,A=0,E=0;for(let O of k)try{await h.request(O.method,O.params),O.type==="dismiss"?A++:C++}catch(G){E++,Ft({src:"questions",step:"dispatch_failed",method:O.method,error:G.message})}let B=[];C>0&&B.push(`${C} answered`),A>0&&B.push(`${A} dismissed`),E>0&&B.push(`${E} failed`),B.length>0&&I.notify(`clarifier: ${B.join(", ")}`)})(),!0}}return!1},ve=()=>{v=!0,F?(F.cancel(),F=null,j=null):j!==null&&(On(n,j).catch(()=>{}),j=null),process.off("SIGINT",Un),process.platform!=="win32"&&process.off("SIGCONT",Zi),Y!==null&&(clearInterval(Y),Y=null);for(let g of Ge.values())clearTimeout(g);Ge.clear(),I.clearWindowTitle(),I.stop({keepFullscreen:!0}),gr(fs,Ot).catch(()=>{}),m.close().catch(()=>{})},St=(g=0)=>{ve(),at&&(at(null),at=null),g!==0&&process.exit(g)},Ht=async()=>{if(!at)return;F?(F.cancel(),F=null,j=null):j!==null&&(On(n,j).catch(()=>{}),j=null);let g=ke.state().buffer.join(`
189
+ `);g.replace(/\s+$/,"").length>0&&Vs(g),I.pauseRepaint(),I.stop({keepFullscreen:!0}),gr(fs,Ot).catch(()=>{});let w=null,k=null;for(;w===null;){let B=await Fn(n,{includeNonInteractive:!0}),O=await of(t,{cwd:yt,sessions:B,config:e,target:n,currentSessionId:Ce,prefs:o});if(O.kind==="abort"){I.start({skipFullscreen:!0}),I.resumeRepaint();return}if(O.kind==="exit"){St(0);return}if(O.kind==="new"){w={choice:O,sessions:B};break}if(O.kind==="fork"){let ue=await ib(t,n,O,B);if(ue.kind==="cancel"){I.start({skipFullscreen:!0}),I.resumeRepaint();return}if(ue.kind==="back")continue;w={choice:{kind:"attach",sessionId:ue.ctx.sessionId,...ue.ctx.agentId?{agentId:ue.ctx.agentId}:{}},sessions:B},k={readonly:!1,cwd:ue.ctx.cwd},ue.ctx.resumeHint!==void 0&&(k.resumeHint=ue.ctx.resumeHint);break}let G=B.find(ue=>ue.sessionId===O.sessionId);if(!(G!==void 0&&!!G.importedFromMachine&&!G.upstreamSessionId&&O.readonly!==!0)){if(n.isLocal&&G&&!G.importedFromMachine&&O.readonly!==!0&&!(await Go(G.cwd)).ok){let Le=await _r(t,G,{defaultCwd:Je(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(Le.kind==="cancel"){I.start({skipFullscreen:!0}),I.resumeRepaint();return}if(Le.kind==="back")continue;w={choice:O,sessions:B},k={readonly:!1,cwd:Le.path,resumeHint:{agentId:O.agentId??G.agentId??"",cwd:Le.path,upstreamSessionId:""}};break}w={choice:O,sessions:B};break}let Pe={...s,readonly:!1},le=await rb(t,G,O,Pe);if(le.kind==="cancel"){I.start({skipFullscreen:!0}),I.resumeRepaint();return}le.kind!=="back"&&(w={choice:O,sessions:B},k={readonly:Pe.readonly===!0,cwd:le.ctx.cwd},le.ctx.resumeHint!==void 0&&(k.resumeHint=le.ctx.resumeHint))}let{choice:C}=w,A=at;if(at=null,process.off("SIGINT",Un),m.close().catch(()=>{}),C.kind==="new"){let{sessionId:B,...O}=s,G={...O,cwd:C.cwd??yt,forceNew:!0,readonly:!1};C.prompt!==void 0&&(G.initialPrompt=C.prompt),A(G);return}if(C.kind!=="attach")return;let E={...s,sessionId:C.sessionId,cwd:k?.cwd??yt,readonly:k?.readonly??C.readonly===!0};C.agentId!==void 0&&(E.agentId=C.agentId),k?.resumeHint!==void 0?E.resumeHint=k.resumeHint:delete E.resumeHint,A(E)},jr=async(g="next")=>{if(!at)return;let k=(await Fn(n)).filter(Pe=>Pe.status==="live");if(k.length<=1)return;let C=k.findIndex(Pe=>Pe.sessionId===Ce),B=((C===-1?0:C)+(g==="prev"?-1:1)+k.length)%k.length,O=k[B],G=at;at=null,process.off("SIGINT",Un),m.close().catch(()=>{});let Ne={...s,sessionId:O.sessionId,cwd:yt,readonly:!1};O.agentId!==void 0&&(Ne.agentId=O.agentId),G(Ne)},nr=async g=>{if(!at)return;let w=await Fn(n,{includeNonInteractive:!0}),k=g.trim();if(!k){I.notify("usage: /session <id|next|prev>");return}let C=k.startsWith(Zt)?[k]:[k,Zt+k],A=w.find(O=>C.includes(O.sessionId));if(!A){let O=w.filter(G=>C.some(Ne=>G.sessionId.startsWith(Ne)));if(O.length===1)A=O[0];else if(O.length>1){I.notify(`ambiguous session id: ${k} (${O.length} matches)`);return}}if(!A){I.notify(`no session matches: ${k}`);return}if(A.sessionId===Ce){I.notify("already on that session");return}let E=at;at=null,process.off("SIGINT",Un),m.close().catch(()=>{});let B={...s,sessionId:A.sessionId,cwd:A.cwd??yt,readonly:A.status!=="live"};A.agentId!==void 0&&(B.agentId=A.agentId),delete B.resumeHint,E(B)},gs=g=>{switch(g.type){case"send":i.defaultEnterAction==="amend"?pa(g.text,g.attachments,g.displayText):io(g.text,g.attachments,g.displayText);return;case"amend":i.defaultEnterAction==="amend"?io(g.text,g.attachments,g.displayText):pa(g.text,g.attachments,g.displayText);return;case"queue-edit":{let w=fa(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});h.request("hydra-acp/prompt/update",{sessionId:Ce,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=fa(g.index);if(!w)return;h.request("hydra-acp/prompt/cancel",{sessionId:Ce,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()){F&&(F.cancel(),F=null,j=null),I.closeBtwOverlay();return}if(g.prefill&&bt){let w=kt.size===0,k=ke.state().buffer.every(C=>C==="");w&&k&&(Lt={text:bt.text,attachments:bt.attachments})}bt?bt.cancel():L>0&&ca(),Hr();return}case"exit":Gs();return;case"plan-toggle":qr(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":Ht().catch(()=>{});return;case"next-live-session":jr().catch(()=>{});return;case"toggle-options":ua();return;case"toggle-questions":M();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":jn();return;case"escalate-search":I.enterScrollbackSearch(),I.updateScrollbackSearchTerm(g.query);return;case"attachment-request":ys(g.source);return}},Tt=async g=>{if(!ct){I.notify("agent does not accept image attachments");return}let w=0;for(let k of g){if(k.startsWith("data:")){let A=Bu(k);if(!A){I.notify("unsupported data: URI");continue}if(A.sizeBytes>Bn){I.notify(`image too large (${nn(A.sizeBytes)}, max ${nn(Bn)})`);continue}ke.addAttachment({mimeType:A.mimeType,data:A.data,name:"pasted image",sizeBytes:A.sizeBytes}),w++;continue}let C=Xo(k);if(!C){I.notify(`unsupported image type: ${$r.basename(k)}`);continue}try{let A=await af.readFile(k);if(A.length>Bn){I.notify(`image too large (${nn(A.length)}, max ${nn(Bn)})`);continue}ke.addAttachment({mimeType:C,data:A.toString("base64"),name:$r.basename(k),sizeBytes:A.length}),w++}catch(A){I.notify(`cannot read ${$r.basename(k)}: ${A.message}`)}}w>0&&(I.setAttachments(ke.state().attachments),I.refreshPrompt())},ys=async(g="clipboard")=>{let w=g==="primary"?await mw():await pw();if(!w.ok){I.notify(w.reason);return}if(w.kind==="image"){if(!ct){I.notify("agent does not accept image attachments");return}ke.addAttachment(w.attachment),I.setAttachments(ke.state().attachments),I.refreshPrompt();return}let k=ke.feed({type:"paste",text:w.text});for(let C of k)gs(C);I.refreshPrompt()},ut=g=>g.attachmentCount>0?`${g.text} \xB7 \u{1F4CE}\xD7${g.attachmentCount}`:g.text,zn=(g,w)=>{let k=Array.isArray(w)?w:[],C="",A=0;for(let E of k){if(!E||typeof E!="object")continue;let B=E;B.type==="text"&&typeof B.text=="string"?C+=B.text:B.type==="image"&&(A+=1)}return{messageId:g,text:xe(C),attachmentCount:A}},kt=new Map,Et=[],Jn=new Map,In=new Set,xn=null,sr=()=>{let g=[...kt.values()],w=g.map(ut);I.setQueuedPrompts(w),I.setBanner({queued:g.length}),ke.setQueue(g.map(k=>k.text))},fa=g=>[...kt.values()][g]?.messageId;if(us&&us.length>0){for(let g of us){if(g.position===0){V=g.messageId;continue}kt.set(g.messageId,zn(g.messageId,g.prompt))}kt.size>0&&sr()}let io=(g,w,k)=>{I.scrollToBottom(),!Pt(g)&&(Vs(g,k),oo(g,w,k))},pa=(g,w,k)=>{if(I.scrollToBottom(),Pt(g))return;if(Vs(g,k),!cs||V===void 0){oo(g,w,k);return}let C=V,A=[];g.length>0&&A.push({type:"text",text:g});for(let O of w)A.push({type:"image",data:O.data,mimeType:O.mimeType});let E={text:g,displayText:k??g,attachments:w,flushed:!1};Et.push(E);let B=()=>{let O=Et.indexOf(E);O>=0&&Et.splice(O,1),E.messageId!==void 0&&Jn.delete(E.messageId)};h.request("hydra-acp/prompt/amend",{sessionId:Ce,targetMessageId:C,prompt:A}).then(O=>{let G=O;if(G.amended&&G.reason==="ok"){At(1);return}if(B(),G.reason==="target_completed"){I.notify("previous response finished \u2014 press Enter to send as a new turn"),ke.setBuffer(g,w),I.refreshPrompt();return}if(G.reason==="target_cancelled"){I.notify("amend skipped \u2014 previous turn was cancelled"),ke.setBuffer(g,w),I.refreshPrompt();return}if(G.reason==="target_not_found"){I.notify("amend skipped \u2014 no matching prompt"),ke.setBuffer(g,w),I.refreshPrompt();return}}).catch(O=>{B(),I.notify(`amend failed: ${O.message}`),ke.setBuffer(g,w),I.refreshPrompt()})},qr=async g=>{if(De.length===0){I.notify("no modes advertised by agent");return}let w=I.currentModeId(),k=De.findIndex(E=>E.id===w),C=k===-1?0:(k+1)%De.length,A=De[C]?.id;if(A){I.setBanner({currentMode:A});try{await h.request("session/set_mode",{sessionId:Ce,modeId:A})}catch(E){I.notify(`set_mode failed: ${E.message}`)}}},Pt=g=>{let w=g.replace(/\s+$/,"");if(!w.startsWith("/")||w.includes(`
190
+ `))return!1;let k=w.indexOf(" ");switch(k===-1?w:w.slice(0,k)){case"/quit":case"/exit":return Gs(),!0;case"/clear":return st.clear(),ws.clear(),ln.length=0,se=null,Ee=null,Me=null,Kn.clear(),Vn.clear(),P.clear(),z.clear(),te.clear(),ie.clear(),I.clearScrollback(),!0;case"/help":{let A=[{prefix:" ",body:"Built-in commands:",bodyStyle:"system"}];for(let E of to)A.push({prefix:" ",body:` ${E.name.padEnd(12)} ${E.description??""}`,bodyStyle:"info"});if(Hn.length>0){A.push({prefix:" ",body:"Agent commands:",bodyStyle:"system"});for(let E of Hn)A.push({prefix:" ",body:` ${E.name.padEnd(12)} ${E.description??""}`,bodyStyle:"info"})}return I.appendLines(A),!0}case"/agent":{let A=k===-1?"":w.slice(k+1).trim(),E=sa();if(!E)return I.appendLines([{prefix:" ",body:"no agent config option advertised for this session",bodyStyle:"info"}]),!0;if(!A){let B=[{prefix:" ",body:"Available agents:",bodyStyle:"system"}];for(let O of E.options){let G=O.value===E.currentValue?"* ":" ";B.push({prefix:" ",body:`${G}${O.value.padEnd(16)} ${O.name}`,bodyStyle:"info"})}return I.appendLines(B),!0}return E.options.some(B=>B.value===A)?A===E.currentValue?(I.notify(`already on agent ${A}`),!0):(I.notify(`switching to ${A}\u2026`),h.request("session/set_config_option",{sessionId:Ce,configId:"agent",value:A}).catch(B=>{I.notify(`set_config_option failed: ${B.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 Ht().catch(()=>{}),!0;case"/session":{let A=k===-1?"":w.slice(k+1).trim();return A?A==="next"||A==="prev"?(jr(A).catch(E=>{I.notify(`session ${A} failed: ${E.message}`)}),!0):(nr(A).catch(E=>{I.notify(`session switch failed: ${E.message}`)}),!0):(Ht().catch(()=>{}),!0)}case"/rename":{let A=k===-1?"":w.slice(k+1).trim(),E=A.length>0?`/hydra title ${A}`:"/hydra title";return Vs(w,w),oo(E,[],w),!0}case"/btw":{let A=k===-1?"":w.slice(k+1).trim();if(!A)return I.appendLines([{prefix:" ",body:"/btw requires a prompt",bodyStyle:"info"}]),!0;if(Ce==="__new__")return I.appendLines([{prefix:" ",body:"no active session to fork",bodyStyle:"info"}]),!0;D+=1;let E=D;F&&(F.cancel(),F=null);let B=null;j!==null&&!J?B=j:j!==null&&(On(n,j).catch(()=>{}),j=null),J=!1,I.openBtwOverlay(),I.setBtwOverlayStatus({label:"busy",style:"busy"});let O=new ec({getMaxWidth:()=>{let le=I.width();return le>0?le:void 0}});O.on("changed",()=>{I.setBtwOverlayContent(O.getLines())});let G={};O.append({sessionUpdate:"prompt_received",prompt:[{type:"text",text:A}]});let Ne=le=>{O.append({sessionUpdate:"agent_message_chunk",content:{type:"text",text:le}})},Pe={};return B!==null&&(Pe.reuseSessionId=B),sw(n,Ce,A,Pe).then(le=>{if(E!==D){le.cancel();return}F=le,j=le.sessionId,I.setBtwOverlayMeta({sessionId:le.sessionId}),le.on("event",ue=>{if(E===D)if(ue.kind==="update"){O.append(ue.update);let Le=_n(ue.update);if(Le&&Le.kind==="usage-update"){let ir=!1;Le.used!==void 0&&G.used!==Le.used&&(G.used=Le.used,ir=!0),Le.size!==void 0&&G.size!==Le.size&&(G.size=Le.size,ir=!0),Le.costAmount!==void 0&&G.costAmount!==Le.costAmount&&(G.costAmount=Le.costAmount,ir=!0),Le.costCurrency!==void 0&&G.costCurrency!==Le.costCurrency&&(G.costCurrency=Le.costCurrency,ir=!0),ir&&I.setBtwOverlayMeta({usage:{...G}})}}else ue.kind==="completed"?(I.setBtwOverlayStatus({label:"done",style:"done"}),F=null):ue.kind==="cancelled"?(I.setBtwOverlayStatus({label:"cancelled",style:"cancelled"}),F=null,j=null):ue.kind==="errored"&&(I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ne(`btw errored: ${ue.error.message}`),j!==null&&On(n,j).catch(()=>{}),F=null,j=null)})}).catch(le=>{if(E!==D)return;let ue=le instanceof Error?le.message:String(le);I.setBtwOverlayStatus({label:"errored",style:"errored"}),Ne(`btw startup failed: ${ue}`),I.appendLines([{prefix:" ",body:`btw startup failed: ${ue}`,bodyStyle:"tool-status-fail"}])}),!0}case"/export":{if(Ce==="__new__")return I.appendLines([{prefix:" ",body:"no active session to export",bodyStyle:"info"}]),!0;let A=k===-1?"":w.slice(k+1).trim(),E=Ce;return(async()=>{try{let B=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(E)}/transcript`,{headers:{Authorization:`Bearer ${n.token}`}});if(!B.ok){let ue=await B.text().catch(()=>"");I.appendLines([{prefix:" ",body:`/export failed: HTTP ${B.status} ${ue}`.trim(),bodyStyle:"info"}]);return}let O=await B.text(),G=new Date().toISOString().replace(/[:.]/g,"-"),Ne=`hydra-${et(E)}-${G}.md`,Pe=A.length>0?Je(A):Ne,le=$r.resolve(Pe);await af.mkdir($r.dirname(le),{recursive:!0}),await af.writeFile(le,O,{encoding:"utf8",mode:384}),I.appendLines([{prefix:" ",body:`Wrote ${le}`,bodyStyle:"system"}])}catch(B){I.appendLines([{prefix:" ",body:`/export failed: ${B.message}`,bodyStyle:"info"}])}})(),!0}default:return!1}},oo=async(g,w,k)=>{let C=[];g.length>0&&C.push({type:"text",text:g});for(let Pe of w)C.push({type:"image",data:Pe.data,mimeType:Pe.mimeType});At(1);let A={text:g,displayText:k??g,attachments:w,flushed:!1};Et.push(A),sn=!1;let E=!1,B=null,O=Pe=>{typeof de<"u"&&de!==null&&de.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:Pe,bodyStyle:"tool-status-fail"}])},G=!1;bt={text:g,attachments:w,cancel:()=>{if(sn){sn=!1,G=!0,O("force-stopping agent \u2014 turn aborted; resumes on your next message\u2026"),h.request("hydra-acp/session/force_cancel",{sessionId:Ce}).catch(le=>{O(`force-stop failed: ${le.message}`)});return}if(E)return;E=!0,h.notify("session/cancel",{sessionId:Ce}).catch(()=>{});let Pe=Date.now();B=setTimeout(()=>{bt!==null&&(Fr>=Pe||(sn=!0,O("cancel not acknowledged by agent \u2014 the turn is still running. Cancel again to force-stop (restarts the agent).")))},rn)}};let Ne;try{let Pe=await h.request("session/prompt",{sessionId:Ce,prompt:C});Pe&&typeof Pe.stopReason=="string"&&(Ne=Pe.stopReason)}catch(Pe){let le=Et.indexOf(A);le>=0&&Et.splice(le,1),A.messageId!==void 0&&Jn.delete(A.messageId),G?I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"turn force-stopped",bodyStyle:"tool-status-fail"}]):I.appendLines([{prefix:"\u2717 ",prefixStyle:"tool-status-fail",body:Pe.message,bodyStyle:"tool-status-fail"}])}finally{if(bt=null,B!==null&&(clearTimeout(B),B=null),At(-1),A.flushed&&xn===A){let Pe=A.messageId!==void 0&&In.has(A.messageId);Pe&&A.messageId!==void 0&&In.delete(A.messageId);let le={kind:"turn-complete"};Ne!==void 0&&(le.stopReason=Ne),Pe&&(le.amended=!0),x(le),xn=null}if(Lt!==null){let{text:Pe,attachments:le}=Lt;Lt=null,ke.state().buffer.every(Le=>Le==="")&&(ke.setBuffer(Pe,le),I.refreshPrompt())}}},st=new Map,Kn=new Map,Vn=new Map,ws=new Map,ln=[],Yn=0,Gt=`tools:${Yn}`,P=new Map,z=new Map,ce=new Set,q=new Map,te=new Map,ie=new Map,se=null,Ee=null,Me=null,Ze=null,Ae=null,ft=e.tui.maxToolItems,Wr=e.tui.maxPlanItems,zr=()=>({maxPlanItems:Ae??i.planExpanded?1/0:Wr}),bs=()=>{if(Ze===null)return;let g=Os(Ze,zr());g.length>0&&I.upsertLines("plan",[{body:""},...g])},Jr="",Qn=null,ao=0,gb=()=>{if(Qn===null)return;let g=I.width(),w=Ls(Jr,g>0?{maxWidth:g}:void 0);w.length!==0&&I.upsertLines(Qn,w)},yb=g=>{g.length!==0&&(Qn===null&&(I.ensureSeparator(),Qn=`agent:${ao}`,ao+=1,Jr=""),Jr+=g,gb())},vs=()=>{Qn=null,Jr=""},Kr="",rr=null,pf=0,wb=()=>({prefix:" ",body:"\u25B8 Thoughts",bodyStyle:"thought"}),bb=()=>{if(rr===null||Kr.length===0)return;let g=Bi(Kr);g.length!==0&&I.upsertLines(rr,g)},vb=g=>{let w=te.get(g);if(w===void 0)return[];let k=Bi(w.text);return w.workerTaskId&&k.unshift({prefix:" ",body:`[T${w.workerTaskId}] `,bodyStyle:"dim"}),k},Sb=(g,w)=>{g.length!==0&&(rr===null&&(I.ensureSeparator("thought"),rr=`thought:${pf}`,pf+=1,Kr=""),Kr+=g,te.set(rr,{text:Kr,workerTaskId:w}),bb())},Ss=()=>{rr=null,Kr=""},mf=g=>$0({...g,collapsedLimit:ft}),hf=g=>z.get(g)??i.toolsExpanded,un=()=>{if(se===null)return;let{lines:g,rowOwners:w}=mf({order:ln,states:st,startedAt:se,endedAt:Ee,stopReason:Me,expanded:hf(Gt),perToolExpanded:ce});I.upsertLines(Gt,g),q.set(Gt,w)},ma=g=>{let w=P.get(g);if(!w)return;let{lines:k,rowOwners:C}=mf({order:w.order,states:w.states,startedAt:w.startedAt,endedAt:w.endedAt,stopReason:w.stopReason,expanded:hf(g),perToolExpanded:ce});I.upsertLines(g,k),q.set(g,C)},kb=()=>{se!==null&&!P.has(Gt)&&un();for(let g of P.keys())ma(g)},yc=()=>{se!==null&&P.set(Gt,{order:[...ln],states:new Map(st),startedAt:se,endedAt:Ee??Date.now(),stopReason:Me,rowOwners:q.get(Gt)??[]})},gf=()=>{Yn+=1,Gt=`tools:${Yn}`,se=Date.now(),Ee=null,Me=null,un()};function Ib(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=E=>{if(typeof E=="string"){C.push({text:tt(E)});return}if(E&&typeof E=="object"){let B=E;typeof B.__hydraBlob=="string"&&C.push({hash:B.__hydraBlob})}};for(let E of k){if(!E||typeof E!="object")continue;let B=E;if(B.type==="content"&&B.content&&typeof B.content=="object"){let O=B.content;if(O.text!==void 0){A(O.text);continue}}if(B.type==="text"&&B.text!==void 0){A(B.text);continue}B.text!==void 0&&A(B.text)}return C.length>0?C:null}let yf=(g,w)=>{let k=w.map(E=>"text"in E?E.text:"").join(`
191
+ `);if(k.length===0)return;let{text:C,truncated:A}=Ig(k);g.resultText=C,g.resultTruncated=A},ha=new Set,xb=(g,w)=>{!w.some(C=>"hash"in C)||ha.has(g)||(ha.add(g),(async()=>{let C=await Promise.all(w.map(async E=>"text"in E?E:{text:await wc(E.hash)??""}));ha.delete(g);let A=st.get(g);if(!A)for(let E of P.values()){let B=E.states.get(g);if(B){A=B;break}}if(A){yf(A,C),st.has(g)&&un();for(let[E,B]of P)B.states.has(g)&&ma(E);I.repaintNow()}})().catch(()=>{ha.delete(g)}))},wf=(g,w,k,C,A,E,B,O,G,Ne)=>{let Pe=!st.has(g),le=st.get(g),ue=le??{initialTitle:w??"tool",latestTitle:w??"tool",status:k??"pending",startedAt:Date.now()};if(!le&&G!==void 0&&(ue.workerTaskId=G),le&&w!==void 0&&(ue.latestTitle=w),E!==void 0&&ue.detail===void 0&&(ue.detail=E),B!==void 0&&ue.detailFull===void 0&&(ue.detailFull=B),O!==void 0&&O.length>0&&(ue.locations=O),le&&k!==void 0&&(ue.status=k),le||(ue.status=k??"pending"),ue.endedAt===void 0&&uu(ue.status)&&(ue.endedAt=Date.now()),C!==void 0&&(ue.errorText=C),A!==void 0&&(ue.editDiff=A),Ne!==void 0){let Le=Ib(Ne);Le!==null&&(yf(ue,Le),Le.some(ir=>"hash"in ir)&&xb(g,Le))}st.set(g,ue),Pe&&(se===null&&(Yn+=1,Gt=`tools:${Yn}`,se=Date.now(),Ee=null,Me=null),ln.push(g))},wc=async g=>{try{let w=await h.request("hydra-acp/session/tool_content",{sessionId:Ce,hash:g});return typeof w?.content=="string"?w.content:null}catch{return null}},ga=new Set,Cb=(g,w)=>{ga.has(g)||w.oldRef===void 0&&w.newRef===void 0||(ga.add(g),(async()=>{let[k,C]=await Promise.all([w.oldRef?wc(w.oldRef.hash):Promise.resolve(w.oldText),w.newRef?wc(w.newRef.hash):Promise.resolve(w.newText)]);if(w.oldRef!==void 0&&k===null||w.newRef!==void 0&&C===null){ga.delete(g);let Ne=cu(w,"diff",{deferredStatus:"error"});Ne.length>0&&(I.upsertLines(`editdiff:${g}`,Ne),I.repaintNow());return}let E={...w.path!==void 0?{path:w.path}:{},oldText:k??"",newText:C??""};Kn.set(g,E);let B=st.get(g);B?.editDiff&&(B.editDiff=E),ga.delete(g);let O=Vn.get(g),G=O===void 0?i.showFileUpdates:O?"diff":"edit";G!=="none"&&(ya(g,E,G==="diff"?"diff":"edit"),I.repaintNow())})())},ya=(g,w,k)=>{let C=`editdiff:${g}`,A=cu(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)},Ab=g=>{if(!g.startsWith("editdiff:"))return;let w=g.slice(9),k=Kn.get(w);k&&(k.oldRef!==void 0||k.newRef!==void 0)&&Cb(w,k)},bf=g=>{let w=`editdiff:${g}`,k=i.showFileUpdates,C=st.get(g),A;if(k==="none"||!C?.editDiff||C.status!=="completed")A=null;else{let B=Vn.get(g);A=B!==void 0?B?"diff":"edit":k==="diff"?"diff":"edit"}if(A===null){I.removeKey(w);return}let E=C.editDiff;Kn.set(g,E),ya(g,E,A)},Rb=()=>{let g=i.showFileUpdates;for(let[w,k]of Kn){let C=`editdiff:${w}`,A=Vn.get(w),E=A===void 0?g:A?"diff":"edit";if(E==="none"){I.removeKey(C);continue}ya(w,k,E==="diff"?"diff":"edit")}},Tb=g=>{if(!g.path)return null;let w=tt(g.oldText).split(`
192
+ `),k=tt(g.newText).split(`
193
+ `),C=0,A=Math.min(w.length,k.length);for(;C<A&&w[C]===k[C];)C++;let E=k[C];if(!E)return null;let B=$r.isAbsolute(g.path)?g.path:$r.resolve(yt,g.path),O;try{O=w0(B,"utf8")}catch{return null}let G=O.split(`
194
+ `);for(let Ne=0;Ne<G.length;Ne++)if(G[Ne]===E)return Ne+1;return null},Eb=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=Kn.get(k),E=st.get(k)?.locations?.[0],B=E?.path??C?.path;if(!B)return!1;let O=null;E?.line!==void 0?O=E.line:C&&(O=Tb(C));let G=O===null?"":`:${O}`;return I.tryOpenPathString(B+G)}if(g.startsWith("tools:")){if(w===0)return!1;let k=q.get(g),C=k?k[w]:void 0;if(!C)return!1;let A=st.get(C),E=A?.locations?.[0];if(E){let O=E.line===void 0?"":`:${E.line}`;if(I.tryOpenPathString(E.path+O))return!0}let B=A?.detailFull??A?.detail;if(B)return I.tryOpenPathString(B)}return!1},Pb=(g,w)=>{if(g.startsWith("editdiff:")){let k=g.slice(9),C=Kn.get(k);if(!C)return;let A=Vn.get(k)??i.showFileUpdates==="diff";Vn.set(k,!A),ya(k,C,A?"edit":"diff"),I.repaintNow();return}if(g==="plan"){if(Ze===null)return;Ae=!(Ae??i.planExpanded),bs(),I.repaintNow();return}if(g.startsWith("tools:")){if(w===0){let A=z.get(g)??i.toolsExpanded;z.set(g,!A),g===Gt&&se!==null?un():ma(g),I.repaintNow();return}let k=q.get(g);if(!k)return;let C=k[w];if(!C)return;_0(C,ce),ma(g),I.repaintNow();return}if(g.startsWith("thought:")){if(!te.has(g))return;let k=ie.get(g);if(k!==void 0){ie.delete(g),I.setRunCollapsed(k,!1,vb(g)),I.repaintNow();return}let C=I.contiguousRun(g,new Set(te.keys()));if(C.length===0)return;let A=C[0];ie.set(A,C),I.setRunCollapsed(C,!0,[wb()]),I.repaintNow();return}};b=(g,w)=>{if(g.kind==="available-commands"){Hn=g.commands,vn();return}if(g.kind==="available-modes"){De=g.modes;return}if(g.kind==="config-options"){no=g.options;let C=g.options.find(E=>E.id==="agent");C&&C.currentValue&&C.currentValue!==an&&(an=C.currentValue,I.setSessionbar({agent:C.currentValue}));let A=g.options.find(E=>E.id==="mode");A&&(De=A.options.map(E=>({id:E.value,name:E.name??E.value,...E.description!==void 0?{description:E.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!==an&&(an=g.agentId,I.setSessionbar({agent:g.agentId}));return}if(g.kind==="usage-update"){let C=!1;g.used!==void 0&&lt.used!==g.used&&(lt.used=g.used,C=!0),g.size!==void 0&&lt.size!==g.size&&(lt.size=g.size,C=!0),g.costAmount!==void 0&&lt.costAmount!==g.costAmount&&(lt.costAmount=g.costAmount,C=!0),g.costCurrency!==void 0&&lt.costCurrency!==g.costCurrency&&(lt.costCurrency=g.costCurrency,C=!0),C&&I.setSessionbar({usage:{...lt}});return}if(g.kind==="user-text"){cn&&Vs(g.text),vs(),Ss(),se!==null&&(Ee=Date.now(),un()),xn=null,I.ensureSeparator();let C=Os(g);C.length>0&&I.appendLines(C),yc(),I.clearKey("plan"),Ze=null,Ae=null,st.clear(),ws.clear(),ln.length=0,Ee=null,gf(),I.redraw();return}if(g.kind==="agent-text"){Ss(),Qn===null&&_(g.workerTaskId),yb(g.text);return}if(g.kind==="agent-thought"){vs(),rr===null&&_(g.workerTaskId),Sb(g.text,g.workerTaskId);return}if(g.kind==="exit-plan-mode"){vs(),Ss();let C=ws.get(g.toolCallId),A={plan:g.plan??C?.plan??"",status:g.status??C?.status};if(ws.set(g.toolCallId,A),A.plan.length===0)return;let E=Eg(A);E.length>0&&I.upsertLines(g.toolCallId,E);return}if(g.kind==="tool-call"){vs(),Ss(),st.has(g.toolCallId)||_(g.workerTaskId),wf(g.toolCallId,g.title,g.status,void 0,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),un(),bf(g.toolCallId);return}if(g.kind==="plan"){vs(),Ss(),Ze=g;let C=Os(g,zr());C.length>0&&I.upsertLines("plan",[{body:""},...C]);let A=g.entries.length>0&&g.entries.every(E=>(E.status??"pending")==="completed");I.setStickyBottomKey(A?null:"plan");return}if(g.kind==="tool-call-update"){vs(),Ss(),wf(g.toolCallId,g.title,g.status,g.errorText,g.editDiff,g.detail,g.detailFull,g.locations,g.workerTaskId,w),g.upstreamInterrupted&&(qs=!0),un(),bf(g.toolCallId);return}g.kind==="model-changed"&&I.setSessionbar({model:g.model});let k=Os(g);if(k.length>0&&I.appendLines(k),g.kind==="turn-complete"){V=void 0,vs(),Ss();let C=g.amended?"amended":g.stopReason;if(!g.amended&&qs&&(C===void 0||C==="end_turn")&&(C="error"),Ze!==null&&C!==void 0&&C!=="end_turn"){let A=Os({...Ze,stopped:!0,amended:g.amended===!0},zr());A.length>0&&I.upsertLines("plan",[{body:""},...A])}Ze=null,Ae=null,I.clearKey("plan"),I.setStickyBottomKey("plan"),se!==null?(Ee=Date.now(),Me=C??null,un(),yc()):C!==void 0&&C!=="end_turn"&&C!=="amended"&&I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:`turn ended: ${C}`,bodyStyle:"tool-status-fail"}]),st.clear(),ws.clear(),ln.length=0,se=null,Ee=null,Me=null,qs=!1,I.ensureSeparator(),Qw({pendingTurns:L,queueSize:kt.size,ownTurnInFlight:bt!==null,hasInFlightHead:V!==void 0,replayDraining:S,amended:g.amended===!0})&&At(-L)}};let vf=y;y=[];let wa=[];for(let{event:g}of vf)g.kind==="user-text"&&typeof g.text=="string"&&wa.push(g.text);I.pauseRepaint(),S=!0;try{for(let{event:g,rawUpdate:w}of vf)b(g,w)}finally{S=!1,I.resumeRepaint()}if(wa.length>0){let g=Rl(Ot,wa);g!==Ot&&(Ot=g,Qt=Rl(Qt,wa),ke.setHistory(Va(me,Qt)),gr(fs,Ot).catch(()=>{}))}cn=!0,(async()=>{try{let g=await fetch(`${n.baseUrl}/v1/sessions/${encodeURIComponent(Ce)}/compact/status`,{headers:{Authorization:`Bearer ${n.token}`}});if(!g.ok)return;let w=await g.json(),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)"),!Js||w.shouldCompact!==!0)return;let C=w.approxTokens??0;U=!0,I.setCompactionPrompt({message:`This session has ~${Gm(C)} tokens of history above the compaction watermark.`,options:[{label:"Compact now",key:"y"},{label:"Not now",key:"n"}],selectedIndex:0})}catch{}})(),dn!==void 0&&L>0?(be=dn,I.setBanner({status:"busy",elapsedMs:Date.now()-dn}),Y===null&&(Y=Qe()),se===null&&gf(),se=dn,un()):dn===void 0&&L>0&&At(-L);let Mb=()=>{if(Se){let g=Se.resolve;Se=null,I.setPermissionPrompt(null),g({outcome:{outcome:"cancelled"}})}vs(),Ss()},Sf=()=>{se!==null&&(Ee=Date.now(),Me="reconnect-recovery-failed",un(),yc(),st.clear(),ws.clear(),ln.length=0,se=null,Ee=null,Me=null)};return p=g=>{Ft({src:"reconnect",step:"disconnect",message:g?.message}),I.setBanner({status:"disconnected",elapsedMs:void 0})},f=async()=>{Ft({src:"reconnect",step:"begin",sessionId:Ce}),Mb();let g={jsonrpc:"2.0",id:`tui-reinit-${Zw()}`,method:"initialize",params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-acp-tui",version:pe}}};Ft({src:"reconnect",step:"initialize-send"});try{await m.request(g),Ft({src:"reconnect",step:"initialize-ok"})}catch(O){Ft({src:"reconnect",step:"initialize-fail",message:O.message})}let w=Oe!==void 0,k={jsonrpc:"2.0",id:`tui-reattach-${Zw()}`,method:"session/attach",params:{sessionId:Ce,historyPolicy:w?"after_message":"none",...w?{afterMessageId:Oe}:{},clientInfo:{name:"hydra-acp-tui",version:pe},...(()=>{let O={};return zs!==void 0&&(O.resume={upstreamSessionId:zs,agentId:an,cwd:yt}),e.tui.toolContent==="references"&&(O.toolContent="references"),Object.keys(O).length>0?{_meta:{[ht]:O}}:{}})()}};wn=[];let C,A,E;Ft({src:"reconnect",step:"attach-send",useAfterMessage:w,lastSeenMessageId:Oe});try{let O=await m.request(k);if(Ft({src:"reconnect",step:"attach-resp",hasError:!!O.error}),O.error)throw new Error(O.error.message);E=Yw(O.result),C=E.appliedPolicy,E.clientId!==void 0&&(ot=E.clientId)}catch(O){A=O,Ft({src:"reconnect",step:"attach-fail",message:A.message})}let B=wn??[];if(wn=null,A)Sf(),I.appendLines([{prefix:" ",body:`reattach failed: ${A.message}`,bodyStyle:"tool-status-fail"}]);else if(w&&C!=="after_message")Sf(),I.appendLines([{prefix:"\u26A0 ",prefixStyle:"tool-status-fail",body:"reconnect couldn't replay events since last seen \u2014 scrollback may be incomplete",bodyStyle:"tool-status-fail"}]);else{S=!0;try{for(let O of B)Dn(O)}finally{S=!1}}if(E){let O=Gw({daemonTurnStartedAt:E.turnStartedAt,pendingTurns:L});O.pendingTurnsDelta!==0&&At(O.pendingTurnsDelta),O.banner==="busy"&&O.busySince!==void 0?(be=O.busySince,I.setBanner({status:"busy",elapsedMs:Date.now()-O.busySince}),Y===null&&(Y=Qe())):I.setBanner({status:"ready",elapsedMs:void 0})}else I.setBanner({status:L>0?"busy":"ready",elapsedMs:L>0?0:void 0});Ft({src:"reconnect",step:"end"})},h.onClose(g=>{g&&t.red(`
195
195
  connection lost: ${g.message}
196
- `),R(g?1:0)}),process.on("SIGINT",wn),s.initialPrompt&&a.sessionId==="__new__"&&Ws(s.initialPrompt,[]),await Go}async function r0(t,e,n,s,r){let i=s.cwd??process.cwd();if(s.sessionId){let o={sessionId:s.sessionId,agentId:s.agentId??"",cwd:i};return s.resumeHint!==void 0&&(o.resumeHint=s.resumeHint),o}if(s.forceNew)return await Nw(t,n,s)!=="ok"?null:Bw(s,i,e);if(s.resume){let o=await En(n,{cwd:i,all:!0}),a=wd(o,i);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}:(t.yellow(`No sessions found for ${i}.
197
- `),null)}for(;;){let o=await En(n,{includeNonInteractive:!0}),a=await Yu(t,{cwd:i,sessions:o,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt),a.cwd!==void 0&&(i=a.cwd,s.cwd=a.cwd);let l=await Nw(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return Bw(s,i,e)}if(a.kind==="fork"){let l=await Uw(t,n,a,o);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let c=o.find(l=>l.sessionId===a.sessionId);if(c!==void 0&&!!c.importedFromMachine&&!c.upstreamSessionId&&!s.readonly){let l=await Hw(t,c,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&c&&!c.importedFromMachine&&!s.readonly&&!(await Uo(c.cwd)).ok){let f=await kr(t,c,{defaultCwd:je(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(f.kind==="cancel")return null;if(f.kind==="back")continue;let u=a.agentId??c.agentId??"";return{sessionId:a.sessionId,agentId:u,cwd:f.path,resumeHint:{agentId:u,cwd:f.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function Hw(t,e,n,s){for(;;){let r=await hw(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await kr(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function Uw(t,e,n,s){let r=s.find(c=>c.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let c=await kr(t,r);if(c.kind==="cancel")return{kind:"cancel"};if(c.kind==="back")return{kind:"back"};o=c.path}let a;try{a=await yd(e,n.sourceSessionId,i?{cwd:o}:{})}catch(c){return t.red(`
196
+ `),St(g?1:0)}),process.on("SIGINT",Un),s.initialPrompt&&a.sessionId==="__new__"&&io(s.initialPrompt,[]),await da}async function O0(t,e,n,s,r){let i=s.cwd??process.cwd();if(s.sessionId){let o={sessionId:s.sessionId,agentId:s.agentId??"",cwd:i};return s.resumeHint!==void 0&&(o.resumeHint=s.resumeHint),o}if(s.forceNew)return await nb(t,n,s)!=="ok"?null:tb(s,i,e);if(s.resume){let o=await Fn(n,{cwd:i,all:!0}),a=Md(o,i);return a?{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}:(t.yellow(`No sessions found for ${i}.
197
+ `),null)}for(;;){let o=await Fn(n,{includeNonInteractive:!0}),a=await of(t,{cwd:i,sessions:o,config:e,target:n,prefs:r,...s.initialPrompt!==void 0?{initialPrompt:s.initialPrompt}:{}});if(a.kind==="abort"||a.kind==="exit")return null;if(a.kind==="new"){a.prompt!==void 0&&(s.initialPrompt=a.prompt),a.cwd!==void 0&&(i=a.cwd,s.cwd=a.cwd);let l=await nb(t,n,s);if(l==="cancel")return null;if(l==="back")continue;return tb(s,i,e)}if(a.kind==="fork"){let l=await ib(t,n,a,o);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}s.readonly=a.readonly===!0;let c=o.find(l=>l.sessionId===a.sessionId);if(c!==void 0&&!!c.importedFromMachine&&!c.upstreamSessionId&&!s.readonly){let l=await rb(t,c,a,s);if(l.kind==="cancel")return null;if(l.kind==="back")continue;return l.ctx}if(n.isLocal&&c&&!c.importedFromMachine&&!s.readonly&&!(await Go(c.cwd)).ok){let u=await _r(t,c,{defaultCwd:Je(e.defaultCwd),title:"Working directory missing \u2014 choose cwd",intro:"This session's working directory no longer exists. Pick a new one:"});if(u.kind==="cancel")return null;if(u.kind==="back")continue;let f=a.agentId??c.agentId??"";return{sessionId:a.sessionId,agentId:f,cwd:u.path,resumeHint:{agentId:f,cwd:u.path,upstreamSessionId:""}}}return{sessionId:a.sessionId,agentId:a.agentId??"",cwd:i}}}async function rb(t,e,n,s){for(;;){let r=await Fw(t,e);if(r==="cancel")return{kind:"cancel"};if(r==="back")return{kind:"back"};if(r==="view"){s.readonly=!0;let a=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:a,cwd:e.cwd}}}let i=await _r(t,e);if(i.kind==="cancel")return{kind:"cancel"};if(i.kind==="back")continue;let o=n.agentId??e.agentId??"";return{kind:"ctx",ctx:{sessionId:n.sessionId,agentId:o,cwd:i.path,resumeHint:{agentId:o,cwd:i.path,upstreamSessionId:""}}}}}async function ib(t,e,n,s){let r=s.find(c=>c.sessionId===n.sourceSessionId),i=!!n.sourceImportedFromMachine&&!n.sourceUpstreamSessionId,o=n.sourceCwd;if(i){if(!r)return{kind:"back"};let c=await _r(t,r);if(c.kind==="cancel")return{kind:"cancel"};if(c.kind==="back")return{kind:"back"};o=c.path}let a;try{a=await Pd(e,n.sourceSessionId,i?{cwd:o}:{})}catch(c){return t.red(`
198
198
  fork failed: ${c.message}
199
- `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function Bw(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function Nw(t,e,n){if(n.agentId||await Sf())return"ok";let s;try{s=await Wl(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await ye(),i=await kw(t,s,r.defaultAgent);if(i.kind==="cancel")return"cancel";if(i.kind==="back")return"back";if(n.agentId=i.agentId,i.persist)try{await da(i.agentId)}catch{}return"ok"}function i0(t,e){o0({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function o0(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?_.tuiLogFile():e;if(n.length!==0)try{d0(n);let s=JSON.stringify({t:new Date().toISOString(),...t});YR(n,`${s}
200
- `)}catch{}}function a0(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,f=c.totalBytes??0,u=(l/1e6).toFixed(1);if(f>0){let p=(f/1e6).toFixed(1),m=Math.min(100,Math.floor(l/f*100));return`${e} downloading ${d} ${u}/${p} MB (${m}%)`}return`${e} downloading ${d} ${u} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
201
- `))}}}function d0(t){try{if(GR(t).size<jw)return;QR(t,`${t}.0`)}catch{}}var ZR,e0,jw,qw=K(()=>{"use strict";sr();It();hu();Ne();vu();tr();lr();xo();to();xn();pe();Nt();Ld();wu();La();Po();Dy();Hy();Sw();zu();Wu();Iw();mu();qu();Tl();xu();Wd();Pu();Xd();Ew();$w();ys();Ri();ZR=12e4;e0=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next live session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];jw=5*1024*1024});var Ww={};cf(Ww,{runTui:()=>Dw});var zw=K(()=>{"use strict";qw()});import{readFileSync as c0}from"fs";import{fileURLToPath as l0}from"url";import{dirname as u0,resolve as f0}from"path";var lf=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),mb=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function uf(t){for(let e of Object.keys(t))if(!lf.has(e)&&!mb.has(e))return e}function dc(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(lf.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function hb(t,e){let n=t[e];if(typeof n=="string")return n}function Br(t,e){return t[e]===!0||t[e]==="true"}var gb="HYDRA_ACP_";function yb(t){return gb+t.toUpperCase().replace(/-/g,"_")}function it(t,e){let n=hb(t,e);return n!==void 0?n:process.env[yb(e)]}Ne();tr();async function Nf(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=mc(n);return{target:await Lf(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await ye();return{target:await Et(s),sessionId:n,fromUrl:!1}}function Cc(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}pe();Ne();qn();import*as Df from"fs/promises";async function Hf(t){if(await Df.mkdir(_.home(),{recursive:!0}),await aa(),!await Hr()){let n=Dr();await Ur(n),process.stdout.write(`Initialized ${_.authToken()}
199
+ `),{kind:"cancel"}}return{kind:"ctx",ctx:{sessionId:a.sessionId,agentId:n.sourceAgentId??"",cwd:o,...i?{resumeHint:{agentId:n.sourceAgentId??"",cwd:o,upstreamSessionId:""}}:{}}}}function tb(t,e,n){return{sessionId:"__new__",agentId:t.agentId??n.defaultAgent??"",cwd:e}}async function nb(t,e,n){if(n.agentId||await Ff())return"ok";let s;try{s=await tu(e)}catch{return"ok"}if(s.length===0)return"ok";let r=await we(),i=await Uw(t,s,r.defaultAgent);if(i.kind==="cancel")return"cancel";if(i.kind==="back")return"back";if(n.agentId=i.agentId,i.persist)try{await Sa(i.agentId)}catch{}return"ok"}function L0(t,e){Ft({src:"session/update",update:t,event:e===null?null:{kind:e.kind}})}function Ft(t){let e=process.env.HYDRA_TUI_DEBUG_LOG,n=e===void 0?$.tuiLogFile():e;if(n.length!==0)try{N0(n);let s=JSON.stringify({t:new Date().toISOString(),...t});y0(n,`${s}
200
+ `)}catch{}}function B0(t,e){let n=!1,s="",r=!1,i=c=>{n||c===3&&r||c===0&&!r||(r=c===3,process.stdout.write(`\x1B]9;4;${c}\x1B\\`))},o=c=>{n||(process.stdout.write("\r"),t.eraseLineAfter(),t.brightYellow(c),s=c)},a=c=>{let d=`${c.agentId}@${c.version}`;if(c.source==="npm")return c.phase==="install_start"||c.phase==="download_start"?`${e} installing ${d} via npm\u2026`:c.phase==="installed"?`${e} ${d} installed`:`${e} installing ${d} via npm\u2026`;if(c.phase==="download_start"||c.phase==="download_progress"){let l=c.receivedBytes??0,u=c.totalBytes??0,f=(l/1e6).toFixed(1);if(u>0){let p=(u/1e6).toFixed(1),m=Math.min(100,Math.floor(l/u*100));return`${e} downloading ${d} ${f}/${p} MB (${m}%)`}return`${e} downloading ${d} ${f} MB`}return c.phase==="download_done"?`${e} downloaded ${d}, verifying\u2026`:c.phase==="extract"?`${e} extracting ${d}\u2026`:c.phase==="installed"?`${e} ${d} installed`:s||e};return{write(c){n||(t.brightYellow(c),s=c)},applyProgress(c){if(n)return;c.phase==="download_start"||c.phase==="download_progress"||c.phase==="install_start"||c.phase==="extract"||c.phase==="download_done"?i(3):c.phase==="installed"&&i(0),o(a(c))},finalize(){n||(n=!0,i(0),process.stdout.write(`
201
+ `))}}}function N0(t){try{if(b0(t).size<ob)return;v0(t,`${t}.0`)}catch{}}var cf,P0,M0,ob,ab=K(()=>{"use strict";pr();xt();Au();je();Mu();ur();Sr();Fo();fo();nw();En();he();Wt();Yd();Eu();Ya();Ho();rw();iw();Hw();nf();tf();jw();Cu();ef();Dl();Ou();sc();Uu();uc();Vw();Xw();Es();Ni();cf="dismiss";P0=12e4;M0=[["Alt+Enter","newline in prompt"],["Shift+Tab","cycle agent modes (plan / accept-edits / etc.)"],["Tab","indent \xB7 slash-command / file-path completion"],null,["\u2191 / \u2193","prompt history \xB7 queue navigation"],["\u2190/\u2192 Home/End","cursor movement"],["Alt+B / Alt+F","word back / forward"],["^A / ^E","line start / end"],["^W / ^U / ^K","kill word / line / to end"],["^Y","yank last kill"],null,["^P","switch session (picker)"],["Alt+N / Alt+Tab","next live session"],["^T","show / hide thoughts"],["^V","paste image from clipboard"],["^O","session options (tools \xB7 plan \xB7 thoughts \xB7 diffs \xB7 mouse \xB7 enter)"],null,["^R","history reverse search (^S walks forward once engaged)"],["PgUp / PgDn","scroll scrollback"],["Mouse wheel","scroll scrollback (when mouse capture is on)"],["Middle-click","paste PRIMARY selection (terminal-style)"],["^X","toggle mouse capture (wheel scroll vs. text selection)"],null,["^C","cancel turn (twice to exit)"],["Esc","cancel turn and prefill draft"],["^D","exit (or delete-forward in prompt)"],["^L","force full redraw"],["^G","toggle this help"]];ob=5*1024*1024});var db={};kf(db,{runTui:()=>sb});var cb=K(()=>{"use strict";ab()});import{readFileSync as D0}from"fs";import{fileURLToPath as H0}from"url";import{dirname as U0,resolve as j0}from"path";var If=new Set(["all","dangerously-skip-permissions","detach","diff","disabled","drip","fold","follow","force","foreground","help","include-cat","info","json","new","no-color","no-pager","raw","reattach","readonly","replace","rotate-token","verbose","version"]),$b=new Set(["agent","args","columns","command","cwd","drip-speed","env","host","model","name","out","prompt","session","stream-bytes","stream-threshold","tail"]);function xf(t){for(let e of Object.keys(t))if(!If.has(e)&&!$b.has(e))return e}function bc(t){let e=[],n={},s=0;for(;s<t.length;){let r=t[s];if(r===void 0)break;if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1){let c=r.slice(2,i);n[c]=r.slice(i+1),s+=1;continue}let o=r.slice(2);if(If.has(o)){n[o]=!0,s+=1;continue}let a=t[s+1];if(a!==void 0&&!a.startsWith("--")){n[o]=a,s+=2;continue}n[o]=!0,s+=1;continue}e.push(r),s+=1}return{positional:e,flags:n}}function Fb(t,e){let n=t[e];if(typeof n=="string")return n}function Vr(t,e){return t[e]===!0||t[e]==="true"}var Ob="HYDRA_ACP_";function Lb(t){return Ob+t.toUpperCase().replace(/-/g,"_")}function rt(t,e){let n=Fb(t,e);return n!==void 0?n:process.env[Lb(e)]}je();ur();async function Gf(t,e){let n=typeof t=="string"&&t.trim().length>0?t.trim():void 0;if(n===void 0)return;if(n.startsWith("hydra://")){let i=Cc(n);return{target:await Yf(i,{allowPrompt:e.allowPrompt}),sessionId:i.sessionId,fromUrl:!0}}let s=await we();return{target:await Mt(s),sessionId:n,fromUrl:!1}}function Lc(t){let e=t.session;if(typeof e=="string"&&e.length>0)return e;let n=process.env.HYDRA_ACP_SESSION;if(typeof n=="string"&&n.length>0)return n}he();je();Gn();import*as Xf from"fs/promises";async function Zf(t){if(await Xf.mkdir($.home(),{recursive:!0}),await va(),!await Gr()){let n=Qr();await Xr(n),process.stdout.write(`Initialized ${$.authToken()}
202
202
  Service token: ${n}
203
- `);return}if(Br(t,"rotate-token")){let n=Dr();await Ur(n),process.stdout.write(`Rotated token in ${_.authToken()}
203
+ `);return}if(Vr(t,"rotate-token")){let n=Qr();await Xr(n),process.stdout.write(`Rotated token in ${$.authToken()}
204
204
  New token: ${n}
205
- `);return}process.stdout.write(`Service token already exists at ${_.authToken()}.
205
+ `);return}process.stdout.write(`Service token already exists at ${$.authToken()}.
206
206
  `),process.stdout.write(`Pass --rotate-token to generate a new service token.
207
- `)}pe();qr();Ne();qn();import{setTimeout as rx}from"timers/promises";import Ph from"chalk";import*as xh from"fs";import*as mi from"fs/promises";import*as Ch from"net";import*as Ah from"tls";import KI from"fastify";import YI from"@fastify/websocket";var Uf="acp.v1";function jf(t,e){return t.has(Uf)?Uf:!1}Ne();import Ih from"pino";import VI from"pino-roll";pe();import*as pt from"fs/promises";import{createHash as Xb}from"crypto";import{gzip as Zb,gunzip as ev}from"zlib";import{promisify as qf}from"util";var Wf=qf(Zb),tv=qf(ev),zf=/^[A-Za-z0-9_-]+$/,nv=/^[a-f0-9]{64}$/,Ac=!0;function Jf(t){Ac=t}function pa(t,e){return zf.test(t)?e===void 0||nv.test(e):!1}function ma(t,e){return`${_.toolBlobFile(t,e)}.gz`}async function Rc(t,e){if(!pa(t))return null;let n=Xb("sha256").update(e,"utf8").digest("hex"),s=ma(t,n),r=_.toolBlobFile(t,n);for(let a of[s,r])try{return await pt.access(a),n}catch{}await pt.mkdir(_.toolsDir(t),{recursive:!0});let i=Ac?s:r,o=Ac?await Wf(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await pt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function ha(t,e){if(!pa(t,e))return null;try{let n=await pt.readFile(ma(t,e));return(await tv(n)).toString("utf8")}catch{}try{return await pt.readFile(_.toolBlobFile(t,e),"utf8")}catch{return null}}async function Kf(t,e){if(!pa(t,e))return null;try{return await pt.readFile(ma(t,e))}catch{}try{let n=await pt.readFile(_.toolBlobFile(t,e));return await Wf(n)}catch{return null}}async function Yf(t,e,n){if(!pa(t,e))return;let s=ma(t,e);try{await pt.access(s);return}catch{}await pt.mkdir(_.toolsDir(t),{recursive:!0}),await pt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Vf(t){zf.test(t)&&await pt.rm(_.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}pe();Ne();Qs();import*as op from"fs/promises";import*as ya from"path";import{z as se}from"zod";pe();import*as Qf from"fs";import*as kt from"fs/promises";import*as us from"path";import{spawn as Xf}from"child_process";import{Readable as sv}from"stream";function Sn(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function Pc(t,e=Sn()){if(e)return t[e]}var Wr=t=>{process.stderr.write(t+`
208
- `)};function Mc(t){Wr=t??(e=>process.stderr.write(e+`
209
- `))}async function Zf(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${Sn()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=Sn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentInstallDir(t.agentId,e,t.version),s=us.resolve(n,t.target.cmd);if(await Ec(s))return s;if(await rv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Ec(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await kt.chmod(s,493).catch(()=>{}),s}async function rv(t){await kt.mkdir(us.dirname(t.installDir),{recursive:!0});let e=await kt.mkdtemp(`${t.installDir}.partial-`);try{Wr(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await iv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});Wr(`hydra-acp: extracting ${t.agentId}`),zr(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await av(n,e),await kt.unlink(n).catch(()=>{});try{await kt.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Ec(t.installDir)){await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),zr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}Wr(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),zr(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await kt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function zr(t,e){if(t)try{t(e)}catch{}}async function iv(t){let e=ov(t.url),n=us.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=Qf.createWriteStream(n),o=sv.fromWeb(s.body);zr(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,f=150;return o.on("data",u=>{a+=u.length;let p=Date.now();p-d>=f&&(d=p,zr(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,Wr(Gf(t.agentId,a,r)))}),await new Promise((u,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>u()),o.pipe(i)}),Wr(Gf(t.agentId,a,r,!0)),zr(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function Gf(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function ov(t){let e=new URL(t);return us.posix.basename(e.pathname)||"archive"}async function av(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Tc("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await dv("unzip")){await Tc("unzip",["-q",t,"-d",e]);return}await Tc("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Tc(t,e){return new Promise((n,s)=>{let r=Xf(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function dv(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=Xf(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Ec(t){try{return await kt.access(t),!0}catch{return!1}}pe();import*as Lt from"fs/promises";import*as kn from"path";import{spawn as cv}from"child_process";var $c=t=>{process.stderr.write(t+`
210
- `)};function Oc(t){$c=t??(e=>process.stderr.write(e+`
211
- `))}async function tp(t){let e=Sn();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=_.agentNpmInstallDir(t.agentId,e,t.version),s=mv(t.packageSpec),r=hv(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=kn.join(n,"node_modules",".bin",t.bin);if(await nr(o))return o;if(await nr(n)){let f=await ep(i);if(f)return f.binPath}await lv({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await ep(i);if(a)return a.binPath;let c=await sp(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function lv(t){await Lt.mkdir(kn.dirname(t.installDir),{recursive:!0});let e=await Lt.mkdtemp(`${t.installDir}.partial-`);try{$c(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),_c(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await pv({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await Lt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await nr(t.installDir)){await Lt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),_c(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}$c(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),_c(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await Lt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function _c(t,e){if(t)try{t(e)}catch{}}var uv=5,fv=25;function pv(t){return np(t,0)}async function np(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=cv("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
212
- stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<uv)return await new Promise(r=>setTimeout(r,fv*(e+1))),np(t,e+1);throw n}}function mv(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function hv(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function sp(t,e){let n=kn.join(t,"node_modules",e,"package.json");try{let s=await Lt.readFile(n,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function ep(t){let e=kn.join(t.installDir,"node_modules",".bin"),n=kn.join(e,t.hint);if(await nr(n))return{binName:t.hint,binPath:n};let s=await sp(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=kn.join(e,i);if(await nr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=kn.join(e,i);if(await nr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=kn.join(e,t.basename);if(await nr(r))return{binName:t.basename,binPath:r}}}async function nr(t){try{return await Lt.access(t),!0}catch{return!1}}var gv=se.object({package:se.string(),bin:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),Jr=se.object({archive:se.string().url().optional(),cmd:se.string().optional(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),yv=se.object({"darwin-aarch64":Jr.optional(),"darwin-x86_64":Jr.optional(),"linux-aarch64":Jr.optional(),"linux-x86_64":Jr.optional(),"windows-x86_64":Jr.optional(),"windows-aarch64":Jr.optional()}),wv=se.object({package:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),bv=se.object({command:se.string(),args:se.array(se.string()).optional(),env:se.record(se.string()).optional()}),vv=se.object({command:se.string().optional(),url:se.string().optional(),description:se.string().optional()}),Sv=se.object({npx:gv.optional(),binary:yv.optional(),uvx:wv.optional(),exec:bv.optional()}),kv=se.object({id:se.string(),name:se.string(),version:se.string().optional(),description:se.string().optional(),authors:se.array(se.string()).optional(),license:se.string().optional(),icon:se.string().optional(),repository:se.string().optional(),website:se.string().optional(),distribution:Sv,onboarding:vv.optional(),requiredEnv:se.array(se.string().min(1)).optional()}),rp=se.object({version:se.string(),agents:se.array(kv),extensions:se.array(se.unknown()).optional()}),ga=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(o=>o.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>Fc(o)===e);return i?this.applyOverride(i):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:je(n.command??e),args:n.args?.map(je),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:Iv(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=rp.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await zt(_.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=rp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Ft(_.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Iv(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Fc(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Kr(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await Lc(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Lc(t){let e=Sn();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Pc(t.distribution.binary,e);if(s?.cmd){let r=ya.resolve(_.agentInstallDir(t.id,e,n),s.cmd);if(await ip(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Fc(t)??s.package,i=_.agentNpmInstallDir(t.id,e,n),o=ya.join(i,"node_modules",".bin",r);if(await ip(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function ip(t){try{return await op.access(t),!0}catch{return!1}}async function cn(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Fc(t)??r.package,a=n.onInstallProgress;return{command:await tp({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=Pc(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${Sn()??"this platform"}.`);let i=n.onInstallProgress,o=await Zf({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as Tv}from"child_process";import*as xa from"fs";import*as kp from"path";It();function Ia(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
213
- `);for(;c!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),d.length>0)try{let l=JSON.parse(d);for(let f of s)f(l)}catch(l){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:z.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
207
+ `)}he();ei();je();Gn();import{setTimeout as Ax}from"timers/promises";import zh from"chalk";import*as Dh from"fs";import*as Ci from"fs/promises";import*as Hh from"net";import*as Uh from"tls";import hx from"fastify";import gx from"@fastify/websocket";var ep="acp.v1";function tp(t,e){return t.has(ep)?ep:!1}je();import Nh from"pino";import yx from"pino-roll";he();import*as mt from"fs/promises";import{createHash as yv}from"crypto";import{gzip as wv,gunzip as bv}from"zlib";import{promisify as np}from"util";var sp=np(wv),vv=np(bv),rp=/^[A-Za-z0-9_-]+$/,Sv=/^[a-f0-9]{64}$/,Bc=!0;function ip(t){Bc=t}function Aa(t,e){return rp.test(t)?e===void 0||Sv.test(e):!1}function Ra(t,e){return`${$.toolBlobFile(t,e)}.gz`}async function Nc(t,e){if(!Aa(t))return null;let n=yv("sha256").update(e,"utf8").digest("hex"),s=Ra(t,n),r=$.toolBlobFile(t,n);for(let a of[s,r])try{return await mt.access(a),n}catch{}await mt.mkdir($.toolsDir(t),{recursive:!0});let i=Bc?s:r,o=Bc?await sp(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await mt.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),n}async function Ta(t,e){if(!Aa(t,e))return null;try{let n=await mt.readFile(Ra(t,e));return(await vv(n)).toString("utf8")}catch{}try{return await mt.readFile($.toolBlobFile(t,e),"utf8")}catch{return null}}async function op(t,e){if(!Aa(t,e))return null;try{return await mt.readFile(Ra(t,e))}catch{}try{let n=await mt.readFile($.toolBlobFile(t,e));return await sp(n)}catch{return null}}async function ap(t,e,n){if(!Aa(t,e))return;let s=Ra(t,e);try{await mt.access(s);return}catch{}await mt.mkdir($.toolsDir(t),{recursive:!0}),await mt.writeFile(s,n,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function dp(t){rp.test(t)&&await mt.rm($.toolsDir(t),{recursive:!0,force:!0}).catch(()=>{})}he();je();ar();import*as bp from"fs/promises";import*as Pa from"path";import{z as re}from"zod";he();import*as lp from"fs";import*as It from"fs/promises";import*as Is from"path";import{spawn as up}from"child_process";import{Readable as kv}from"stream";function An(){let t=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!t||!e))return`${t}-${e}`}function Uc(t,e=An()){if(e)return t[e]}var ti=t=>{process.stderr.write(t+`
208
+ `)};function jc(t){ti=t??(e=>process.stderr.write(e+`
209
+ `))}async function fp(t){if(!t.target.archive)throw new Error(`Agent ${t.agentId} has no archive URL for ${An()??"this platform"}`);if(!t.target.cmd)throw new Error(`Agent ${t.agentId} has no cmd in its binary target`);let e=An();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentInstallDir(t.agentId,e,t.version),s=Is.resolve(n,t.target.cmd);if(await Hc(s))return s;if(await Iv({agentId:t.agentId,version:t.version,archiveUrl:t.target.archive,installDir:n,onProgress:t.onProgress}),!await Hc(s))throw new Error(`Agent ${t.agentId}: extracted archive did not contain ${t.target.cmd} (looked in ${n})`);return process.platform!=="win32"&&await It.chmod(s,493).catch(()=>{}),s}async function Iv(t){await It.mkdir(Is.dirname(t.installDir),{recursive:!0});let e=await It.mkdtemp(`${t.installDir}.partial-`);try{ti(`hydra-acp: downloading ${t.agentId} from ${t.archiveUrl}`);let n=await xv({url:t.archiveUrl,dir:e,agentId:t.agentId,version:t.version,onProgress:t.onProgress});ti(`hydra-acp: extracting ${t.agentId}`),ni(t.onProgress,{phase:"extract",agentId:t.agentId,version:t.version}),await Av(n,e),await It.unlink(n).catch(()=>{});try{await It.rename(e,t.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Hc(t.installDir)){await It.rm(e,{recursive:!0,force:!0}).catch(()=>{}),ni(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw s}ti(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),ni(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await It.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function ni(t,e){if(t)try{t(e)}catch{}}async function xv(t){let e=Cv(t.url),n=Is.join(t.dir,e),s=await fetch(t.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${t.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=lp.createWriteStream(n),o=kv.fromWeb(s.body);ni(t.onProgress,{phase:"download_start",agentId:t.agentId,version:t.version,totalBytes:r});let a=0,c=Date.now(),d=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-d>=u&&(d=p,ni(t.onProgress,{phase:"download_progress",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r})),p-c>=l&&(c=p,ti(cp(t.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),ti(cp(t.agentId,a,r,!0)),ni(t.onProgress,{phase:"download_done",agentId:t.agentId,version:t.version,receivedBytes:a,totalBytes:r}),n}function cp(t,e,n,s=!1){let r=(e/1e6).toFixed(1);if(n>0){let o=(n/1e6).toFixed(1),a=Math.min(100,Math.floor(e/n*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${t} ${r} MB`}function Cv(t){let e=new URL(t);return Is.posix.basename(e.pathname)||"archive"}async function Av(t,e){let n=t.toLowerCase();if(n.endsWith(".tar.gz")||n.endsWith(".tgz")||n.endsWith(".tar")){await Dc("tar",["-xf",t,"-C",e]);return}if(n.endsWith(".zip")){if(await Rv("unzip")){await Dc("unzip",["-q",t,"-d",e]);return}await Dc("tar",["-xf",t,"-C",e]);return}throw new Error(`Unsupported archive format: ${t}`)}function Dc(t,e){return new Promise((n,s)=>{let r=up(t,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){n();return}s(new Error(`${t} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function Rv(t){return new Promise(e=>{let n=process.platform==="win32"?"where":"which",s=up(n,[t],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Hc(t){try{return await It.access(t),!0}catch{return!1}}he();import*as jt from"fs/promises";import*as Rn from"path";import{spawn as Tv}from"child_process";var Wc=t=>{process.stderr.write(t+`
210
+ `)};function zc(t){Wc=t??(e=>process.stderr.write(e+`
211
+ `))}async function mp(t){let e=An();if(!e)throw new Error(`Agent ${t.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let n=$.agentNpmInstallDir(t.agentId,e,t.version),s=$v(t.packageSpec),r=Fv(s),i={installDir:n,packageName:s,hint:t.bin,basename:r},o=Rn.join(n,"node_modules",".bin",t.bin);if(await fr(o))return o;if(await fr(n)){let u=await pp(i);if(u)return u.binPath}await Ev({agentId:t.agentId,version:t.version,packageSpec:t.packageSpec,installDir:n,registry:t.registry,onProgress:t.onProgress});let a=await pp(i);if(a)return a.binPath;let c=await gp(n,s),d=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],l=d.length>0?` (package declares bins: ${d.join(", ")})`:"";throw new Error(`Agent ${t.agentId}: npm install of ${t.packageSpec} did not produce bin ${t.bin} (looked in ${n}/node_modules/.bin/)${l}`)}async function Ev(t){await jt.mkdir(Rn.dirname(t.installDir),{recursive:!0});let e=await jt.mkdtemp(`${t.installDir}.partial-`);try{Wc(`hydra-acp: installing ${t.packageSpec} for ${t.agentId} into ${e}`),qc(t.onProgress,{phase:"install_start",agentId:t.agentId,version:t.version,packageSpec:t.packageSpec}),await _v({packageSpec:t.packageSpec,cwd:e,registry:t.registry});try{await jt.rename(e,t.installDir)}catch(n){let s=n;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await fr(t.installDir)){await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),qc(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version});return}throw n}Wc(`hydra-acp: installed ${t.agentId} to ${t.installDir}`),qc(t.onProgress,{phase:"installed",agentId:t.agentId,version:t.version})}catch(n){throw await jt.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}}function qc(t,e){if(t)try{t(e)}catch{}}var Pv=5,Mv=25;function _v(t){return hp(t,0)}async function hp(t,e){try{await new Promise((n,s)=>{let r=t.registry?["--registry",t.registry]:[],i;try{i=Tv("npm",["install","--no-audit","--no-fund","--silent",...r,t.packageSpec],{cwd:t.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,c)=>{if(a===0){n();return}let d=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,l=o.trim();s(new Error(l?`npm install ${t.packageSpec} failed (${d})
212
+ stderr: ${l}`:`npm install ${t.packageSpec} failed (${d})`))})})}catch(n){if(n.code==="ETXTBSY"&&e<Pv)return await new Promise(r=>setTimeout(r,Mv*(e+1))),hp(t,e+1);throw n}}function $v(t){if(t.startsWith("@")){let n=t.indexOf("/");if(n===-1)return t;let r=t.slice(n+1).indexOf("@");return r===-1?t:t.slice(0,n+1+r)}let e=t.indexOf("@");return e<=0?t:t.slice(0,e)}function Fv(t){let e=t.lastIndexOf("/");return e===-1?t:t.slice(e+1)}async function gp(t,e){let n=Rn.join(t,"node_modules",e,"package.json");try{let s=await jt.readFile(n,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function pp(t){let e=Rn.join(t.installDir,"node_modules",".bin"),n=Rn.join(e,t.hint);if(await fr(n))return{binName:t.hint,binPath:n};let s=await gp(t.installDir,t.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=Rn.join(e,i);if(await fr(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[t.hint,t.basename])if(r.includes(i)){let o=Rn.join(e,i);if(await fr(o))return{binName:i,binPath:o}}}}if(t.basename!==t.hint){let r=Rn.join(e,t.basename);if(await fr(r))return{binName:t.basename,binPath:r}}}async function fr(t){try{return await jt.access(t),!0}catch{return!1}}var Ov=re.object({package:re.string(),bin:re.string().optional(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),si=re.object({archive:re.string().url().optional(),cmd:re.string().optional(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),Lv=re.object({"darwin-aarch64":si.optional(),"darwin-x86_64":si.optional(),"linux-aarch64":si.optional(),"linux-x86_64":si.optional(),"windows-x86_64":si.optional(),"windows-aarch64":si.optional()}),Bv=re.object({package:re.string(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),Nv=re.object({command:re.string(),args:re.array(re.string()).optional(),env:re.record(re.string()).optional()}),Dv=re.object({command:re.string().optional(),url:re.string().optional(),description:re.string().optional()}),Hv=re.object({npx:Ov.optional(),binary:Lv.optional(),uvx:Bv.optional(),exec:Nv.optional()}),Uv=re.object({id:re.string(),name:re.string(),version:re.string().optional(),description:re.string().optional(),authors:re.array(re.string()).optional(),license:re.string().optional(),icon:re.string().optional(),repository:re.string().optional(),website:re.string().optional(),distribution:Hv,onboarding:Dv.optional(),requiredEnv:re.array(re.string().min(1)).optional()}),yp=re.object({version:re.string(),agents:re.array(Uv),extensions:re.array(re.unknown()).optional()}),Ea=class{constructor(e,n={}){this.config=e;this.options=n}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let n=await this.fetchFromNetwork();return this.cache=n,await this.writeDiskCache(n),n.data}catch(n){if(e)return this.cache=e,e.data;throw n}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let n=this.localAgents().find(o=>o.id===e);if(n)return n;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>Jc(o)===e);return i?this.applyOverride(i):void 0}localAgents(){return Object.entries(this.config.agents??{}).map(([e,n])=>({id:e,name:n.name??e,description:n.description,version:"local",distribution:{exec:{command:Je(n.command??e),args:n.args?.map(Je),env:n.env}}}))}applyOverride(e){let n=this.config.agentOverrides?.[e.id];return!n?.packageSpec||!e.distribution.npx?e:{...e,version:jv(n.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:n.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let n=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return n<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let n=await e.json(),s=yp.parse(n),r={fetchedAt:Date.now(),raw:n,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await Xt($.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let n=yp.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:n}}catch{return}}async writeDiskCache(e){await Ut($.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function jv(t){let e=t.lastIndexOf("@"),s=(e>0?t.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function Jc(t){let e=t.distribution.npx?.package;if(!e)return;let n=e.lastIndexOf("/"),s=n===-1?e:e.slice(n+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function ri(t){let e=typeof t.localAgents=="function"?t.localAgents():[],n;try{n=await t.load()}catch(o){if(e.length===0)throw o;n={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...n.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await Kc(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:n.version,fetchedAt:t.lastFetchedAt(),agents:i}}async function Kc(t){let e=An();if(!e)return"no";let n=t.version??"current";if(t.distribution.exec)return"yes";if(t.distribution.binary){let s=Uc(t.distribution.binary,e);if(s?.cmd){let r=Pa.resolve($.agentInstallDir(t.id,e,n),s.cmd);if(await wp(r))return"yes"}}if(t.distribution.npx){let s=t.distribution.npx,r=s.bin??Jc(t)??s.package,i=$.agentNpmInstallDir(t.id,e,n),o=Pa.join(i,"node_modules",".bin",r);if(await wp(o))return"yes"}return!t.distribution.npx&&!t.distribution.binary&&t.distribution.uvx?"lazy":"no"}async function wp(t){try{return await bp.access(t),!0}catch{return!1}}async function hn(t,e=[],n={}){let s=t.version??"current";if(t.distribution.npx){let r=t.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??Jc(t)??r.package,a=n.onInstallProgress;return{command:await mp({agentId:t.id,version:s,packageSpec:r.package,bin:o,registry:n.npmRegistry,onProgress:a?d=>a({source:"npm",...d}):void 0}),args:i,env:r.env??{},version:s}}if(t.distribution.binary){let r=Uc(t.distribution.binary);if(!r)throw new Error(`Agent ${t.id} has no binary distribution for ${An()??"this platform"}.`);let i=n.onInstallProgress,o=await fp({agentId:t.id,version:s,target:r,onProgress:i?c=>i({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(t.distribution.uvx){let r=t.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(t.distribution.exec){let r=t.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${t.id} has no usable distribution method.`)}import{spawn as Kv}from"child_process";import*as Ba from"fs";import*as Op from"path";xt();function La(t,e){let n="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let c of r)c(a)}};return t.setEncoding("utf8"),t.on("data",a=>{n+=a;let c=n.indexOf(`
213
+ `);for(;c!==-1;){let d=n.slice(0,c).trim();if(n=n.slice(c+1),d.length>0)try{let l=JSON.parse(d);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:W.ParseError,message:`Failed to parse ndjson line: ${l.message}`}})}c=n.indexOf(`
214
214
  `)}}),t.on("end",()=>o()),t.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let c=JSON.stringify(a)+`
215
- `;await new Promise((d,l)=>{e.write(c,f=>{if(f){l(f);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}sr();pe();var Ev=4096,ps=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??Ev,this.killEscalationMs=e.killEscalationMs??Pv,this.logger=e.logger,this.fileLog=Mv(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
216
- `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=Ia(n.stdout,n.stdin);this.connection=new Pt(s),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
215
+ `;await new Promise((d,l)=>{e.write(c,u=>{if(u){l(u);return}d()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}pr();he();var Vv=4096,Cs=class t{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,n){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=n,this.stderrTailBytes=e.stderrTailBytes??Vv,this.killEscalationMs=e.killEscalationMs??Yv,this.logger=e.logger,this.fileLog=Qv(e.agentId),this.writeLog(`--- spawn pid=${n.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
216
+ `),!n.stdout||!n.stdin)throw new Error("agent subprocess missing stdio");let s=La(n.stdout,n.stdin);this.connection=new _t(s),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),n.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
217
217
  `),this.connection.fail(new Error(i))}),n.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
218
218
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${n.pid} exited after kill code=${r} signal=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${n.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let n=this.stderrTail.trim();return n?`${e}
219
- stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=Tv(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
219
+ stderr: ${n}`:e}static spawn(e){let n={...process.env,...e.plan.env,...e.extraEnv??{}},s=Kv(e.plan.command,e.plan.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new t(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
220
220
  `),this.logger?.info(`agent ${this.agentId} pid=${this.child.pid} kill requested signal=${e}`),await this.connection.close().catch(()=>{}),this.signalProcessGroup(e),await this.waitForExit(this.killEscalationMs),!this.exited&&(this.writeLog(`--- kill escalating signal=SIGKILL time=${new Date().toISOString()} ---
221
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},Pv=2e3;function Mv(t){try{let e=_.agentLogFile(t);xa.mkdirSync(kp.dirname(e),{recursive:!0});let n=xa.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as ar from"fs/promises";import*as Da from"os";import*as vo from"path";import{customAlphabet as DS}from"nanoid";Uc();xn();ol();pe();Qs();import*as Jn from"fs/promises";import{z as Cn}from"zod";var IS=Cn.object({version:Cn.literal(1),agentId:Cn.string(),upstreamSessionId:Cn.string(),deletedAt:Cn.string(),upstreamUpdatedAt:Cn.string().optional(),cwd:Cn.string().optional(),title:Cn.string().optional(),reason:Cn.enum(["user","expired"]).optional(),interactive:Cn.boolean().optional()}),Ma=class{async add(e){let n={version:1,...e};await Ft(_.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await Jn.access(_.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=_.tombstoneFile(e,n),r=await zt(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return IS.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await Jn.unlink(_.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await Jn.rmdir(_.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let n;try{n=await Jn.readdir(_.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await Jn.readdir(_.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Yp(t,e){return e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as dm from"fs/promises";It();Nt();Ea();Ta();var AS=12e4;async function Gp(t,e,n){let s=t.timeoutMs??AS,r,i,o=!1;try{let a=(async()=>{r=ps.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:fe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let m=TS(d);if(m.size===0||m.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",m=>{let h=RS(m);h.length>0&&f.push(h)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let u=f.join(""),p=n(u);if(!p){let m=JSON.stringify(u.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${u.length} preview=${m})`);let h=u.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${u.length} chars): ${h}${u.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function Qp(t){let e=Xr(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
221
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let n=this.child.pid;if(n!==void 0)try{process.kill(-n,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(n=>{let s=setTimeout(()=>{this.child.off("exit",r),n()},e),r=()=>{clearTimeout(s),n()};this.child.once("exit",r)})}},Yv=2e3;function Qv(t){try{let e=$.agentLogFile(t);Ba.mkdirSync(Op.dirname(e),{recursive:!0});let n=Ba.createWriteStream(e,{flags:"a"});return n.on("error",()=>{}),n}catch{return}}import*as wr from"fs/promises";import*as Xa from"os";import*as Po from"path";import{customAlphabet as ik}from"nanoid";Xc();En();yl();he();ar();import*as es from"fs/promises";import{z as Pn}from"zod";var qS=Pn.object({version:Pn.literal(1),agentId:Pn.string(),upstreamSessionId:Pn.string(),deletedAt:Pn.string(),upstreamUpdatedAt:Pn.string().optional(),cwd:Pn.string().optional(),title:Pn.string().optional(),reason:Pn.enum(["user","expired"]).optional(),interactive:Pn.boolean().optional()}),Wa=class{async add(e){let n={version:1,...e};await Ut($.tombstoneFile(e.agentId,e.upstreamSessionId),n,{mode:384})}async has(e,n){try{return await es.access($.tombstoneFile(e,n)),!0}catch{return!1}}async read(e,n){let s=$.tombstoneFile(e,n),r=await Xt(s);if(r===void 0)return await this.has(e,n)?{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}:void 0;try{return qS.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:n,deletedAt:new Date(0).toISOString()}}}async remove(e,n){try{await es.unlink($.tombstoneFile(e,n))}catch(s){if(s.code!=="ENOENT")throw s}try{await es.rmdir($.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let n;try{n=await es.readdir($.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let n;try{n=await es.readdir($.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of n){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function cm(t,e){return t.reason==="user"||e===void 0?!1:t.upstreamUpdatedAt===void 0?!0:e>t.upstreamUpdatedAt}import*as Im from"fs/promises";xt();Wt();ja();Ua();var JS=12e4;async function um(t,e,n){let s=t.timeoutMs??JS,r,i,o=!1;try{let a=(async()=>{r=Cs.spawn({agentId:t.agentId,cwd:t.cwd,plan:t.plan,logger:t.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:pe}}),d=await r.connection.request("session/new",{cwd:t.cwd,mcpServers:[]}),l=d.sessionId;if(typeof l!="string"){t.logger?.warn(`synopsis: agent ${t.agentId} returned non-string sessionId from session/new`),t.onFailure?.(`agent ${t.agentId} did not return a sessionId from session/new`);return}if(t.onWorkerSpawned?.(l,r.pid),t.modelId){let m=VS(d);if(m.size===0||m.has(t.modelId))try{await r.connection.request("session/set_model",{sessionId:l,modelId:t.modelId})}catch(h){t.logger?.warn(`synopsis: agent ${t.agentId} rejected set_model ${JSON.stringify(t.modelId)}: ${h.message}; continuing on default`)}else t.logger?.warn(`synopsis: model ${JSON.stringify(t.modelId)} not advertised by agent ${t.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let u=[];r.connection.onNotification("session/update",m=>{let h=KS(m);h.length>0&&u.push(h)}),await r.connection.request("session/prompt",{sessionId:l,prompt:[{type:"text",text:e}]});let f=u.join(""),p=n(f);if(!p){let m=JSON.stringify(f.slice(0,200));t.logger?.warn(`synopsis: agent ${t.agentId} reply did not parse (replyLen=${f.length} preview=${m})`);let h=f.slice(0,120).replace(/\s+/g," ").trim();t.onFailure?.(`agent ${t.agentId} returned unparseable JSON (${f.length} chars): ${h}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((c,d)=>{i=setTimeout(()=>{o=!0,t.logger?.warn(`synopsis: agent ${t.agentId} timed out after ${s}ms`),t.onFailure?.(`agent ${t.agentId} timed out after ${s}ms`),c(void 0)},s),i.unref?.(),a.then(l=>{i&&clearTimeout(i),o||c(l)},l=>{i&&clearTimeout(i),o||d(l)})})}catch(a){let c=a.message;t.logger?.warn(`synopsis: agent ${t.agentId} failed: ${c}`),t.onFailure?.(`agent ${t.agentId} failed: ${c}`);return}finally{i&&clearTimeout(i),r&&await r.kill().catch(()=>{})}}async function fm(t){let e=ci(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp title-regen worker for session ${t.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${n}
222
222
 
223
223
  ${e}
224
224
 
225
- ${Xc}`:`${n}
225
+ ${cl}`:`${n}
226
226
 
227
- ${Xc}`;return Gp(t,s,zp)}async function Xp(t){let e=Xr(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
227
+ ${cl}`;return um(t,s,om)}async function pm(t){let e=ci(t.history,{maxChars:t.maxTranscriptChars}),n=t.sessionId!==void 0?`[hydra-acp compaction worker for session ${t.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${n}
228
228
 
229
229
  ${e}
230
230
 
231
- ${Zc}`:`${n}
231
+ ${ll}`:`${n}
232
232
 
233
- ${Zc}`;return Gp(t,s,Jp)}function RS(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function TS(t){let e=new Set;Vp(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&Vp(e,n.availableModels),e}function Vp(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}cl();pe();var ES=2,$a=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??ES}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]="title",this.drain())}scheduleCompaction(e){if(this.stopped||this.inflight.has(e))return;if(this.queued[e]==="title"){this.queued[e]="compaction";return}this.queued[e]="compaction",this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=n-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){try{let s=await this.opts.store.read(e);if(!s){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let r=await this.opts.histories.load(e,{maxEntries:1/0}),i=s.summarizedThroughEntry;if(i!==void 0&&r.length<=i){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${r.length})`);return}let o=n==="compaction"?this.opts.compactionAgent??s.agentId:this.opts.synopsisAgent??s.agentId,a=await this.opts.registry.getAgent(o);if(!a){this.opts.logger?.warn(`synopsis: agent ${o} not in registry for session ${e}; skipping`);return}let c=await cn(a,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.compactionAgent===void 0,l=n==="compaction"?this.opts.compactionModel??(d?s.currentModel:void 0):this.opts.synopsisModel,f=_.sessionDir(e);if(await dm.mkdir(f,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${r.length} model=${JSON.stringify(l??"(default)")} cwd=${f}`),n==="compaction"){let u=this.opts.compactionMaxIterations??3,p=0,m=i??0,h,w=0,b,v=Date.now();await this.opts.onCompactionStateChange?.(e,{status:"requested",requestedAt:v}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"started",requestedAt:v});try{do{p++,this.opts.logger?.info(`synopsis: compaction iteration ${p} sessionId=${e} historyLen=${r.length} watermark=${m}`);let S=await this.opts.histories.load(e,{maxEntries:1/0});if(S.length<=m)break;let x=await Xp({agentId:o,cwd:f,plan:c,history:S,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(F,$)=>{this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,iter:p,worker:{upstreamSessionId:F,pid:$??0}})},onFailure:F=>{b=F}});if(x){let F=im(x.synopsis,S);F&&om(F)&&(await this.opts.persistSynopsis(e,F,S.length),h=F,w=S.length,b=void 0,await this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,iter:p}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"iteration",iter:p,historyLen:S.length}),await this.opts.onCompactionArtifact?.(e,F,w),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${p} fields=${am(F)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${p} returned no result`);if(m=S.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(p<u);if(h)p>=u&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${w} iterations=${p}`);else{p>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${u} without producing artifact sessionId=${e}: ${b??"no reason captured"}`);let S=b??(p===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${p} iteration(s)`);await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:v,iter:p,lastError:S}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:S})}}catch(S){let x=S instanceof Error?S.message:String(S);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${x}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:v,iter:p,lastError:x}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:x})}}else{let u=await Qp({agentId:o,cwd:f,plan:c,history:r,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!u){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let p=im(u.synopsis,r);p&&om(p)?(await this.opts.persistSynopsis(e,p,r.length),u.title&&await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!u.title)} fields=${am(p)}`)):u.title&&(await this.opts.persistTitle(e,u.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function im(t,e){let n=nm(e),s=tm(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function om(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function am(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}pe();import*as xt from"fs/promises";function cm(t){return t==="summary"?"summary":"inline"}var ll=256;function lm(t,e){return e!=="summary"?t:t.map(PS)}function PS(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(um));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=ul(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function MS(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function um(t){if(MS(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=ul(e.text)),typeof e.content=="string"?n.content=ul(e.content):e.content&&typeof e.content=="object"&&(n.content=um(e.content)),n}function ul(t){if(typeof t=="string"&&t.length>ll){let e=t.length-ll;return`${t.slice(0,ll)}\u2026[+${e} chars omitted from summary export]`}return t}var _S=2048;function fm(t){let e=new Set,n=s=>{if(pm(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function pm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function $S(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function ml(t,e){if(!$S(t))return t;let n=t.params,s=n.update,r=await fl(s,e);return{...t,params:{...n,update:r}}}async function fl(t,e){if(typeof t=="string"){if(t.length<=_S)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await fl(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await fl(r,e);return n}return t}async function mm(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await pl(n,e);return s===n?t:{...t,params:s}}async function pl(t,e){if(pm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await pl(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await pl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var po=/^[A-Za-z0-9_-]+$/,OS=1e3,Oa=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??OS}async append(e,n){if(po.test(e))return this.enqueue(e,async()=>{await xt.mkdir(_.sessionDir(e),{recursive:!0});let s=await ml(n,i=>Rc(e,i)),r=JSON.stringify(s)+`
234
- `;await xt.appendFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(po.test(e))return this.enqueue(e,async()=>{await xt.mkdir(_.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await ml(i,o=>Rc(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
233
+ ${ll}`;return um(t,s,am)}function KS(t){if(!t||typeof t!="object")return"";let e=t.update;if(!e||typeof e!="object")return"";let n=e;if(n.sessionUpdate!=="agent_message_chunk")return"";let s=n.content;return s&&typeof s.text=="string"?s.text:""}function VS(t){let e=new Set;lm(e,t.availableModels);let n=t.models;return n&&typeof n=="object"&&!Array.isArray(n)&&lm(e,n.availableModels),e}function lm(t,e){if(Array.isArray(e)){for(let n of e)if(n&&typeof n=="object"){let s=n.modelId??n.value??n.id;typeof s=="string"&&s.length>0&&t.add(s)}}}vl();he();var YS=2,Ja=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??YS}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]="title",this.drain())}scheduleCompaction(e){if(this.stopped||this.inflight.has(e))return;if(this.queued[e]==="title"){this.queued[e]="compaction";return}this.queued[e]="compaction",this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let n=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=n-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let n=Object.keys(this.queued)[0];if(!n)return;let s=this.queued[n];delete this.queued[n];let r=this.runOne(n,s).finally(()=>{this.inflight.delete(n),this.drain()});this.inflight.set(n,r)}}async runOne(e,n){try{let s=await this.opts.store.read(e);if(!s){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let r=await this.opts.histories.load(e,{maxEntries:1/0}),i=s.summarizedThroughEntry;if(i!==void 0&&r.length<=i){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${r.length})`);return}let o=n==="compaction"?this.opts.compactionAgent??s.agentId:this.opts.synopsisAgent??s.agentId,a=await this.opts.registry.getAgent(o);if(!a){this.opts.logger?.warn(`synopsis: agent ${o} not in registry for session ${e}; skipping`);return}let c=await hn(a,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.compactionAgent===void 0,l=n==="compaction"?this.opts.compactionModel??(d?s.currentModel:void 0):this.opts.synopsisModel,u=$.sessionDir(e);if(await Im.mkdir(u,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${o} historyLen=${r.length} model=${JSON.stringify(l??"(default)")} cwd=${u}`),n==="compaction"){let f=this.opts.compactionMaxIterations??3,p=0,m=i??0,h,y=0,b,v=Date.now();await this.opts.onCompactionStateChange?.(e,{status:"requested",requestedAt:v}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"started",requestedAt:v});try{do{p++,this.opts.logger?.info(`synopsis: compaction iteration ${p} sessionId=${e} historyLen=${r.length} watermark=${m}`);let S=await this.opts.histories.load(e,{maxEntries:1/0});if(S.length<=m)break;let x=await pm({agentId:o,cwd:u,plan:c,history:S,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(_,F)=>{this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,iter:p,worker:{upstreamSessionId:_,pid:F??0}})},onFailure:_=>{b=_}});if(x){let _=vm(x.synopsis,S);_&&Sm(_)&&(await this.opts.persistSynopsis(e,_,S.length),h=_,y=S.length,b=void 0,await this.opts.onCompactionStateChange?.(e,{status:"running",requestedAt:v,iter:p}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"iteration",iter:p,historyLen:S.length}),await this.opts.onCompactionArtifact?.(e,_,y),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${p} fields=${km(_)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${p} returned no result`);if(m=S.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===m)break}while(p<f);if(h)p>=f&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${p}`);else{p>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${f} without producing artifact sessionId=${e}: ${b??"no reason captured"}`);let S=b??(p===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${p} iteration(s)`);await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:v,iter:p,lastError:S}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:S})}}catch(S){let x=S instanceof Error?S.message:String(S);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${x}`),await this.opts.onCompactionStateChange?.(e,{status:"failed",requestedAt:v,iter:p,lastError:x}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:x})}}else{let f=await fm({agentId:o,cwd:u,plan:c,history:r,modelId:l,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!f){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let p=vm(f.synopsis,r);p&&Sm(p)?(await this.opts.persistSynopsis(e,p,r.length),f.title&&await this.opts.persistTitle(e,f.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${km(p)}`)):f.title&&(await this.opts.persistTitle(e,f.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(s){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${s.message}`)}}};function vm(t,e){let n=ym(e),s=gm(e);return t?{...t,files_touched:n.length>0?n:t.files_touched,tools_used:s.length>0?s:t.tools_used}:n.length===0&&s.length===0?void 0:{files_touched:n.length>0?n:void 0,tools_used:s.length>0?s:void 0}}function Sm(t){return!!(t.goal&&t.goal.trim().length>0||t.outcome&&t.outcome.trim().length>0||t.files_touched&&t.files_touched.length>0||t.tools_used&&t.tools_used.length>0||t.rejected_approaches&&t.rejected_approaches.length>0||t.open_threads&&t.open_threads.length>0)}function km(t){let e=[];return t.goal&&e.push("goal"),t.outcome&&e.push("outcome"),t.files_touched&&t.files_touched.length>0&&e.push(`files=${t.files_touched.length}`),t.tools_used&&t.tools_used.length>0&&e.push(`tools=${t.tools_used.length}`),t.rejected_approaches&&t.rejected_approaches.length>0&&e.push(`rejected=${t.rejected_approaches.length}`),t.open_threads&&t.open_threads.length>0&&e.push(`open=${t.open_threads.length}`),`[${e.join(",")}]`}he();import*as Ct from"fs/promises";function xm(t){return t==="summary"?"summary":"inline"}var Sl=256;function Cm(t,e){return e!=="summary"?t:t.map(QS)}function QS(t){if(t.method!=="session/update")return t;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return t;let n=e,s=n.update;if(!s||typeof s!="object"||Array.isArray(s))return t;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return t;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(Am));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,c={};a.error!==void 0&&(c.error=kl(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),i.rawOutput=c}return{...t,params:{...n,update:i}}}function GS(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&t.type==="diff"}function Am(t){if(GS(t)){let s=t,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!t||typeof t!="object"||Array.isArray(t))return t;let e=t,n={...e};return typeof e.text=="string"&&(n.text=kl(e.text)),typeof e.content=="string"?n.content=kl(e.content):e.content&&typeof e.content=="object"&&(n.content=Am(e.content)),n}function kl(t){if(typeof t=="string"&&t.length>Sl){let e=t.length-Sl;return`${t.slice(0,Sl)}\u2026[+${e} chars omitted from summary export]`}return t}var XS=2048;function Rm(t){let e=new Set,n=s=>{if(Tm(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))n(r)};for(let s of t)n(s.params);return e}function Tm(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.__hydraBlob=="string"}function ZS(t){if(t.method!=="session/update")return!1;let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return!1;let s=n.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function Cl(t,e){if(!ZS(t))return t;let n=t.params,s=n.update,r=await Il(s,e);return{...t,params:{...n,update:r}}}async function Il(t,e){if(typeof t=="string"){if(t.length<=XS)return t;let n=await e(t);return n===null?t:{__hydraBlob:n,bytes:t.length}}if(Array.isArray(t)){let n=[];for(let s of t)n.push(await Il(s,e));return n}if(t&&typeof t=="object"){let n={};for(let[s,r]of Object.entries(t))n[s]=await Il(r,e);return n}return t}async function Em(t,e){let n=t.params;if(!n||typeof n!="object"||Array.isArray(n))return t;let s=await xl(n,e);return s===n?t:{...t,params:s}}async function xl(t,e){if(Tm(t))return await e(t.__hydraBlob)??"";if(Array.isArray(t)){let n=!1,s=[];for(let r of t){let i=await xl(r,e);i!==r&&(n=!0),s.push(i)}return n?s:t}if(t&&typeof t=="object"){let n=!1,s={};for(let[r,i]of Object.entries(t)){let o=await xl(i,e);o!==i&&(n=!0),s[r]=o}return n?s:t}return t}var Io=/^[A-Za-z0-9_-]+$/,ek=1e3,Ka=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??ek}async append(e,n){if(Io.test(e))return this.enqueue(e,async()=>{await Ct.mkdir($.sessionDir(e),{recursive:!0});let s=await Cl(n,i=>Nc(e,i)),r=JSON.stringify(s)+`
234
+ `;await Ct.appendFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,n){if(Io.test(e))return this.enqueue(e,async()=>{await Ct.mkdir($.sessionDir(e),{recursive:!0});let s=[];for(let i of n)s.push(await Cl(i,o=>Nc(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
235
235
  `)+`
236
- `;await xt.writeFile(_.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(po.test(e))return this.enqueue(e,async()=>{let s;try{s=await xt.readFile(_.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
237
- `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await xt.writeFile(_.historyFile(e),i.join(`
236
+ `;await Ct.writeFile($.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,n){if(Io.test(e))return this.enqueue(e,async()=>{let s;try{s=await Ct.readFile($.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
237
+ `).filter(o=>o.length>0);if(r.length<=n)return;let i=r.slice(-n);await Ct.writeFile($.historyFile(e),i.join(`
238
238
  `)+`
239
- `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!po.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await xt.readFile(_.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
240
- `)){if(u.length===0)continue;let p;try{p=JSON.parse(u)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&o.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async u=>{let p=d.get(u);if(p!==void 0)return p;let m=await ha(e,u);return d.set(u,m),m},f=[];for(let u of c)f.push(await mm(u,l));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(po.test(e))return this.enqueue(e,async()=>{try{await xt.unlink(_.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await Vf(e);try{await xt.rmdir(_.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};pe();Ne();La();or();Ra();It();Nt();Kc();var ym=900*1e3,wm=5e3,bm=3,HS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ba=DS(HS,16),Na=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>ps.spawn(a)),this.store=s??new Pa,this.tombstones=r.tombstones??new Ma,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Oa({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let i=r.compaction??{},o=i.tailK??20;this.compactionTailK=o,this.synopsisCoordinator=new $a({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c)=>{let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c)=>{this.broadcastHydraCompaction(a,c)},onCompactionArtifact:async(a,c,d)=>{let l=this.get(a);if(!l){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${a}`),await this.mutateRecord(a,{synopsis:c,summarizedThroughEntry:d});return}try{if(!await l.isQuiescedForSwap()){let u=this.compactionDeferrals.get(a)??0;if(u++,u>bm){this.logger?.warn(`compaction: deferral cap reached for sessionId=${a}, skipping swap until next trigger`),this.compactionDeferrals.delete(a),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"]),l.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached"});return}this.compactionDeferrals.set(a,u),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${u}`),l.broadcastCompactionPhase({phase:"deferred",attempts:u}),setTimeout(()=>{this.retrySwap(a)},wm).unref();return}this.compactionDeferrals.delete(a),await l.swapUpstream({artifact:c,tailK:o,summarizedThroughEntry:d}),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"])}catch(f){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${f instanceof Error?f.message:String(f)}, leaving session as-is`)}}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;compactionDeferrals=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async retrySwap(e){let n=this.get(e);if(!n){this.compactionDeferrals.delete(e);return}let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let o=this.compactionDeferrals.get(e)??0;if(o++,o>bm){this.logger?.warn(`compaction: deferral cap reached on retry for sessionId=${e}, giving up`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]),n.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached on retry"});return}this.compactionDeferrals.set(e,o),this.logger?.info(`compaction: still not quiesced on retry, re-deferring sessionId=${e} attempt=${o}`),setTimeout(()=>{this.retrySwap(e)},wm).unref();return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing on retry for sessionId=${e}, skipping swap`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}this.compactionDeferrals.delete(e),await n.swapUpstream({artifact:i.synopsis,tailK:s,summarizedThroughEntry:i.summarizedThroughEntry}),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"])}catch(r){this.logger?.warn(`compaction: retrySwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async refreshAgentCatalog(){try{let{agents:e}=await Kr(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let r={...n.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Ba()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}n.agentCapabilities=r}let s=new ni({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:r.mcpServers??[]}),loadExistingAgentSession:(r,i)=>this.bootstrapAgentLoad(r,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(s.sessionId),getCompactionState:()=>this.getCompactionState(s.sessionId),uncompactHook:()=>this.performUncompact(s.sessionId),onCompactionSwapHook:r=>{this.mutateRecord(s.sessionId,{rollbackBreadcrumb:r}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(s.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(s),s}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=z.AlreadyAttached,i}return n}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=z.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await cn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let h=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});o=h.agentCapabilities,i.authMethods=wo(h.authMethods)}catch(h){throw await i.kill().catch(()=>{}),ms(h,i)}let a;try{let h=vm(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){if(h&&typeof h=="object"&&h.code===z.AuthRequired)throw await i.kill().catch(()=>{}),ms(h,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
241
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=Sl(a??{}),d=e.agentModes??wl(vl(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(h=>h.id))}`);let l=await Yr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:d,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let f=yl(a??{}),u=wl(bl(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(u?.map(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Vr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new ni({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:h=>this.bootstrapAgent({...h,mcpServers:h.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(h,w)=>this.bootstrapAgentLoad(h,{...w,mcpServers:w.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:d,agentModels:u,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(m.sessionId),getCompactionState:()=>this.getCompactionState(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:h=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:h}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Yr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Vr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new ni({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(c.sessionId),getCompactionState:()=>this.getCompactionState(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await ar.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:je(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=z.AgentNotInstalled,p}let s=await cn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Da.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}})}catch(p){throw await r.kill().catch(()=>{}),ms(p,r)}if(r.authMethods=wo(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=_.sessionsDir(),f=[],u=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(c.has(m)){u+=1;continue}if(US(p.cwd,l)){u+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!Yp(h,p.updatedAt)){u+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${h.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let w=`${Jt}${Ba()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:w,lineageId:uo(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(S.title=p.title);let x=il(S);await this.store.write(x),f.push({version:1,...x})}return{synced:f,skipped:u}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=z.AgentNotInstalled,i}let s=await cn(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}}),o=i.agentCapabilities;r.authMethods=wo(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let d=yl(a),l=bl(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==d){let m=Qr(f,l),h=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,f,h)&&(d=f);else if(m.kind==="resolved")(m.modelId===d||await this.applySeedModel(r,c,m.modelId,`${h} resolved to ${JSON.stringify(m.modelId)}`))&&(d=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let w=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${w}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let u=vl(a),p=Sl(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:o,initialModel:d,initialModels:l.length>0?l:void 0,initialModes:u.length>0?u:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ms(i,r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=z.AgentNotInstalled,o}let r=await cn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}}),a=o.agentCapabilities;i.authMethods=wo(o.authMethods);let c=vm(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=yl(d),f=wl(bl(d)),u=vl(d),p=Sl(d);return{agent:i,upstreamSessionId:e,agentMeta:d._meta,agentCapabilities:a,initialModel:l,initialModels:f,initialModes:u.length>0?u:void 0,initialMode:p}}catch(o){throw await i.kill().catch(()=>{}),ms(o,i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=z.AgentNotInstalled,c}let i=await cn(r,[],{npmRegistry:this.npmRegistry}),o=n??je(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:fe}});a.authMethods=wo(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),ms(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=z.AgentNotInstalled,s}return cn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=ii({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:km(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=jS(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return ha(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:qS(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=ei(r.update.prompt),o=Qc(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Jt))return;let n=Jt+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=z.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await bo(n.sessionId),c=ii({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"live",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await bo(s.sessionId),i=ii(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>bo(l.sessionId)));for(let l=0;l<i.length;l+=1){let f=i[l],u=o[l];s.add(f.sessionId);let p=ii({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},u.hasContent);if(!r(p))continue;let m=u.mtime??new Date(f.updatedAt).toISOString();n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"live",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>bo(l.sessionId)));for(let l=0;l<c.length;l+=1){let f=c[l],u=d[l],p=ii(f,u.hasContent);if(!r(p))continue;let m=u.mtime??f.updatedAt;n.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:p,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState})}return n.sort((l,f)=>l.updatedAt<f.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=uo(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Sm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of fm(o)){let l=await Kf(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=z.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Jt}${Ba()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let m=new Error(`source session not found: ${e}`);throw m.code=z.SessionNotFound,m}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=z.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,c;if(n.forkAt!==void 0){if(a=Gc(o,n.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw m.code=z.InvalidParams,m}c=n.forkAt}else{let m=zS(o);m?(a=m.index,c=m.messageId):(a=-1,c="")}let d=o.slice(0,a+1),l=await Sm(e),f={...s,lineageId:uo(),agentId:r,interactive:!1,...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},u=yo({record:f,history:d,promptHistory:l.length>0?l:void 0,hydraVersion:fe,machine:Da.hostname()}),p=`${Jt}${Ba()}`;return await this.writeImportedRecord({sessionId:p,bundle:u,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c}),{sessionId:p,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await Yf(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await ar.utimes(_.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await ir(_.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let n=await this.store.read(e);if(!n)return!1;if(n.upstreamSessionId){let s=await bo(e),r=ii(n,s.hasContent);await this.tombstones.add({agentId:n.agentId,upstreamSessionId:n.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:n.updatedAt,cwd:n.cwd,title:n.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(n),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e){this.synopsisCoordinator.scheduleCompaction(e)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}broadcastHydraCompaction(e,n){let s=this.get(e);s&&s.broadcastCompactionPhase(n)}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Op(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<ym),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${ym/1e3}s)`),await ao(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await ao(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function US(t,e){if(typeof t!="string"||t.length===0)return!1;let n=vo.resolve(t),s=vo.resolve(e);return n===s||n.startsWith(s+vo.sep)}function jS(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let f={id:l.id};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let f={modelId:l.modelId};return l.name!==void 0&&(f.name=l.name),l.description!==void 0&&(f.description=l.description),f}):void 0)??e?.agentModels;return il({sessionId:t.sessionId,lineageId:e?.lineageId??uo(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:km(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function km(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function qS(t){return t?{...t}:void 0}function vm(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ha(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=WS(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function yl(t){return Ha(t,{nestedKey:"models",configId:"model",fromObject:e=>An(e.currentModelId)??An(e.currentModel)??An(e.modelId)??An(e.model),fromConfig:e=>An(e.currentValue)})}function ms(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==z.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=z.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function wo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function An(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function WS(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function wl(t){return t.length>0?t:void 0}function bl(t){return Ha(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=ti(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=ti(e.options);return n.length>0?n:void 0}})??[]}function vl(t){return Ha(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=co(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=co(e.options);return n.length>0?n:void 0}})??[]}function Sl(t){return Ha(t,{nestedKey:"modes",configId:"mode",fromObject:e=>An(e.currentModeId)??An(e.currentMode)??An(e.modeId)??An(e.mode),fromConfig:e=>An(e.currentValue)})}function zS(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Sm(t){try{let e=await ar.readFile(_.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
242
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function bo(t){try{let e=await ar.stat(_.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function ii(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===rr?!1:e?!0:void 0}import{spawn as JS}from"child_process";import*as ai from"fs";import*as hs from"fs/promises";import*as Im from"path";var Ua=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};Ne();var KS=1e3,YS=6e4,kl=3e3,oi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??KS,this.restartCapMs=r.restartCapMs??YS;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await hs.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},kl);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw So(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw So(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw So(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw So(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw So(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},kl);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Ua(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await hs.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=Im.join(this.adapter.paths.dir(),n),r;try{let i=await hs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Il(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+kl;for(;Date.now()<i&&Il(r);)await new Promise(o=>setTimeout(o,50));if(Il(r))try{process.kill(r,"SIGKILL")}catch{}}await hs.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=ai.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
239
+ `,{encoding:"utf8",mode:384})})}async load(e,n={}){if(!Io.test(e))return[];let s=(n.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Ct.readFile($.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let o=[];for(let f of i.split(`
240
+ `)){if(f.length===0)continue;let p;try{p=JSON.parse(f)}catch{continue}if(!p||typeof p!="object"||Array.isArray(p))continue;let m=p;typeof m.method=="string"&&typeof m.recordedAt=="number"&&o.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=n.maxEntries??this.maxEntries,c=o.length>a?o.slice(-a):o;if(!s)return c;let d=new Map,l=async f=>{let p=d.get(f);if(p!==void 0)return p;let m=await Ta(e,f);return d.set(f,m),m},u=[];for(let f of c)u.push(await Em(f,l));return u}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Io.test(e))return this.enqueue(e,async()=>{try{await Ct.unlink($.historyFile(e))}catch(n){if(n.code!=="ENOENT")throw n}await dp(e);try{await Ct.rmdir($.sessionDir(e))}catch(n){let s=n;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw n}})}enqueue(e,n){let r=(this.writeQueues.get(e)??Promise.resolve()).then(n,n),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};he();je();Ya();yr();Ha();xt();Wt();rl();var _m=900*1e3,$m=5e3,Fm=3,ok="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qa=ik(ok,16),Ga=class t{constructor(e,n,s,r={}){this.registry=e;this.spawner=n??(a=>Cs.spawn(a)),this.store=s??new qa,this.tombstones=r.tombstones??new Wa,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Ka({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 Ja({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:i.maxIterations,persistTitle:async(a,c)=>{let d=this.get(a);if(d){await d.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,d)=>this.persistSynopsis(a,c,d),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c)=>{let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c)=>{this.broadcastHydraCompaction(a,c)},onCompactionArtifact:async(a,c,d)=>{let l=this.get(a);if(!l){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${a}`),await this.mutateRecord(a,{synopsis:c,summarizedThroughEntry:d});return}try{if(!await l.isQuiescedForSwap()){let f=this.compactionDeferrals.get(a)??0;if(f++,f>Fm){this.logger?.warn(`compaction: deferral cap reached for sessionId=${a}, skipping swap until next trigger`),this.compactionDeferrals.delete(a),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"]),l.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached"});return}this.compactionDeferrals.set(a,f),this.logger?.info(`compaction: session not quiesced, deferring swap sessionId=${a} attempt=${f}`),l.broadcastCompactionPhase({phase:"deferred",attempts:f}),setTimeout(()=>{this.retrySwap(a)},$m).unref();return}this.compactionDeferrals.delete(a),await l.swapUpstream({artifact:c,tailK:o,summarizedThroughEntry:d}),l.compactionState=void 0,await this.mutateRecord(a,{},["compactionState"])}catch(u){this.logger?.warn(`compaction: swap failed for sessionId=${a}: ${u instanceof Error?u.message:String(u)}, leaving session as-is`)}}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;compactionDeferrals=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async retrySwap(e){let n=this.get(e);if(!n){this.compactionDeferrals.delete(e);return}let s=this.compactionTailK;try{if(!await n.isQuiescedForSwap()){let o=this.compactionDeferrals.get(e)??0;if(o++,o>Fm){this.logger?.warn(`compaction: deferral cap reached on retry for sessionId=${e}, giving up`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]),n.broadcastCompactionPhase({phase:"failed",error:"deferral cap reached on retry"});return}this.compactionDeferrals.set(e,o),this.logger?.info(`compaction: still not quiesced on retry, re-deferring sessionId=${e} attempt=${o}`),setTimeout(()=>{this.retrySwap(e)},$m).unref();return}let i=await this.store.read(e).catch(()=>{});if(!i?.synopsis||i.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing on retry for sessionId=${e}, skipping swap`),this.compactionDeferrals.delete(e),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}this.compactionDeferrals.delete(e),await n.swapUpstream({artifact:i.synopsis,tailK:s,summarizedThroughEntry:i.summarizedThroughEntry}),n.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"])}catch(r){this.logger?.warn(`compaction: retrySwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async refreshAgentCatalog(){try{let{agents:e}=await ri(this.registry);this.agentCatalog=e.map(n=>({id:n.id,name:n.name,...n.description!==void 0?{description:n.description}:{}}))}catch{}}async create(e){let n=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let r={...n.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Qa()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}n.agentCapabilities=r}let s=new fi({cwd:e.cwd,agentId:e.agentId,agent:n.agent,upstreamSessionId:n.upstreamSessionId,agentMeta:n.agentMeta,agentCapabilities:n.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:r.mcpServers??[]}),loadExistingAgentSession:(r,i)=>this.bootstrapAgentLoad(r,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:n.initialModel,currentMode:n.initialMode,agentModes:n.initialModes,agentModels:n.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(s.sessionId),getCompactionState:()=>this.getCompactionState(s.sessionId),uncompactHook:()=>this.performUncompact(s.sessionId),onCompactionSwapHook:r=>{this.mutateRecord(s.sessionId,{rollbackBreadcrumb:r}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(s.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(s),s}async resurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n){if(n.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=W.AlreadyAttached,i}return n}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let n=this.sessions.get(e.hydraSessionId);if(n)return n;let s=await this.registry.getAgent(e.agentId);if(!s){let h=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw h.code=W.AgentNotInstalled,h}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await hn(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let h=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}});o=h.agentCapabilities,i.authMethods=To(h.authMethods)}catch(h){throw await i.kill().catch(()=>{}),As(h,i)}let a;try{let h=Om(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...h&&{_meta:h}})}catch(h){if(h&&typeof h=="object"&&h.code===W.AuthRequired)throw await i.kill().catch(()=>{}),As(h,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${h.message}); recovering via import-reseed
241
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=_l(a??{}),d=e.agentModes??El(Ml(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(d?.map(h=>h.id))}`);let l=await ii({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=Tl(a??{}),f=El(Pl(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(h=>h.modelId))}`),e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await oi({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let h=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${h} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new fi({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:h=>this.bootstrapAgent({...h,mcpServers:h.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(h,y)=>this.bootstrapAgentLoad(h,{...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(m.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(m.sessionId),getCompactionState:()=>this.getCompactionState(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:h=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:h}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let n=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:n,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await ii({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await oi({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new fi({sessionId:e.hydraSessionId,cwd:n,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:d=>this.bootstrapAgent({...d,mcpServers:d.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(d,l)=>this.bootstrapAgentLoad(d,{...l,mcpServers:l.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:()=>this.synopsisCoordinator.scheduleCompaction(c.sessionId),getCompactionState:()=>this.getCompactionState(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:d=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:d}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await wr.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let n=this.sessions.get(e);!n||n.attachedCount>0||n.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await n.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Je(this.defaultCwd)}async syncFromAgent(e){let n=await this.registry.getAgent(e);if(!n){let p=new Error(`agent ${e} not found in registry`);throw p.code=W.AgentNotInstalled,p}let s=await hn(n,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Xa.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}})}catch(p){throw await r.kill().catch(()=>{}),As(p,r)}if(r.authMethods=To(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let c=new Set;for(let p of this.sessions.values())c.add(`${p.agentId}::${p.upstreamSessionId}`);let d=await this.store.list().catch(()=>[]);for(let p of d)c.add(`${p.agentId}::${p.upstreamSessionId}`);let l=$.sessionsDir(),u=[],f=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(c.has(m)){f+=1;continue}if(ak(p.cwd,l)){f+=1;continue}let h=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(h){if(!cm(h,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 ${h.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let y=`${Zt}${Qa()}`,b=new Date().toISOString(),v=p.updatedAt??b,S={sessionId:y,lineageId:So(),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=gl(S);await this.store.write(x),u.push({version:1,...x})}return{synced:u,skipped:f}}async collectAgentSessions(e){let n=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),c=Array.isArray(a.sessions)?a.sessions:[];for(let d of c){if(typeof d.sessionId!="string"||typeof d.cwd!="string")continue;let l={sessionId:d.sessionId,cwd:d.cwd};typeof d.title=="string"&&(l.title=d.title),typeof d.updatedAt=="string"&&(l.updatedAt=d.updatedAt),n.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return n}async applySeedModel(e,n,s,r){try{return await e.connection.request("session/set_model",{sessionId:n,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let n=await this.registry.getAgent(e.agentId);if(!n){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=W.AgentNotInstalled,i}let s=await hn(n,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}}),o=i.agentCapabilities;r.authMethods=To(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=Tl(a),l=Pl(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==d){let m=di(u,l),h=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,u,h)&&(d=u);else if(m.kind==="resolved")(m.modelId===d||await this.applySeedModel(r,c,m.modelId,`${h} resolved to ${JSON.stringify(m.modelId)}`))&&(d=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${h} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(d)}`);else{let y=l.map(b=>b.modelId).join(", ");this.logger?.warn(`${h} not in agent's availableModels ([${y}]); skipping session/set_model, session will use ${JSON.stringify(d)}`)}}let f=Ml(a),p=_l(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(()=>{}),As(i,r)}}async bootstrapAgentLoad(e,n){let s=await this.registry.getAgent(n.agentId);if(!s){let o=new Error(`agent ${n.agentId} not found in registry`);throw o.code=W.AgentNotInstalled,o}let r=await hn(s,n.agentArgs??[],{npmRegistry:this.npmRegistry}),i=this.spawner({agentId:n.agentId,cwd:n.cwd,plan:r,...n.forwardedEnv?{extraEnv:n.forwardedEnv}:{}});try{let o=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}}),a=o.agentCapabilities;i.authMethods=To(o.authMethods);let c=Om(n.agentId,void 0),d=await i.connection.request("session/load",{sessionId:e,cwd:n.cwd,mcpServers:n.mcpServers??[],...c&&{_meta:c}}),l=Tl(d),u=El(Pl(d)),f=Ml(d),p=_l(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(()=>{}),As(o,i)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let n=this.get(e);if(!n)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let i=s.compactionState;if(i!=null)throw new Error(`compaction is in progress (status: ${i.status}) \u2014 wait for it to complete before rolling back`);if(!await n.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await n.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,n){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=W.AgentNotInstalled,c}let i=await hn(r,[],{npmRegistry:this.npmRegistry}),o=n??Je(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:pe}});a.authMethods=To(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),As(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let n=await this.registry.getAgent(e);if(!n){let s=new Error(`agent ${e} not found in registry`);throw s.code=W.AgentNotInstalled,s}return hn(n,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let n=this.pendingAuthAgents.get(e);if(n&&(this.pendingAuthAgents.delete(e),!!n.isAlive()))return n}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:n})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),n){if(e.upstreamSessionId){let s=gi({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}}),e.onTitleChange(n=>{this.persistTitle(e.sessionId,n).catch(()=>{})}),e.onPriorityChange(n=>{this.persistPriority(e.sessionId,n).catch(()=>{})}),e.onAgentChange(({agentId:n,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,n,s).catch(()=>{})}),e.onModelChange(n=>{this.persistSnapshot(e.sessionId,{currentModel:n}).catch(()=>{})}),e.onModeChange(n=>{this.persistSnapshot(e.sessionId,{currentMode:n}).catch(()=>{})}),e.onInteractiveChange(n=>{this.persistSnapshot(e.sessionId,{interactive:n}).catch(()=>{})}),e.onUsageChange(n=>{this.persistSnapshot(e.sessionId,{currentUsage:Bm(n)}).catch(()=>{})}),e.onAgentCommandsChange(n=>{this.persistSnapshot(e.sessionId,{agentCommands:n.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(n=>{this.persistSnapshot(e.sessionId,{agentModes:n.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(n=>{this.persistSnapshot(e.sessionId,{agentModels:n.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(n=>{this.mutateRecord(e.sessionId,{attentionFlags:n}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let n=await this.store.read(e.sessionId),s=dk(e,n);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,n){return Ta(e,n)}async loadFromDisk(e){let n=await this.store.read(e);if(!n)return;let s=n.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,agentId:n.agentId,cwd:n.cwd,title:s,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:ck(n.currentUsage?{...n.currentUsage,cumulativeCost:(n.currentUsage.cumulativeCost??0)+(n.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,createdAt:n.createdAt,pendingHistorySync:n.pendingHistorySync,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forwardedEnv:n.forwardedEnv,compactionState:n.compactionState,attentionFlags:n.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,n){if(n===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=n),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:n};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let n=await this.store.read(e);if(!n||n.pendingHistorySync!==!0)return;let s={...n};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let n=await this.histories.load(e).catch(()=>[]);for(let s of n){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=li(r.update.prompt),o=dl(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let n of this.sessions.values()){let s=n.agent.agentId,r=n.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(Zt))return;let n=Zt+e;if(this.sessions.has(n)||await this.store.read(n))return n}require(e){let n=this.sessions.get(e);if(!n){let s=new Error(`session ${e} not found`);throw s.code=W.SessionNotFound,s}return n}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let n=this.sessions.get(e);if(n){let a=await Eo(n.sessionId),c=gi({interactive:n.interactive,...n.originatingClient?{originatingClient:n.originatingClient}:{}},a.hasContent),d=a.mtime??new Date(n.updatedAt).toISOString();return{sessionId:n.sessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:c,priority:n.priority,updatedAt:d,attachedClients:n.attachedCount,status:"live",busy:n.turnStartedAt!==void 0,awaitingInput:n.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await Eo(s.sessionId),i=gi(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let n=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(n);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(n,{expiresAt:s+t.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(n);o&&o.promise===i&&this.listCache.delete(n)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let n=[],s=new Set,r=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>Eo(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=gi({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let m=f.mtime??new Date(u.updatedAt).toISOString();n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput,compactionState:u.compactionState})}let c=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),d=await Promise.all(c.map(l=>Eo(l.sessionId)));for(let l=0;l<c.length;l+=1){let u=c[l],f=d[l],p=gi(u,f.hasContent);if(!r(p))continue;let m=f.mtime??u.updatedAt;n.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:u.compactionState})}return n.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),n}async exportBundle(e,n={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let d=So(),l={...s,lineageId:d};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:d}))}).catch(()=>{}),r=l}let i=n.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Lm(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let c={};for(let d of Rm(o)){let l=await op(e,d);l&&(c[d]=l.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:c}}async importBundle(e,n={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!n.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=W.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:n.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${Zt}${Qa()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:n.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,n={}){let s=await this.store.read(e);if(!s){let m=new Error(`source session not found: ${e}`);throw m.code=W.SessionNotFound,m}let r=n.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let h=new Error(`agent ${r} not found in registry`);throw h.code=W.AgentNotInstalled,h}let o=await this.histories.load(e).catch(()=>[]),a,c;if(n.forkAt!==void 0){if(a=al(o,n.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${n.forkAt}`);throw m.code=W.InvalidParams,m}c=n.forkAt}else{let m=uk(o);m?(a=m.index,c=m.messageId):(a=-1,c="")}let d=o.slice(0,a+1),l=await Lm(e),u={...s,lineageId:So(),agentId:r,interactive:!1,...n.title!==void 0?{title:n.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},f=Ro({record:u,history:d,promptHistory:l.length>0?l:void 0,hydraVersion:pe,machine:Xa.hostname()}),p=`${Zt}${Qa()}`;return await this.writeImportedRecord({sessionId:p,bundle:f,cwd:n.cwd,forkedFromSessionId:e,forkedFromMessageId:c}),{sessionId:p,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await ap(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let n=new Date(e.bundle.session.updatedAt);Number.isNaN(n.getTime())||await wr.utimes($.historyFile(e.sessionId),n,n).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await gr($.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,n="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await Eo(e),i=gi(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:n,...i!==void 0?{interactive:i}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,n){let s=this.get(e);if(s)return s.setPriority(n),!0;if(!await this.hasRecord(e))return!1;let r=n===void 0||n<=0?void 0:Math.floor(n);return await this.persistPriority(e,r),!0}async persistPriority(e,n){n===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:n}),this.invalidateListCache()}async setTitle(e,n){let s=this.get(e);return s?(await s.retitle(n),!0):await this.hasRecord(e)?(await this.persistTitle(e,n),!0):!1}async persistTitle(e,n){await this.mutateRecord(e,{title:n})}async persistSynopsis(e,n,s){await this.mutateRecord(e,{synopsis:n,summarizedThroughEntry:s})}async persistAgentChange(e,n,s){await this.mutateRecord(e,{agentId:n,upstreamSessionId:s})}async persistSnapshot(e,n){let s={};n.currentModel!==void 0&&(s.currentModel=n.currentModel),n.currentMode!==void 0&&(s.currentMode=n.currentMode),n.currentUsage!==void 0&&(s.currentUsage=n.currentUsage),n.agentCommands!==void 0&&(s.agentCommands=n.agentCommands),n.agentModes!==void 0&&(s.agentModes=n.agentModes),n.agentModels!==void 0&&(s.agentModels=n.agentModels),n.interactive!==void 0&&(s.interactive=n.interactive),n.cwd!==void 0&&(s.cwd=n.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,n,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...n,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,n){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(n),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(n=>n.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e){this.synopsisCoordinator.scheduleCompaction(e)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}broadcastHydraCompaction(e,n){let s=this.get(e);s&&s.broadcastCompactionPhase(n)}async getSummarizedThroughEntry(e){let n=this.sessions.get(e);return n?n.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),n=0;for(let s of e){let r=s.attentionFlags??[],i=r.filter(o=>!(o.source==="daemon"&&o.reason.startsWith("permission:")));if(i.length!==r.length){let o=r.length-i.length;n+=o,await this.mutateRecord(s.sessionId,{attentionFlags:i}).catch(()=>{})}}n>0&&this.logger?.info(`cleared ${n} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),n=await this.store.list().catch(()=>[]);for(let s of n){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(i){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)}}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let n of e){let s=await Kp(n.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(c=>r-c.enqueuedAt<_m),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${n.sessionId} (TTL ${_m/1e3}s)`),await wo(n.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(n.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${n.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await wo(n.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${n.sessionId} and replaying ${i.length} prompt(s)`),c.replayPersistedQueue(i)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${n.sessionId}: ${c.message}`)}}}};function ak(t,e){if(typeof t!="string"||t.length===0)return!1;let n=Po.resolve(t),s=Po.resolve(e);return n===s||n.startsWith(s+Po.sep)}function dk(t,e){let s=(t.mergedAvailableCommands().length>0?t.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=t.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=t.availableModels(),d=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return gl({sessionId:t.sessionId,lineageId:e?.lineageId??So(),upstreamSessionId:t.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:t.agentId,cwd:t.cwd,title:t.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel??e?.currentModel,currentMode:t.currentMode??e?.currentMode,currentUsage:Bm(t.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,agentModels:d,parentSessionId:t.parentSessionId??e?.parentSessionId,forkedFromSessionId:t.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:t.originatingClient??e?.originatingClient,interactive:t.interactive??e?.interactive,priority:t.priority??e?.priority,forwardedEnv:t.forwardedEnv??e?.forwardedEnv,attentionFlags:t.listAttentionFlags(),createdAt:e?.createdAt??new Date(t.createdAt).toISOString()})}function Bm(t){if(!t)return;let e={};return t.used!==void 0&&(e.used=t.used),t.size!==void 0&&(e.size=t.size),t.costAmount!==void 0&&(e.costAmount=t.costAmount),t.costCurrency!==void 0&&(e.costCurrency=t.costCurrency),t.cumulativeCost!==void 0&&(e.cumulativeCost=t.cumulativeCost),Object.keys(e).length>0?e:void 0}function ck(t){return t?{...t}:void 0}function Om(t,e){if(e&&t==="claude-acp")return{claudeCode:{options:{model:e}}}}function Za(t,e){let n=e.fromObject(t);if(n!==void 0)return n;let s=t[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=t._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let i=lk(t,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Tl(t){return Za(t,{nestedKey:"models",configId:"model",fromObject:e=>Mn(e.currentModelId)??Mn(e.currentModel)??Mn(e.modelId)??Mn(e.model),fromConfig:e=>Mn(e.currentValue)})}function As(t,e){if(!t||typeof t!="object")return t;let n=t;if(n.code!==W.AuthRequired)return t;let s=d=>!!d&&typeof d=="object"&&!Array.isArray(d),r=s(n.data)?n.data:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof n.message=="string"?n.message:"authentication required",c=new Error(a);return c.code=W.AuthRequired,c.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function To(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let s=n;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,c=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...c&&{_meta:c}})}return e.length>0?e:void 0}function Mn(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function lk(t,e){let n=t.configOptions;if(Array.isArray(n))for(let s of n){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function El(t){return t.length>0?t:void 0}function Pl(t){return Za(t,{nestedKey:"models",configId:"model",fromObject:e=>{let n=ui(e.availableModels);return n.length>0?n:void 0},fromConfig:e=>{let n=ui(e.options);return n.length>0?n:void 0}})??[]}function Ml(t){return Za(t,{nestedKey:"modes",configId:"mode",fromObject:e=>{let n=bo(e.availableModes);return n.length>0?n:void 0},fromConfig:e=>{let n=bo(e.options);return n.length>0?n:void 0}})??[]}function _l(t){return Za(t,{nestedKey:"modes",configId:"mode",fromObject:e=>Mn(e.currentModeId)??Mn(e.currentMode)??Mn(e.modeId)??Mn(e.mode),fromConfig:e=>Mn(e.currentValue)})}function uk(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(!n||n.method!=="session/update")continue;let s=n.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function Lm(t){try{let e=await wr.readFile($.tuiHistoryFile(t),"utf8"),n=[];for(let s of e.split(`
242
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&n.push(r)}catch{}return n}catch{return[]}}async function Eo(t){try{let e=await wr.stat($.historyFile(t));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function gi(t,e){return t.interactive!==void 0?t.interactive:t.originatingClient?.name===hr?!1:e?!0:void 0}import{spawn as fk}from"child_process";import*as wi from"fs";import*as Rs from"fs/promises";import*as Nm from"path";var ed=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,n,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${n}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${n}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};je();var pk=1e3,mk=6e4,$l=3e3,yi=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,n,s,r={}){this.adapter=n,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??pk,this.restartCapMs=r.restartCapMs??mk;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,n){let s=this.entries.get(e);s&&(s.version=n)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Rs.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let n of this.entries.values()){n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},$l);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let n of this.entries.values()){try{n.logStream?.end()}catch{}n.child=void 0,n.logStream=void 0,n.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let n=this.entries.get(e);return n?this.infoFor(n):void 0}has(e){return this.entries.has(e)}async startByName(e){let n=this.entries.get(e);if(!n)throw Mo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(n.child)throw Mo(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0),n.manuallyStopped=!1,n.restartCount=0,n.breaker.reset(),n.failureReason=void 0,this.spawn(n,0),this.infoFor(n)}async stopByName(e){let n=this.entries.get(e);if(!n)throw Mo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;return s?(await this.terminate(n,s),this.infoFor(n)):this.infoFor(n)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw Mo(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let n=this.makeEntry(e);return this.entries.set(e.name,n),e.enabled&&this.spawn(n,0),this.infoFor(n)}async unregister(e){let n=this.entries.get(e);if(!n)throw Mo(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");n.manuallyStopped=!0,n.restartTimer&&(clearTimeout(n.restartTimer),n.restartTimer=void 0);let s=n.child;s&&await this.terminate(n,s);try{n.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,n){if(n.exitCode!==null||n.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{n.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},$l);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let n;return e.failureReason!==void 0?n="failed":e.child?n="running":e.restartTimer?n="restarting":e.config.enabled?n="stopped":n="disabled",{name:e.config.name,status:n,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new ed(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Rs.readdir(this.adapter.paths.dir())}catch(n){if(n.code==="ENOENT")return;throw n}for(let n of e){if(!n.endsWith(".pid"))continue;let s=Nm.join(this.adapter.paths.dir(),n),r;try{let i=await Rs.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Fl(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+$l;for(;Date.now()<i&&Fl(r);)await new Promise(o=>setTimeout(o,50));if(Fl(r))try{process.kill(r,"SIGKILL")}catch{}}await Rs.unlink(s).catch(()=>{})}}spawn(e,n){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=wi.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${n+1})
243
243
  `);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let c={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:a,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...l]=i;if(d===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
244
- `),o.end();return}let f=je(d),u=[...l,...r.args].map(je),p;try{p=JS(f,u,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){o.write(`[hydra-acp] failed to spawn ${r.name}: ${m.message}
245
- `),o.end(),this.scheduleRestart(e,n);return}if(p.stdout&&p.stdout.pipe(o,{end:!1}),p.stderr&&p.stderr.pipe(o,{end:!1}),typeof p.pid=="number")try{ai.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
244
+ `),o.end();return}let u=Je(d),f=[...l,...r.args].map(Je),p;try{p=fk(u,f,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){o.write(`[hydra-acp] failed to spawn ${r.name}: ${m.message}
245
+ `),o.end(),this.scheduleRestart(e,n);return}if(p.stdout&&p.stdout.pipe(o,{end:!1}),p.stderr&&p.stderr.pipe(o,{end:!1}),typeof p.pid=="number")try{wi.writeFileSync(this.adapter.paths.pidFile(r.name),`${p.pid}
246
246
  `,{encoding:"utf8",mode:384})}catch(m){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${m.message}
247
247
  `)}e.child=p,e.logStream=o,e.pid=typeof p.pid=="number"?p.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,p.on("error",m=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${m.message}
248
- `)}),p.on("exit",(m,h)=>{try{ai.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${h??"null"}
249
- `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof m=="number"?m:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let w=e.exitWaiters.splice(0);for(let v of w)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(m,r.name,this.adapter.kind);if(typeof b=="object"){e.failureReason=b.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${b.tripped}
250
- `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Il(t){try{return process.kill(t,0),!0}catch{return!1}}function So(t,e){return t.code=e,t}pe();var VS={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:_.extensionsDir,logFile:_.extensionLogFile,pidFile:_.extensionPidFile}},ja=class extends oi{constructor(e,n,s={}){super(e,VS,n,s)}};pe();var GS={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:_.transformersDir,logFile:_.transformerLogFile,pidFile:_.transformerPidFile}},qa=class extends oi{connected=new Map;constructor(e,n,s={}){super(e,GS,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var Wa=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};pe();qr();pe();import*as Io from"fs/promises";import*as za from"path";var ko=t=>{process.stderr.write(t+`
251
- `)};function xl(t){ko=t??(e=>process.stderr.write(e+`
252
- `))}async function xm(t,e){let n=Sn();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=za.join(_.agentsDir(),n),a;try{a=await Io.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;ko(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let f=i.get(d)??new Set,u=za.join(o,d),p;try{p=await Io.readdir(u,{withFileTypes:!0})}catch(m){ko(`hydra-acp: prune: failed to read ${u}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||f.has(h)||h.includes(".partial-"))continue;let w=za.join(u,h);try{await Io.rm(w,{recursive:!0,force:!0}),ko(`hydra-acp: pruned stale ${d} ${h} (${w})`)}catch(b){ko(`hydra-acp: prune: failed to remove ${w}: ${b.message}`)}}}}function Cm(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let f of l.agents)await Lc(f)==="yes"&&a.push(f.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:f}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${f}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Cl(t){let e=t.maxDeletions??200,n=(p,m)=>{t.logger&&t.logger[p](`session-gc: ${m}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p)&&(d+=1)}catch(m){l+=1,n("warn",`delete ${p} failed: ${m.message}`)}let f=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${QS(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let u={considered:o.length,deleted:d,failed:l,deferred:f};return c!==void 0&&(u.oldestLastUsedMs=c),u}function Am(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Cl({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function QS(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}Nt();xo();pe();Qs();import*as Em from"path";import{createHash as ZS,randomBytes as ek,timingSafeEqual as tk}from"crypto";var Pm="hydra_session_",nk=3600*24*30,Rm=12,sk=32,rk=50;function ik(){return Em.join(_.home(),"session-tokens.json")}function Tm(t){return ZS("sha256").update(t).digest("hex")}function Mm(t){return ek(t).toString("hex")}function ok(){return Mm(Rm).slice(0,Rm*2)}function ak(){return`${Pm}${Mm(sk)}`}var Ja=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=ik(),s=await zt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(dk));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=ak(),s=Tm(n),r=ok(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:nk,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Pm))return;let n=Tm(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!tk(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},rk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Ft(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function dk(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}qn();var _m="Bearer ",Ka=class{constructor(e){this.token=e}token;async validate(e){return ck(e,this.token)?"service":void 0}},Ya=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Va=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function $m(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(_m)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(_m.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Om(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Ga=class{tokens=new Map;mint(e,n){let s=Dr();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function ck(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var Qa=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};pe();Ne();Tl();or();ed();import*as _l from"fs";import*as Ro from"os";import*as Zm from"path";import*as $l from"readline";ys();xn();function td(t){let e=Bk(t),n=Nk(e),s=[];Dk(s,t),Hk(s,e,n);let r=s.join(`
248
+ `)}),p.on("exit",(m,h)=>{try{wi.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${h??"null"}
249
+ `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof m=="number"?m:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let y=e.exitWaiters.splice(0);for(let v of y)v();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let b=e.breaker.recordExit(m,r.name,this.adapter.kind);if(typeof b=="object"){e.failureReason=b.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${b.tripped}
250
+ `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,n+1)})}scheduleRestart(e,n){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(n,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,n)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Fl(t){try{return process.kill(t,0),!0}catch{return!1}}function Mo(t,e){return t.code=e,t}he();var hk={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:$.extensionsDir,logFile:$.extensionLogFile,pidFile:$.extensionPidFile}},td=class extends yi{constructor(e,n,s={}){super(e,hk,n,s)}};he();var gk={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:$.transformersDir,logFile:$.transformerLogFile,pidFile:$.transformerPidFile}},nd=class extends yi{connected=new Map;constructor(e,n,s={}){super(e,gk,n,s)}registerConnection(e,n,s){this.connected.set(e,{name:e,connection:n,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let n=[];for(let s of e){let r=this.connected.get(s);r&&n.push(r)}return n}};var sd=class{entries=new Map;changeHandlers=[];register(e,n,s){this.entries.set(e,{connection:n,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[n,s]of this.entries)for(let r of s.commands)e.push({name:n,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};he();ei();he();import*as $o from"fs/promises";import*as rd from"path";var _o=t=>{process.stderr.write(t+`
251
+ `)};function Ol(t){_o=t??(e=>process.stderr.write(e+`
252
+ `))}async function Dm(t,e){let n=An();if(!n)return;let s=await t.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let i=e.activeAgentVersions(),o=rd.join($.agentsDir(),n),a;try{a=await $o.readdir(o,{withFileTypes:!0})}catch(c){let d=c;if(d.code==="ENOENT")return;_o(`hydra-acp: prune: failed to read ${o}: ${d.message}`);return}for(let c of a){if(!c.isDirectory())continue;let d=c.name,l=r.get(d);if(l===void 0)continue;let u=i.get(d)??new Set,f=rd.join(o,d),p;try{p=await $o.readdir(f,{withFileTypes:!0})}catch(m){_o(`hydra-acp: prune: failed to read ${f}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let h=m.name;if(h===l||u.has(h)||h.includes(".partial-"))continue;let y=rd.join(f,h);try{await $o.rm(y,{recursive:!0,force:!0}),_o(`hydra-acp: pruned stale ${d} ${h} (${y})`)}catch(b){_o(`hydra-acp: prune: failed to remove ${y}: ${b.message}`)}}}}function Hm(t){let e,n=!1,s=0,r=(a,c)=>{t.logger&&t.logger[a](`agent-sync: ${c}`)},i=async()=>{let a=[];try{let l=await t.registry.load();for(let u of l.agents)await Kc(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),t.intervalMs}if(a.length===0)return t.intervalMs;let c=s%a.length;s=(s+1)%a.length;let d=a[c];try{let{synced:l,skipped:u}=await t.manager.syncFromAgent(d);r("info",`${d}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${d}: ${l.message}`)}return Math.max(1,Math.floor(t.intervalMs/a.length))},o=a=>{n||(e=setTimeout(()=>{i().then(c=>{o(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),o(t.intervalMs)})},a),e.unref())};return o(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}async function Ll(t){let e=t.maxDeletions??200,n=(p,m)=>{t.logger&&t.logger[p](`session-gc: ${m}`)},s=Date.now(),r=t.maxAgeMs>0?s-t.maxAgeMs:Number.POSITIVE_INFINITY,i=await t.manager.list({includeNonInteractive:!0}).catch(p=>(n("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((t.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let h=Date.parse(p.updatedAt);Number.isFinite(h)&&(t.maxAgeMs>0&&h>r||o.push({sessionId:p.sessionId,lastUsedMs:h}))}if(o.length===0)return t.verbose&&n("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=o.slice(0,e),c=a[0]?.lastUsedMs,d=0,l=0;for(let{sessionId:p}of a)try{await t.manager.deleteRecord(p,"expired")&&(d+=1)}catch(m){l+=1,n("warn",`delete ${p} failed: ${m.message}`)}let u=o.length-a.length;if(t.verbose||d>0||l>0){let p=(t.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";n("info",`swept ${d} ${p} session(s) older than ${yk(t.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:d,failed:l,deferred:u};return c!==void 0&&(f.oldestLastUsedMs=c),f}function Um(t){let e,n=!1,s=!1,r=i=>{n||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Ll({manager:t.manager,maxAgeMs:t.maxAgeMs,selection:"unpromoted",...t.maxDeletionsPerSweep!==void 0?{maxDeletions:t.maxDeletionsPerSweep}:{},...t.logger?{logger:t.logger}:{}})}finally{s=!1}}})().catch(a=>{t.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(t.intervalMs)})},i),e.unref())};return r(t.intervalMs),()=>{n=!0,e&&(clearTimeout(e),e=void 0)}}function yk(t){if(t<=0)return"any age";let e=t/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let n=t/(3600*1e3);return`${n.toFixed(n>=10?0:1)}h`}Wt();Fo();he();ar();import*as Wm from"path";import{createHash as bk,randomBytes as vk,timingSafeEqual as Sk}from"crypto";var zm="hydra_session_",kk=3600*24*30,jm=12,Ik=32,xk=50;function Ck(){return Wm.join($.home(),"session-tokens.json")}function qm(t){return bk("sha256").update(t).digest("hex")}function Jm(t){return vk(t).toString("hex")}function Ak(){return Jm(jm).slice(0,jm*2)}function Rk(){return`${zm}${Jm(Ik)}`}var id=class t{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,n){this.filePath=n;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],n=Ck(),s=await Xt(n);s&&Array.isArray(s.records)&&(e=s.records.filter(Tk));let r=new t(e,n);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let n=Rk(),s=qm(n),r=Ak(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:kk,a=new Date(i.getTime()+o*1e3),c={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:n,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(zm))return;let n=qm(e),s=this.records.get(n);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(n,"hex");if(r.length!==i.length||!Sk(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(n),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[n,s]of this.records)if(s.id===e)return this.records.delete(n),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:n,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,n)=>n.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let n=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),n+=1);return n>0&&this.scheduleWrite(),n}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},xk))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Ut(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 Tk(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}Gn();var Km="Bearer ",od=class{constructor(e){this.token=e}token;async validate(e){return Ek(e,this.token)?"service":void 0}},ad=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},dd=class{constructor(e){this.validators=e}validators;async validate(e){for(let n of this.validators){let s=await n.validate(e);if(s!==void 0)return s}}};function Vm(t){return async function(n,s){let r=n.headers.authorization;if(!r||!r.startsWith(Km)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Km.length).trim(),o=await t.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}n.authIdentity=o}}function Ym(t){let e=t.headers["sec-websocket-protocol"],n=Array.isArray(e)?e.join(","):e;if(n)for(let s of n.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var cd=class{tokens=new Map;mint(e,n){let s=Qr();return this.tokens.set(s,{name:e,kind:n}),s}revoke(e){for(let[n,s]of this.tokens)s.name===e&&this.tokens.delete(n)}resolve(e){return this.tokens.get(e)}async validate(e){let n=this.tokens.get(e);if(n)return`${n.kind}:${n.name}`}};function Ek(t,e){if(t.length!==e.length)return!1;let n=0;for(let s=0;s<t.length;s+=1)n|=t.charCodeAt(s)^e.charCodeAt(s);return n===0}var ld=class{entries=new Map;maxFails;windowMs;constructor(e=10,n=900*1e3){this.maxFails=e,this.windowMs=n}isBlocked(e){let n=this.entries.get(e);return n?Date.now()-n.windowStart>this.windowMs?(this.entries.delete(e),!1):n.fails>=this.maxFails:!1}recordFailure(e){let n=Date.now(),s=this.entries.get(e);if(!s||n-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:n});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[n,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(n)}};he();je();Dl();yr();pd();import*as ql from"fs";import*as Bo from"os";import*as mh from"path";import*as Wl from"readline";Es();En();function md(t){let e=sI(t),n=rI(e),s=[];iI(s,t),oI(s,e,n);let r=s.join(`
253
253
  `);return r.endsWith(`
254
254
  `)||(r+=`
255
- `),r}function Bk(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=Rn(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function Nk(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function Dk(t,e){let n=e.session,s=Ve(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${dr(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${Pl(a.size)}`:void 0;c.push(d?`${Pl(a.used)} / ${d} tokens`:`${Pl(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
256
- `)),t.push("")}function Hk(t,e,n){if(!e.some(d=>Uk(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
257
- `))t.push(`> ${dr(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":c(),i+=d.text;break;case"agent-thought":{c(),a();let l=d.text.split(`
258
- `);for(let f of l)t.push(`> _${dr(f)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${qk(l.status)} ${jk(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let f=l.status==="completed"?"[x]":"[ ]";t.push(`- ${f} ${dr(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${dr(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${dr(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Uk(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function jk(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${dr(t.title)}${n}`}function qk(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function dr(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Pl(t){return t.toLocaleString("en-US")}It();Nt();eo();ys();function Wk(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let f=l.toUpperCase();f==="AND"?o=!0:f==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>zk(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function zk(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:zm(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:zm(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function zm(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Jk(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Kk=5,Yk=200,Jm=30;async function Vm(t,e,n={}){let s=Wk(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??Kk,i=n.maxSessions??Yk,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(f=>o.has(f.sessionId)):a,d=[],l=!1;for(let f of c){if(d.length>=i){l=!0;break}let u=await t.loadHistory(f.sessionId).catch(()=>[]),p=Vk(u,s,r);if(p.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};f.title!==void 0&&(m.title=f.title),d.push(m)}return{query:e,truncated:l,results:d}}function Vk(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Gk(t,o,i,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Gk(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=Qk(a).filter(d=>Jk(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),f=l.indexOf(r);if(f===-1)continue;let u=0;for(;f!==-1;)u++,f=l.indexOf(r,f+r.length);if(i+=u,o.length<s){let p=l.indexOf(r),m={kind:d.kind,text:nI(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(m.toolName=d.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Qk(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=nd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?tt(s.text):nd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(eI(s))return[];let i=nd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=tI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Xk(s);default:return[]}}function Xk(t){let e=Km(t,"name"),n=Km(t,"title"),s=[];if(n!==void 0){let a=Ie(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=Ie(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=Ym(r);if(a.length>0){let c={kind:"tool-input",text:Ie(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=Ym(i);if(a.length>0){let c={kind:"tool-input",text:Ie(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=Zk(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Zk(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=Ie(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=Ie(s);if(r.length>0)return r}}return null}function eI(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function nd(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?tt(e.text):""}function tI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=nd(n);s.length>0&&e.push(s)}return e.join("")}function Km(t,e){let n=t[e];return typeof n=="string"?n:void 0}function Ym(t){try{return JSON.stringify(t)}catch{return""}}function nI(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Jm),c=Math.min(s.length,o+i.length+Jm),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as Qm}from"crypto";function Gm(t){let e=Qm(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Ml(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push(Gm({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(Gm({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=li(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function li(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=Qm(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var sd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Xm(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!Xs(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function eh(t,e,n,s={}){t.get("/v1/sessions",async c=>{let d=c.query,l=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:l})}}),t.get("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.getOne(f);return u||(d.code(404).send({error:"session not found"}),d)}),t.post("/v1/sessions/search",async(c,d)=>{let l=c.body??{},f=typeof l.q=="string"?l.q:"";if(f.trim().length===0)return d.code(400).send({error:"q is required"}),d;let u=Array.isArray(l.sessionIds)?l.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Vm(e,f,{sessionIds:u})}),t.post("/v1/sessions",async(c,d)=>{let l=c.body??{},f=je(l.cwd??n.cwd),u=l.agentId??n.agentId,p=li(s),m=p!==void 0?[...l.mcpServers??[],...p.descriptors]:l.mcpServers;try{let h=await e.create({cwd:f,agentId:u,mcpServers:m});p!==void 0&&p.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){p!==void 0&&p.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),t.post("/v1/sessions/collect",async(c,d)=>{let l=c.body??{},f=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,u=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,p=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let m=await Cl({manager:e,maxAgeMs:f,maxDeletions:u,selection:p,verbose:!1});d.code(200).send(m)}catch(m){d.code(500).send({error:m.message})}}),t.post("/v1/sessions/:id/kill",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){u.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m={};(p.mode==="memory"||p.mode==="file")&&(m.mode=p.mode),typeof p.capacityBytes=="number"&&(m.capacityBytes=p.capacityBytes),typeof p.fileCapBytes=="number"&&(m.fileCapBytes=p.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=h=>Zm.join(Ro.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return u.openStream(m)}catch(h){return d.code(409).send({error:h.message}),d}}),t.post("/v1/sessions/:id/stdin",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(!u)return d.code(404).send({error:"session not found"}),d;let p=c.body??{},m=typeof p.chunk=="string"?p.chunk:"",h=p.eof===!0;try{return u.streamWrite(m,h)}catch(w){return d.code(409).send({error:w.message}),d}}),t.patch("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{};if(u.priority!==void 0){let m=u.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(u.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),d.code(202).send();return}if(typeof u.title!="string"||u.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,u.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.delete("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f);if(u){await u.close({deleteRecord:!0}),d.code(204).send();return}if(!await e.deleteRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),t.get("/v1/sessions/:id/export",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.query?.tools,p=u==="references"?"references":cm(u),m=await e.exportBundle(f,p==="references"?{tools:"references"}:{});if(!m){d.code(404).send({error:"session not found"});return}let h=yo({record:m.record,history:p==="summary"?lm(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:fe,machine:Ro.hostname(),hydraHost:Xm(n)}),w=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${f}-${w}.hydra"`),d.code(200).send(h)}),t.get("/v1/sessions/:id/diff",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=c.query??{},m=p.fold==="true"||p.fold==="1",h=typeof p.paths=="string"&&p.paths.length>0?new Set(p.paths.split(",").map(b=>b.trim()).filter(b=>b.length>0)):void 0,w=di(u.history);h&&(w=w.filter(b=>h.has(b.path))),m&&(w=w.map(b=>({...b,hunks:ci(b.hunks)}))),d.code(200).send(w)}),t.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let l=c.params,f=await e.resolveCanonicalId(l.id)??l.id,u=await e.loadToolBlob(f,l.hash);if(u===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(u)}),t.get("/v1/sessions/:id/transcript",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=await e.exportBundle(f);if(!u){d.code(404).send({error:"session not found"});return}let p=yo({record:u.record,history:u.history,promptHistory:u.promptHistory.length>0?u.promptHistory:void 0,hydraVersion:fe,machine:Ro.hostname(),hydraHost:Xm(n)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(td(p))}),t.post("/v1/sessions/:id/fork",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=c.body??{},p={};if(u.forkAt!==void 0){if(typeof u.forkAt!="string"||u.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}p.forkAt=u.forkAt}if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}p.cwd=je(u.cwd)}if(u.agentId!==void 0){if(typeof u.agentId!="string"||u.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}p.agentId=u.agentId}if(u.title!==void 0){if(typeof u.title!="string"){d.code(400).send({error:"title must be a string"});return}p.title=u.title}try{let m=await e.forkSession(f,p);d.code(201).send(m)}catch(m){let h=m;if(h.code===z.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===z.InvalidParams||h.code===z.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),t.post("/v1/sessions/import",async(c,d)=>{let l=c.body??{};if(l.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let f;if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}f=l.cwd}let u;try{u=ln(l.bundle)}catch(p){d.code(400).send({error:"invalid bundle",details:p.message});return}try{let p=await e.importBundle(u,{replace:l.replace===!0,...f!==void 0?{cwd:f}:{}});d.code(201).send(p)}catch(p){let m=p;if(m.code===z.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}d.code(500).send({error:m.message})}}),t.get("/v1/sessions/:id/compact/status",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,u=e.get(f),p;if(u?p=u.summarizedThroughEntry:p=await e.getSummarizedThroughEntry(f),p===void 0&&!await e.hasRecord(f))return d.code(404).send({error:"session not found"}),d;let m=await e.getCompactionState(f),h=await e.getRollbackBreadcrumb(f),w=!1,b,S=await e.getHistory(f).catch(()=>[])??[];if(S.length>0&&n.compaction){let x=p??0,T=S.length,$=S.slice(x).reduce((N,j)=>N+JSON.stringify(j.params).length,0);b=Rl($);let H=u?.currentModel,J=S.at(-1).recordedAt,B=u?.currentUsage;w=Fm({summarizedThroughEntry:x,totalEntries:T,unsummarizedChars:$,compactionInFlight:e.getCompactionInFlight(),currentModel:H,lastActivityMs:J,nowMs:Date.now(),config:n.compaction,...typeof B?.used=="number"?{agentReportedUsed:B.used}:{},...typeof B?.size=="number"?{agentReportedSize:B.size}:{}})}return{summarizedThroughEntry:p??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:w,...b!=null?{approxTokens:b}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),t.post("/v1/sessions/:id/compact",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(e.get(f)){e.scheduleCompaction(f),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),d.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l;if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),d.code(202).send({rolledBack:!0})}catch(u){let p=u instanceof Error?u.message:String(u);d.code(409).send({error:p})}}),t.get("/v1/sessions/:id/history",async(c,d)=>{let l=c.params.id,f=c.query,u=f?.follow==="1"||f?.follow==="true",p=await e.resolveCanonicalId(l)??l,m=e.get(p),h,w,b=!1,v=1e4,S=[];if(m){u&&(w=m.onBroadcast(T=>{d.raw.writableEnded||(b?d.raw.write(JSON.stringify(T)+`
259
- `):(S.push(T),S.length>v&&S.shift()))})),c.raw.on("close",()=>{w?.(),d.raw.writableEnded||d.raw.end()});try{h=await m.getHistorySnapshot()}catch(T){throw w?.(),T}}else{let T=await e.getHistory(p);if(T===void 0)return d.code(404).send({error:"session not found"}),d;h=T}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let x=new Set;for(let T of h??[]){d.raw.write(JSON.stringify(T)+`
260
- `);let F=T;typeof F.recordedAt=="number"&&x.add(String(F.recordedAt))}for(;S.length>0;){let T=S.splice(0,S.length);for(let F of T){let $=F,H=typeof $.recordedAt=="number"?String($.recordedAt):"";H&&x.has(H)||d.raw.write(JSON.stringify(F)+`
261
- `)}}return b=!0,w||d.raw.end(),d});function r(c,d,l){let f=typeof c=="string"?c.trim():"";if(f.length===0)return null;let u;try{u=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!u||typeof u!="object"||Array.isArray(u))return console.debug("events endpoint: skipping non-object JSONL line"),null;let p=u;if(typeof p.recordedAt!="number"||l!==void 0&&p.recordedAt<l||typeof p.params!="object"||p.params===null||Array.isArray(p.params))return null;let m=p.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let w=m.update.sessionUpdate;return typeof w!="string"||!d.has(w)?null:{recordedAt:p.recordedAt,entry:u}}function i(c,d,l){let u=d.params.update,p={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:l,update:u};return u.messageId!==void 0&&u.messageId!==null&&(p.messageId=u.messageId),p}async function o(c,d,l,f){let u=$l.createInterface({input:_l.createReadStream(d),crlfDelay:1/0}),p=null;for await(let m of u){let h=r(m,l,f);if(h){let w=h.entry.params.update.sessionUpdate;p={ts:h.recordedAt,row:i(c,h.entry,w)};break}}return{sessionId:c,rl:u,current:p,exhausted:p===null}}async function a(c,d,l){for await(let f of c.rl){let u=r(f,d,l);if(u){let p=u.entry.params.update.sessionUpdate;c.current={ts:u.recordedAt,row:i(c.sessionId,u.entry,p)};return}}c.exhausted=!0}t.get("/v1/sessions/events",async(c,d)=>{let l=c.query,f=l.kinds;if(!f||f.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let u=f.split(",").map(v=>v.trim());if(u.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let v of u)if(!sd.has(v))return d.code(400).send({error:`kind "${v}" is not queryable; allowed kinds: ${[...sd].join(", ")}`}),d;let p=new Set(u),m;if(l.since!==void 0&&l.since.trim().length>0){let v=new Date(l.since);if(isNaN(v.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;m=v.getTime()}let h=await e.list({includeNonInteractive:!0}),w=m!==void 0?h.filter(v=>new Date(v.updatedAt).getTime()>=m):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let b=[];for(let v of w)try{let S=_.historyFile(v.sessionId),x=await o(v.sessionId,S,p,m);x.exhausted||b.push(x)}catch(S){if(S.code==="ENOENT")continue;throw S}c.raw.on("close",()=>{for(let v of b)try{v.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;b.length>0;){let v=-1,S=1/0;for(let T=0;T<b.length;T++){let F=b[T];F.current!==null&&F.current.ts<S&&(S=F.current.ts,v=T)}if(v===-1)break;let x=b[v];if(d.raw.write(JSON.stringify(x.current.row)+`
262
- `),await a(x,p,m),x.exhausted){try{x.rl.close()}catch{}b.splice(v,1)}}}catch(v){for(let S of b)try{S.rl.close()}catch{}throw v}return d.raw.end(),d}),t.get("/v1/sessions/:id/events",async(c,d)=>{let l=c.params.id,f=c.query,u=await e.resolveCanonicalId(l)??l;if(!e.get(u)&&!await e.hasRecord(u))return d.code(404).send({error:"session not found"}),d;let m=f.kinds;if(!m||m.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=m.split(",").map(T=>T.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let T of h)if(!sd.has(T))return d.code(400).send({error:`kind "${T}" is not queryable; allowed kinds: ${[...sd].join(", ")}`}),d;let w=new Set(h),b;if(f.since!==void 0&&f.since.trim().length>0){let T=new Date(f.since);if(isNaN(T.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;b=T.getTime()}let v=_.historyFile(u),S=_l.createReadStream(v),x=$l.createInterface({input:S,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let T of x){let F=typeof T=="string"?T.trim():"";if(F.length===0)continue;let $;try{$=JSON.parse(F)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",v);continue}if(!$||typeof $!="object"||Array.isArray($)){console.debug("events endpoint: skipping non-object JSONL line in %s",v);continue}let H=$;if(typeof H.recordedAt!="number"||typeof H.params!="object"||H.params===null||Array.isArray(H.params))continue;let J=H.params;if(typeof J.update!="object"||J.update===null||Array.isArray(J.update))continue;let B=J.update,N=B.sessionUpdate;if(typeof N!="string"||!w.has(N)||b!==void 0&&H.recordedAt<b)continue;let j={ts:new Date(H.recordedAt).toISOString(),kind:N,update:B};B.messageId!==void 0&&B.messageId!==null&&(j.messageId=B.messageId),d.raw.write(JSON.stringify(j)+`
263
- `)}}catch(T){if(T.code==="ENOENT")return d.raw.end(),d;throw T}return d.raw.end(),d})}It();function th(t,e,n,s={}){t.get("/v1/agents",async()=>Kr(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await cn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===z.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function nh(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var sI=/^[A-Za-z0-9._-]+$/;function rd(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=rI(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){To(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){To(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){To(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){To(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){To(o,c)}})}function To(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function rI(t){let e=t.name;if(typeof e!="string"||!sI.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function sh(t,e){rd(t,"extension",e)}function rh(t,e){rd(t,"transformer",e)}function ih(t,e){t.get("/v1/config",async()=>e)}import{z as ui}from"zod";pe();import*as ws from"fs/promises";import*as ch from"path";import{randomBytes as iI,scrypt as oI,timingSafeEqual as aI}from"crypto";import{promisify as dI}from"util";var lh=dI(oI);function Ol(){return ch.join(_.home(),"password-hash")}var oh=32768,ah=8,dh=1,cI=64,lI=16,uh=128*1024*1024;async function fh(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=iI(lI),n=await lh(t,e,cI,{N:oh,r:ah,p:dh,maxmem:uh}),s=`scrypt$${oh}$${ah}$${dh}$${e.toString("hex")}$${n.toString("hex")}
264
- `;await ws.mkdir(_.home(),{recursive:!0}),await ws.writeFile(Ol(),s,{encoding:"utf8",mode:384})}async function id(){try{return(await ws.readFile(Ol(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function od(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await ws.readFile(Ol(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let c=await lh(t,o,a.length,{N:s,r,p:i,maxmem:uh});return c.length!==a.length?!1:aI(c,a)}var uI=ui.object({password:ui.string().min(1),label:ui.string().min(1).max(256).optional(),ttlSec:ui.number().int().positive().optional()}),fI=ui.object({id:ui.string().optional()}).optional();function ph(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=pI(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=uI.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await id())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await od(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=fI.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function pI(t){return t.ip||"unknown"}sr();fi();import{nanoid as Dl}from"nanoid";Ra();It();Nt();import{randomBytes as hh}from"crypto";import*as gh from"os";function we(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function wI(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function un(t,e,n){let s=t.get(e);if(!s)throw we(z.SessionNotFound,n??`session ${e} not found`);return s}async function Fl(t,e){let n=li(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=hh(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=Ml({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,f=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{f.unbind(l)})}return xI(d,t),d}function yh(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Om({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Tn(n),a=new Pt(o),c={clientId:`hydra_client_${Dl(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let d=(f,u)=>{if(c.attached.get(f)?.readonly)throw we(z.PermissionDenied,`${u} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let u=ap.parse(f??{});u.clientInfo?.name&&(c.clientInfo={name:u.clientInfo.name,...u.clientInfo.version!==void 0?{version:u.clientInfo.version}:{}});let p=u.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),II()}),i&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async u=>{let p=u??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let w=h;if(typeof w.verb!="string")return;let b={verb:w.verb};return typeof w.argsHint=="string"&&(b.argsHint=w.argsHint),typeof w.description=="string"&&(b.description=w.description),b}).filter(h=>h!==void 0):[];return f.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(i.name)})}if(i&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async u=>{let p=u??{},m=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(w=>{if(!w||typeof w!="object")return;let b=w;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(w=>w!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(i.name,a,m,h),{ok:!0,registered:h.length}}),a.onClose(()=>{f.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async f=>{let u=f??{},p=Array.isArray(u.intercepts)?u.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0,m=typeof u.method=="string"?u.method:void 0,h=u.envelope,w=u.route;if(!p||!m)throw we(-32602,"emit_message requires sessionId and method");let b=un(e.manager,p),v=typeof u.respondsTo=="string"?u.respondsTo:void 0;if(v)return b.dischargeClaim(v,h),{ok:!0};if(w==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,h)};if(w==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,h)};throw we(-32602,`unsupported route: ${JSON.stringify(w)}`)}),a.onRequest("hydra-acp/session/request_permission",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(-32602,"hydra-acp/session/request_permission requires sessionId");return un(e.manager,p).requestPermissionFromClients(u)}),a.onRequest("hydra-acp/transformer/attach",async f=>SI(f,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async f=>{let u=f??{},p=typeof u.agentId=="string"?u.agentId:e.defaultAgent,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.parentSessionId=="string"?u.parentSessionId:void 0,w=u._meta&&typeof u._meta=="object"?u._meta:void 0,b=w&&w["hydra-acp"]&&typeof w["hydra-acp"]=="object"?w["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!m&&h){let F=e.manager.get(h);F&&(m=F.cwd)}if(!m)throw we(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof u.interactive=="boolean"?u.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:h,interactive:x,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(z.InvalidParams,"fork_session requires sessionId");let p=typeof u.forkAt=="string"?u.forkAt:void 0,m=typeof u.cwd=="string"?u.cwd:void 0,h=typeof u.agentId=="string"?u.agentId:void 0;return await e.manager.forkSession(u.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async f=>{let u=f??{};if(typeof u.sessionId!="string")throw we(z.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw we(z.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0,m=u.until==="idle"?"idle":"turn_complete",h=typeof u.timeoutMs=="number"?Math.min(u.timeoutMs,18e5):3e5;if(!p)throw we(-32602,"await_child requires childSessionId");let w=un(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],F=0,$=!1,H,J,B=!1,N=()=>{B||(B=!0,clearTimeout(j),H?.(),J?.(),b($?{entries:x,truncated:!0}:{entries:x}))};H=w.onBroadcast(X=>{let Y=wI(X);for(x.push(X),T.push(Y),F+=Y;x.length>0&&(x.length>1e3||F>1048576);)x.shift(),F-=T.shift()??0,$=!0;m==="turn_complete"&&X.params?.update?.sessionUpdate==="turn_complete"&&N()});let j=setTimeout(N,h);typeof j.unref=="function"&&j.unref(),J=w.onClose(()=>N())})}),a.onRequest("hydra-acp/child_session/close",async f=>{let u=f??{},p=typeof u.childSessionId=="string"?u.childSessionId:void 0;if(!p)throw we(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async f=>{let u=f??{},p=typeof u.token=="string"?u.token:void 0,m=typeof u.sessionId=="string"?u.sessionId:void 0,h=typeof u.estimatedRemainingMs=="number"?u.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async f=>{let u=f??{};if(typeof u.sessionId!="string"||typeof u.hash!="string")throw we(z.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,m=await e.manager.loadToolBlob(p,u.hash);if(m===null)throw we(z.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>bI(f,e)),a.onRequest("session/new",async f=>{let u=dp.parse(f),p=Bt(f?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(j=>typeof j=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],w,b,v=u.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){w=hh(32).toString("hex"),b=e.mcpTokenRegistry.reserve(w);let X={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${w}`}]};v=[...u.mcpServers??[],X]}let S,x,T=li(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let F=Ml({baselineMcpServers:u.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),$;try{$=await e.manager.create({cwd:u.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:mh(a),transformChain:h,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...F?{mintMcpServersForSwap:F}:{}})}catch(j){throw b!==void 0&&b.abandon(j instanceof Error?j:void 0),x!==void 0&&x.abandon(j instanceof Error?j:void 0),T!==void 0&&T.abandon(j instanceof Error?j:void 0),j}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let j=w,X=e.mcpTokenRegistry;b.complete($),$.onClose(()=>{X.unbind(j)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let j=S,X=e.mcpTokenRegistry;x.complete($),$.onClose(()=>{X.unbind(j)})}T!==void 0&&T.bindToSession($);let H,J;try{H=ad(a,$,c),{entries:J}=await $.attach(H,"full")}catch(j){throw await $.close({deleteRecord:!1}).catch(()=>{}),j}c.attached.set($.sessionId,{sessionId:$.sessionId,clientId:H.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let j of J){if(a.isClosed())break;await a.notify(j.method,j.params).catch(()=>{})}})()});let B=Ll($),N=Bl($);return{sessionId:$.sessionId,...B?{modes:B}:{},...N?{models:N}:{},configOptions:$.buildConfigOptions(),_meta:Nl(e.manager,$,{clientId:H.clientId})}}),a.onRequest("session/attach",async f=>{let u=lp.parse(f),p=u.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Bt(u._meta),h=m.resume,w=m.readonly===!0,b=m.env;t.log.info(`session/attach sessionId=${u.sessionId} hasResumeHints=${!!h} readonly=${w}`);let v=h?u.sessionId:await e.manager.resolveCanonicalId(u.sessionId)??u.sessionId,S=e.manager.get(v);if(!S&&w){let N=await e.manager.loadFromDisk(v);if(!N)throw we(z.SessionNotFound,`session ${u.sessionId} not found`);let j=await e.manager.loadHistory(v),X=u.clientId??`cli_${Dl(8)}`;c.attached.set(N.hydraSessionId,{sessionId:N.hydraSessionId,clientId:X,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${N.hydraSessionId} clientId=${X} attachedCount=${c.attached.size} replayed=${j.length}`);for(let Y of j)await a.notify(Y.method,Y.params).catch(()=>{});return{sessionId:N.hydraSessionId,clientId:X,connectedClients:[X],historyPolicy:"full",replayed:j.length,_meta:kI(N)}}let x=!S;if(!S){let N=await e.manager.loadFromDisk(v),j=N;if(h&&(j={...N,hydraSessionId:u.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!j)throw we(z.SessionNotFound,`session ${u.sessionId} not found and no resume hints provided`);let X=j.originatingClient?j:{...j,originatingClient:c.clientInfo},Y=b!==void 0?{...X,forwardedEnv:b}:X;S=await Fl(e,{...Y,onInstallProgress:mh(a)})}let T=ad(a,S,c,u.clientInfo,u.clientId),F=m.replayMode==="drip",{entries:$,appliedPolicy:H}=await S.attach(T,u.historyPolicy,{afterMessageId:u.afterMessageId,raw:F,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:w}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${u.historyPolicy} appliedPolicy=${H} replayed=${$.length} readonly=${w}${F?" replayMode=drip":""}`),F){let N=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,j=750;(async()=>{let X=null;for(let Y of $){let be=typeof Y.recordedAt=="number"?Y.recordedAt:null;if(X!==null&&be!==null){let V=Math.min(j,Math.max(0,(be-X)/N));V>0&&await new Promise(ge=>setTimeout(ge,V))}be!==null&&(X=be);try{await a.notify(Y.method,Y.params)}catch{return}}})()}else for(let N=0;N<$.length&&!a.isClosed();N++){let j=$[N],X=a.notify(j.method,j.params).catch(()=>{});(N+1)%200===0&&await X}S.replayPendingPermissions(T);let J=Ll(S),B=Bl(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:H,replayed:$.length,...J?{modes:J}:{},...B?{models:B}:{},configOptions:S.buildConfigOptions(),_meta:Nl(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async f=>{let u=up.parse(f),p=c.attached.get(u.sessionId);if(!p)throw we(z.SessionNotFound,"client not attached to that session");let m=e.manager.get(u.sessionId);return m?.detach(p.clientId),c.attached.delete(u.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(u.sessionId),{sessionId:u.sessionId,_meta:{[mt]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let u=fp.parse(f??{});return{sessions:(await e.manager.list({cwd:u.cwd})).filter(w=>w.originatingClient?.name!==rr).map(pp)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw we(z.InternalError,"agent registry unavailable");return Kr(e.registry)}),a.onRequest("session/prompt",async f=>{let u=mp.parse(f);d(u.sessionId,"session/prompt");let p=c.attached.get(u.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${u.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),we(z.SessionNotFound,"not attached to session");let m=e.manager.get(u.sessionId);if(!m){let h=await e.manager.loadFromDisk(u.sessionId);if(!h)throw we(z.SessionNotFound,`session ${u.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${u.sessionId}`),m=await Fl(e,h);let w=ad(a,m,c,void 0,p.clientId);await m.attach(w,"none")}return m.prompt(p.clientId,u)});let l=f=>{let u;try{u=Sa.parse(f)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=c.attached.get(u.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${u.sessionId}`);return}let m=e.manager.get(u.sessionId);m&&m.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${u.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async f=>{let u=Sa.parse(f);return d(u.sessionId,"session/cancel"),l(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let u=gp.parse(f);return d(u.sessionId,"hydra-acp/prompt/cancel"),un(e.manager,u.sessionId).cancelQueuedPrompt(u.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let u=Sa.parse(f);return d(u.sessionId,"hydra-acp/session/force_cancel"),un(e.manager,u.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let u=yp.parse(f);return d(u.sessionId,"hydra-acp/prompt/update"),un(e.manager,u.sessionId).updateQueuedPrompt(u.messageId,u.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let u=wp.parse(f);d(u.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(u.sessionId);if(!p)throw we(z.SessionNotFound,"not attached to session");return un(e.manager,u.sessionId).amendPrompt(p.clientId,u)}),a.onRequest("session/load",async f=>{let u=f??{},p=typeof u.sessionId=="string"?u.sessionId:void 0;if(!p)throw we(z.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let x=await e.manager.loadFromDisk(m);if(!x)throw we(z.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Fl(e,x)}let w=ad(a,h,c),{entries:b}=await h.attach(w,"pending_only");c.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:w.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}h.replayPendingPermissions(w);let v=Ll(h),S=Bl(h);return{sessionId:h.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:h.buildConfigOptions(),_meta:Nl(e.manager,h,{clientId:w.clientId})}}),a.onRequest("session/set_model",async f=>{let u=f?.sessionId;typeof u=="string"&&d(u,"session/set_model");let p=vI(f,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),we(p.code,p.message);if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:m}=p,h=await p.session.forwardRequest("session/set_model",{...f,modelId:m});return p.session.applyModelChange(m),h}),a.onRequest("session/set_mode",async f=>{let u=f,p=u?.sessionId;if(typeof p=="string"&&d(p,"session/set_mode"),!u||typeof u.sessionId!="string")throw we(z.InvalidParams,"session/set_mode requires string sessionId");if(typeof u.modeId!="string")throw we(z.InvalidParams,"session/set_mode requires string modeId");let m=un(e.manager,u.sessionId),h=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(u.modeId),h}),a.onRequest("session/set_config_option",async f=>{let u=f,p=b=>we(z.InvalidParams,b),m=u?.sessionId;if(typeof m=="string"&&d(m,"session/set_config_option"),!u||typeof u.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof u.configId!="string")throw p("session/set_config_option requires string configId");if(typeof u.value!="string")throw p("session/set_config_option requires string value");let h=un(e.manager,u.sessionId),w=h.buildConfigOptions().find(b=>b.id===u.configId);if(!w)throw p(`unknown configId ${JSON.stringify(u.configId)} for this session`);if(!w.options.some(b=>b.value===u.value))throw p(`value ${JSON.stringify(u.value)} is not valid for configId ${JSON.stringify(u.configId)}`);switch(u.configId){case"model":{u.value!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:u.sessionId,modelId:u.value}),h.applyModelChange(u.value);break}case"mode":{u.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:u.sessionId,modeId:u.value}),h.applyModeChange(u.value);break}case"agent":{u.value!==h.agentId&&await h.setAgent(u.value);break}default:throw p(`configId ${JSON.stringify(u.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(f,u)=>{if(!u.startsWith("session/")||f===null||typeof f!="object")throw we(z.MethodNotFound,`Method not found: ${u}`);let p=f.sessionId;if(typeof p!="string")throw we(z.MethodNotFound,`Method not found: ${u}`);return d(p,u),un(e.manager,p).forwardRequest(u,f)})})}async function bI(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw we(z.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let u=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(u)}let c=a.authMethods??[],d=c.find(u=>u.id===s);if(!d){let u=c.map(p=>p.id);throw we(z.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${u.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=d._meta?.type;if((d.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let u=d._meta?.args,p=[];if(u!==void 0){if(!Array.isArray(u))throw we(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${u===null?"null":typeof u}`);for(let b of u)if(typeof b!="string")throw we(z.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(b)}`);p=u}let m=await e.manager.planSpawnForAgent(a.agentId),h={};for(let[b,v]of Object.entries(process.env))typeof v=="string"&&(h[b]=v);Object.assign(h,m.env);let w=gh.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m.command,args:[...m.args,...p],env:h,cwd:w}}try{return await a.connection.request("authenticate",{methodId:s})}catch(u){throw ms(u,a)}}function mh(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(ka,n).catch(()=>{})}}function Ll(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function Bl(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function vI(t,e){if(!t||typeof t!="object")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:z.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:z.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=Qr(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(c=>c.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:z.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function SI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw we(z.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw we(z.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw we(z.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return un(n.manager,r).addTransformer(i),{ok:!0}}function kI(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[mt]:ba(e,n)}}function Nl(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...n.resurrected===!0?{resurrected:!0}:{}};return io(e.agentMeta,ba(s,r))}function II(){return{protocolVersion:1,agentInfo:{name:"hydra",version:fe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:io(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function xI(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function ad(t,e,n,s,r){return{clientId:r??`cli_${Dl(8)}`,connection:t,clientInfo:s}}var dd=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as CI}from"crypto";import{McpServer as AI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as RI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as ht}from"zod";function*Hl(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function Dt(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var wh="Bearer ";function pi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith(wh))return;let n=e.slice(wh.length).trim();return n.length>0?n:void 0}function TI(t){let e=new AI({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:ht.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return Dt(s)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:ht.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return Dt(s)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:ht.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:ht.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:ht.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,s,r);return Dt(i)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:ht.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:ht.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.streamInfo();return Dt({outcome:r,writeCursor:i.writeCursor,closed:i.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:ht.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:ht.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:ht.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:ht.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:ht.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:ht.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:ht.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:ht.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:ht.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s);return Dt(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return Dt(n)}),e}var EI=1e4;function bh(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=TI(a),l=new RI({sessionIdGenerator:()=>CI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=pi(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown stdin token"});return}let l;if(d.session!==void 0)l=d.session;else{let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),EI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let f=await s(c,l);a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Ta();import{randomUUID as PI}from"crypto";import{McpServer as MI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as _I}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as bs}from"zod";function $I(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function OI(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function FI(t){let e=new MI({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `recall_search` to find entries by keyword, `recall_range` to pull a contiguous slice verbatim, and `recall_tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("recall_search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via recall_range. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:bs.string().min(1).describe("Case-insensitive substring to search for."),limit:bs.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:bs.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Dt({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. recall_search retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:f}of Hl(o)){if(f==="tool_call"&&!r)continue;let u=Xr([l]),p=u.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let m=$I(f),h=OI(u,p),w=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:m,snippet:h,timestamp:w}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return Dt({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("recall_range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after recall_search narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:bs.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:bs.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return Dt({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. recall_range retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`recall_range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`recall_range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),f=Xr(l);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:l.length,truncated:d}}}),e.registerTool("recall_tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:bs.string().optional(),file_path:bs.string().optional(),limit:bs.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Dt({calls:[],truncated:!1,note:"This session has no compacted history. recall_tool_calls retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("recall_tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[];for(let{entryId:f,entry:u,kind:p,update:m}of Hl(c)){if(p!=="tool_call")continue;let h;if(typeof m.name=="string"&&m.name.length>0?h=m.name:typeof m.title=="string"&&m.title.length>0?h=m.title:h="(unnamed)",n!==void 0&&h.toLowerCase()!==n.toLowerCase())continue;let w=m.rawInput,b={};if(w&&typeof w=="object"&&!Array.isArray(w))for(let[x,T]of Object.entries(w))typeof T=="string"?b[x]=T.length>500?T.slice(0,497)+"\u2026":T:(typeof T=="number"||typeof T=="boolean")&&(b[x]=T);if(a&&w&&typeof w=="object"&&!Array.isArray(w)){let x=s.toLowerCase(),T=["file_path","path"],F=!1;for(let $ of T){let H=w[$];if(typeof H=="string"&&H.toLowerCase()===x){F=!0;break}}if(!F)continue}let v="in_progress";typeof m.status=="string"&&(v=m.status);let S=typeof u.recordedAt=="number"?String(u.recordedAt):void 0;if(d.push({entryId:f,tool:h,args:b,status:v,timestamp:S}),d.length>=r)break}let l=d.length>=r;return Dt({calls:d,truncated:l})}),e}var LI=1e4;function vh(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=FI(a),l=new _I({sessionIdGenerator:()=>PI()});await d.connect(l);let f={server:d,transport:l};return n.set(o,f),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=pi(o);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let d=e.lookup(c);if(d===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(c,async()=>{if(d.session!==void 0)return d.session;let u,p=new Promise(h=>{u=setTimeout(()=>h(void 0),LI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(u!==void 0&&clearTimeout(u),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var cd=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as WI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as zI}from"crypto";import{Server as BI}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as NI,ListToolsRequestSchema as DI}from"@modelcontextprotocol/sdk/types.js";function Sh(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new BI({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(DI,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(NI,async(o,a)=>{let c=o.params.name;if(!i.has(c))return ld(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=UI(d,a.sendNotification);try{let f=await s(),u=await jI(e.connection,t,c,o.params.arguments??{},f);return qI(u,c)}catch(f){return ld(f instanceof Error?f.message:String(f))}finally{l()}}),r}var HI=15e3;function UI(t,e,n=HI){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function jI(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function qI(t,e){if(t===null||typeof t!="object")return ld(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:ld(`extension ${e} omitted content array`)}function ld(t){return{content:[{type:"text",text:t}],isError:!0}}var JI=1e4;function kh(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let f=l.get(d);f!==void 0&&(l.delete(d),r(f))}}n.onChange(d=>{i(d)});async function o(d,l){let f=s.get(d);f===void 0&&(f=new Map,s.set(d,f),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let u=f.get(l);if(u!==void 0)return u.transport;let p=n.lookup(l);if(p===void 0)return;let h=Sh(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),JI)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId}),w=new WI({sessionIdGenerator:()=>zI()});return await h.connect(w),f.set(l,{server:h,transport:w}),w}async function a(d,l){let f=pi(d);if(f===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,m=await o(f,p);if(m===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await m.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function Rh(t,e){XI(t);let n=t.daemon.tls?await mi.readFile(je(t.daemon.tls.key)):void 0,s=t.daemon.tls?await mi.readFile(je(t.daemon.tls.cert)):void 0;await mi.mkdir(_.home(),{recursive:!0});let{stream:r,fileStream:i}=await GI(t.daemon.logLevel),o=KI({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(YI,{options:{handleProtocols:jf}}),Mc(ee=>{o.log.info(ee)}),Oc(ee=>{o.log.info(ee)});let a=await Ja.load(),c=new Qa,d=new Ga,l=new Va([new Ka(e),new Ya(a),d]),f=$m({validator:l});o.addHook("onRequest",async(ee,$e)=>{ee.routeOptions.config?.skipAuth||ee.url==="/acp"||ee.url?.startsWith("/acp?")||await f(ee,$e)});let u=setInterval(()=>{a.sweepExpired()},300*1e3);u.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let m=new ga(t,{onFetched:()=>{xm(m,v)}});xl(ee=>o.log.info(ee));let h={info:ee=>o.log.info(ee),warn:ee=>o.log.warn(ee)},w=ee=>ps.spawn({...ee,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:h});Jf(t.compressToolContent);let b=new Wa,v=new Na(m,w,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:h,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new ja(gf(t),void 0,{tokenRegistry:d}),x=new qa(yf(t),void 0,{tokenRegistry:d});nh(o,fe,gs(t));let T=new dd,F=new cd,$,H=()=>{if($!==void 0)return $;let ee=o.server.address();return $=`http://127.0.0.1:${ee&&typeof ee=="object"?ee.port:t.daemon.port}`,$};eh(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:F,mcpTokenRegistry:T,getDaemonOrigin:H}),th(o,m,v,{npmRegistry:t.npmRegistry}),sh(o,S),rh(o,x),ih(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),ph(o,{store:a,rateLimiter:c}),bh(o,T),vh(o,T),kh(o,T,F),yh(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(ee,$e)=>S.reportVersion(ee,$e),onTransformerVersion:(ee,$e)=>x.reportVersion(ee,$e),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:F,getDaemonOrigin:H,registry:m});let J=!!t.daemon.tls;await o.listen({host:J?"127.0.0.1":t.daemon.host,port:J?0:t.daemon.port});let B=o.server.address(),N=B&&typeof B=="object"?B.port:t.daemon.port,j,X=t.daemon.host,Y=N;if(J&&n&&s){j=QI({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:N,tlsOptions:{key:n,cert:s},logger:o.log});let ee=j.address();ee&&typeof ee=="object"&&(Y=ee.port)}await mi.mkdir(_.home(),{recursive:!0}),await Cf({pid:process.pid,host:X,port:Y,loopbackPort:N,startedAt:new Date().toISOString()});let be={daemonUrl:`http://127.0.0.1:${N}`,daemonHost:"127.0.0.1",daemonPort:N,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${N}/acp`,hydraHome:_.home()};S.setContext(be),x.setContext(be),await S.start(),await x.start(),v.resurrectPendingQueues().catch(ee=>{o.log.warn(`queue replay scan failed: ${ee.message}`)}),v.resumePendingCompactions().catch(ee=>{o.log.warn(`compaction resume scan failed: ${ee.message}`)});let V=t.daemon.agentSyncIntervalMinutes*60*1e3,ge=V>0?Cm({registry:m,manager:v,intervalMs:V,logger:h}):void 0,Je=t.daemon.sessionGcIntervalMinutes*60*1e3,Ms=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ct=Je>0?Am({manager:v,intervalMs:Je,maxAgeMs:Ms,logger:h}):void 0;return{app:o,manager:v,registry:m,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:F,processRegistry:d,shutdown:async()=>{Ct&&Ct(),ge&&ge(),clearInterval(u),clearInterval(p);let ee=async($e,pn)=>{try{await pn()}catch(Ce){o.log.warn(`shutdown step ${$e} failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}};await ee("sessionTokenStore.flush",()=>a.flush()),await ee("extensions.stop",()=>S.stop()),await ee("transformers.stop",()=>x.stop()),await ee("manager.closeAll",()=>v.closeAll()),await ee("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await ee("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await ee("manager.flushMetaWrites",()=>v.flushMetaWrites()),await ee("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Mc(null),Oc(null),xl(null),j&&await ee("tlsTerminator.close",()=>new Promise($e=>j.close(()=>$e()))),await ee("app.close",()=>o.close());try{xh.unlinkSync(_.pidFile())}catch{}await ee("fileStream.flushSync",()=>i.flushSync())}}}async function GI(t){let e=await VI({file:_.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),n=Ih.destination(2);return{stream:Ih.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function QI(t){let e=Ah.createServer(t.tlsOptions,n=>{let s=Ch.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function XI(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}lr();Nt();xo();import*as Eh from"fs";import*as hi from"fs/promises";async function gi(t,e,n){let s=sx(e),r;try{r=await hi.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
265
- `),process.exit(1);return}throw c}let i=await nx(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
266
- `);let o=!1,a=Eh.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await hi.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await hi.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function nx(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await hi.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let f=Buffer.alloc(l);await r.read(f,0,l,i),o=f.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
255
+ `),r}function sI(t){let e=[];for(let n of t.history){if(n.method!=="session/update")continue;let s=n.params;if(!s||typeof s!="object")continue;let r=_n(s.update,{cwd:t.session.cwd});r!==null&&e.push({event:r,recordedAt:n.recordedAt})}return e}function rI(t){let e=new Map;for(let{event:n}of t){if(n.kind==="tool-call"){let s=e.get(n.toolCallId);e.set(n.toolCallId,{title:n.title,status:n.status??s?.status??"pending"});continue}if(n.kind==="tool-call-update"){let s=e.get(n.toolCallId)??{title:"tool call",status:"pending"};e.set(n.toolCallId,{title:n.title??s.title,status:n.status??s.status})}}return e}function iI(t,e){let n=e.session,s=et(n.sessionId),r=n.title?.trim()||`Hydra session ${s}`;t.push(`# ${br(r)}`),t.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${n.lineageId}\`)`);let o=[n.agentId];n.currentModel&&o.push(`model: ${n.currentModel}`),n.currentMode&&o.push(`mode: ${n.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${n.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=n.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let c=[];if(a.used!==void 0){let d=a.size!==void 0?`${Ul(a.size)}`:void 0;c.push(d?`${Ul(a.used)} / ${d} tokens`:`${Ul(a.used)} tokens`)}if(a.costAmount!==void 0){let d=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${d}`)}i.push(`- **Usage:** ${c.join(" \xB7 ")}`)}t.push(i.join(`
256
+ `)),t.push("")}function oI(t,e,n){if(!e.some(d=>aI(d.event))){t.push("_No conversation history recorded._"),t.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(t.push(i.trimEnd()),t.push(""),i="")},c=()=>{o||(r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),o=!0)};for(let{event:d}of e)switch(d.kind){case"user-text":{a(),r+=1,t.push("---"),t.push(""),t.push(`## Turn ${r}`),t.push(""),t.push("**User:**"),t.push("");for(let l of d.text.split(`
257
+ `))t.push(`> ${br(l)}`);t.push(""),t.push("**Assistant:**"),t.push(""),o=!0;break}case"agent-text":c(),i+=d.text;break;case"agent-thought":{c(),a();let l=d.text.split(`
258
+ `);for(let u of l)t.push(`> _${br(u)}_`);t.push("");break}case"tool-call":{if(c(),a(),s.has(d.toolCallId))break;s.add(d.toolCallId);let l=n.get(d.toolCallId)??{title:d.title,status:d.status??"pending"};t.push(`- ${cI(l.status)} ${dI(l)}`),t.push("");break}case"tool-call-update":break;case"plan":{c(),a(),t.push("**Plan:**"),t.push("");for(let l of d.entries){let u=l.status==="completed"?"[x]":"[ ]";t.push(`- ${u} ${br(l.content)}`)}t.push("");break}case"mode-changed":c(),a(),t.push(`_mode: ${br(d.mode)}_`),t.push("");break;case"model-changed":c(),a(),t.push(`_model: ${br(d.model)}_`),t.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function aI(t){switch(t.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function dI(t){let e=t.status,n=e==="completed"||e===void 0?"":` _(${e})_`;return`${br(t.title)}${n}`}function cI(t){switch(t){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function br(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ul(t){return t.toLocaleString("en-US")}xt();Wt();uo();Es();function lI(t){let e=t.trim();if(e.length===0)return{operator:"OR",terms:[]};let n=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=n.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,c=[];for(let l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:c.push(l)}o?i="AND":a&&(i="OR");let d=c.map(l=>uI(l)).filter(l=>l.term.length>0);return{operator:i,terms:d}}function uI(t){let e=/^(\w+):"([^"]*)"$/.exec(t);if(e)return{scope:oh(e[1]),term:e[2]};let n=/^"([^"]*)"$/.exec(t);if(n)return{scope:"all",term:n[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(t);return s?{scope:oh(s[1]),term:s[2].trim()}:{scope:"all",term:t.trim()}}function oh(t){switch(t.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function fI(t,e){return t==="all"?!0:t==="user"?e==="user":t==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var pI=5,mI=200,ah=30;async function lh(t,e,n={}){let s=lI(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=n.maxSnippetsPerSession??pI,i=n.maxSessions??mI,o=n.sessionIds?new Set(n.sessionIds):null,a=await t.list(),c=o?a.filter(u=>o.has(u.sessionId)):a,d=[],l=!1;for(let u of c){if(d.length>=i){l=!0;break}let f=await t.loadHistory(u.sessionId).catch(()=>[]),p=hI(f,s,r);if(p.snippets.length===0)continue;let m={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(m.title=u.title),d.push(m)}return{query:e,truncated:l,results:d}}function hI(t,e,n){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=gI(t,o,i,n-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function gI(t,e,n,s){let r=e.toLowerCase(),i=0,o=[];for(let a of t){let c=yI(a).filter(d=>fI(n,d.kind));for(let d of c){let l=d.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),m={kind:d.kind,text:kI(d.text,p,r.length),recordedAt:a.recordedAt};d.toolName!==void 0&&(m.toolName=d.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function yI(t){if(t.method!=="session/update")return[];let e=t.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let n=e.update;if(!n||typeof n!="object"||Array.isArray(n))return[];let s=n,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=hd(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?tt(s.text):hd(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(vI(s))return[];let i=hd(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=SI(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return wI(s);default:return[]}}function wI(t){let e=dh(t,"name"),n=dh(t,"title"),s=[];if(n!==void 0){let a=xe(n);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==n){let a=xe(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=t.rawInput;if(r&&typeof r=="object"){let a=ch(r);if(a.length>0){let c={kind:"tool-input",text:xe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=t.locations;if(Array.isArray(i)&&i.length>0){let a=ch(i);if(a.length>0){let c={kind:"tool-input",text:xe(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=bI(t);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function bI(t){let e=t.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=xe(o.text);if(a.length>0)return a}}let n=t.rawOutput;if(n&&typeof n=="object"){let s=n.error;if(typeof s=="string"){let r=xe(s);if(r.length>0)return r}}return null}function vI(t){let e=t._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e["hydra-acp"];return!n||typeof n!="object"||Array.isArray(n)?!1:n.compatFor==="prompt_received"}function hd(t){if(typeof t=="string")return tt(t);if(!t||typeof t!="object"||Array.isArray(t))return"";let e=t;return typeof e.text=="string"?tt(e.text):""}function SI(t){if(!Array.isArray(t))return"";let e=[];for(let n of t){let s=hd(n);s.length>0&&e.push(s)}return e.join("")}function dh(t,e){let n=t[e];return typeof n=="string"?n:void 0}function ch(t){try{return JSON.stringify(t)}catch{return""}}function kI(t,e,n){let s=t.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=t.slice(e,e+n).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-ah),c=Math.min(s.length,o+i.length+ah),d=a>0?"\u2026":"",l=c<s.length?"\u2026":"";return`${d}${s.slice(a,c)}${l}`}import{randomBytes as fh}from"crypto";function uh(t){let e=fh(32).toString("hex");return t.tokenRegistry.reserve(e).complete(t.session),t.session.onClose(()=>{t.tokenRegistry.unbind(e)}),{name:t.name,type:"http",url:`${t.getOrigin()}/mcp/${t.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function jl(t){if(t.deps.mcpTokenRegistry===void 0||t.deps.getDaemonOrigin===void 0)return;let e=t.deps.mcpTokenRegistry,n=t.deps.getDaemonOrigin;return async s=>{let r=[...t.baselineMcpServers??[]];t.stdinEnabled&&r.push(uh({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:n})),r.push(uh({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:n}));let i=Si(t.deps);return i!==void 0&&(i.bindToSession(s),r=[...r,...i.descriptors]),r}}function Si(t){if(t.extensionMcp===void 0||t.mcpTokenRegistry===void 0||t.getDaemonOrigin===void 0)return;let e=t.extensionMcp.list();if(e.length===0)return;let n=fh(32).toString("hex"),s=t.mcpTokenRegistry.reserve(n),r=t.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${n}`}]})),o=t.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(n)})},abandon:a=>s.abandon(a)}}var gd=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ph(t){if(t.publicHost&&t.publicHost.length>0)return t.publicHost;if(t.host&&!dr(t.host))return t.port!==void 0?`${t.host}:${t.port}`:t.host}function hh(t,e,n,s={}){t.get("/v1/sessions",async d=>{let l=d.query,u=l?.includeNonInteractive==="1"||l?.includeNonInteractive==="true";return{sessions:await e.list({cwd:l?.cwd,includeNonInteractive:u})}}),t.get("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.getOne(f);return p||(l.code(404).send({error:"session not found"}),l)}),t.post("/v1/sessions/search",async(d,l)=>{let u=d.body??{},f=typeof u.q=="string"?u.q:"";if(f.trim().length===0)return l.code(400).send({error:"q is required"}),l;let p=Array.isArray(u.sessionIds)?u.sessionIds.filter(h=>typeof h=="string"&&h.length>0):void 0;return await lh(e,f,{sessionIds:p})}),t.post("/v1/sessions",async(d,l)=>{let u=d.body??{},f=Je(u.cwd??n.cwd),p=u.agentId??n.agentId,m=Si(s),h=m!==void 0?[...u.mcpServers??[],...m.descriptors]:u.mcpServers;try{let y=await e.create({cwd:f,agentId:p,mcpServers:h});m!==void 0&&m.bindToSession(y),l.code(201).send({sessionId:y.sessionId,agentId:y.agentId,cwd:y.cwd})}catch(y){m!==void 0&&m.abandon(y instanceof Error?y:void 0),l.code(500).send({error:y.message})}}),t.post("/v1/sessions/collect",async(d,l)=>{let u=d.body??{},f=typeof u.maxAgeDays=="number"&&u.maxAgeDays>0?u.maxAgeDays*24*60*60*1e3:0,p=typeof u.limit=="number"&&u.limit>0?u.limit:1e3,m=u.selection==="explicit"||u.selection==="unpromoted"?u.selection:"unpromoted";try{let h=await Ll({manager:e,maxAgeMs:f,maxDeletions:p,selection:m,verbose:!1});l.code(200).send(h)}catch(h){l.code(500).send({error:h.message})}}),t.post("/v1/sessions/:id/kill",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){p.close({deleteRecord:!1}).catch(()=>{}),l.code(202).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.post("/v1/sessions/:id/stdin/open",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let m=d.body??{},h={};(m.mode==="memory"||m.mode==="file")&&(h.mode=m.mode),typeof m.capacityBytes=="number"&&(h.capacityBytes=m.capacityBytes),typeof m.fileCapBytes=="number"&&(h.fileCapBytes=m.fileCapBytes),(h.mode??"memory")==="file"&&(h.filePathFor=y=>mh.join(Bo.tmpdir(),`hydra-acp-stdin-${y}.log`));try{return p.openStream(h)}catch(y){return l.code(409).send({error:y.message}),l}}),t.post("/v1/sessions/:id/stdin",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(!p)return l.code(404).send({error:"session not found"}),l;let m=d.body??{},h=typeof m.chunk=="string"?m.chunk:"",y=m.eof===!0;try{return p.streamWrite(h,y)}catch(b){return l.code(409).send({error:b.message}),l}}),t.patch("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{};if(p.priority!==void 0){let h=p.priority,y;if(h===null||h===0)y=void 0;else if(typeof h=="number"&&Number.isInteger(h)&&h>0)y=h;else{l.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(f,y)){l.code(404).send({error:"session not found"});return}l.code(204).send();return}if(p.regen===!0){if(!(e.get(f)!==void 0||await e.hasRecord(f))){l.code(404).send({error:"session not found"});return}e.scheduleSynopsis(f),l.code(202).send();return}if(typeof p.title!="string"||p.title.trim().length===0){l.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.delete("/v1/sessions/:id",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);if(p){await p.close({deleteRecord:!0}),l.code(204).send();return}if(!await e.deleteRecord(f)){l.code(404).send({error:"session not found"});return}l.code(204).send()}),t.get("/v1/sessions/:id/export",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.query?.tools,m=p==="references"?"references":xm(p),h=await e.exportBundle(f,m==="references"?{tools:"references"}:{});if(!h){l.code(404).send({error:"session not found"});return}let y=Ro({record:h.record,history:m==="summary"?Cm(h.history,"summary"):h.history,promptHistory:h.promptHistory.length>0?h.promptHistory:void 0,...h.toolBlobs!==void 0?{toolBlobs:h.toolBlobs}:{},hydraVersion:pe,machine:Bo.hostname(),hydraHost:ph(n)}),b=new Date().toISOString().replace(/[:.]/g,"-");l.header("Content-Disposition",`attachment; filename="${f}-${b}.hydra"`),l.code(200).send(y)}),t.get("/v1/sessions/:id/diff",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let m=d.query??{},h=m.fold==="true"||m.fold==="1",y=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,b=bi(p.history);y&&(b=b.filter(v=>y.has(v.path))),h&&(b=b.map(v=>({...v,hunks:vi(v.hunks)}))),l.code(200).send(b)}),t.get("/v1/sessions/:id/tools/:hash",async(d,l)=>{let u=d.params,f=await e.resolveCanonicalId(u.id)??u.id,p=await e.loadToolBlob(f,u.hash);if(p===null){l.code(404).send({error:"tool blob not found"});return}l.header("Content-Type","text/plain; charset=utf-8"),l.code(200).send(p)}),t.get("/v1/sessions/:id/transcript",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=await e.exportBundle(f);if(!p){l.code(404).send({error:"session not found"});return}let m=Ro({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:pe,machine:Bo.hostname(),hydraHost:ph(n)});l.header("Content-Type","text/markdown; charset=utf-8"),l.code(200).send(md(m))}),t.post("/v1/sessions/:id/fork",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=d.body??{},m={};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}m.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}m.cwd=Je(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}m.agentId=p.agentId}if(p.title!==void 0){if(typeof p.title!="string"){l.code(400).send({error:"title must be a string"});return}m.title=p.title}try{let h=await e.forkSession(f,m);l.code(201).send(h)}catch(h){let y=h;if(y.code===W.SessionNotFound){l.code(404).send({error:y.message});return}if(y.code===W.InvalidParams||y.code===W.AgentNotInstalled){l.code(400).send({error:y.message});return}l.code(500).send({error:y.message})}}),t.post("/v1/sessions/import",async(d,l)=>{let u=d.body??{};if(u.bundle===void 0){l.code(400).send({error:"missing bundle"});return}let f;if(u.cwd!==void 0){if(typeof u.cwd!="string"||u.cwd.length===0){l.code(400).send({error:"cwd must be a non-empty string"});return}f=u.cwd}let p;try{p=gn(u.bundle)}catch(m){l.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(p,{replace:u.replace===!0,...f!==void 0?{cwd:f}:{}});l.code(201).send(m)}catch(m){let h=m;if(h.code===W.BundleAlreadyImported){l.code(409).send({error:"bundle already imported",existingSessionId:h.existingSessionId});return}l.code(500).send({error:h.message})}}),t.get("/v1/sessions/:id/compact/status",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f),m;if(p?m=p.summarizedThroughEntry:m=await e.getSummarizedThroughEntry(f),m===void 0&&!await e.hasRecord(f))return l.code(404).send({error:"session not found"}),l;let h=await e.getCompactionState(f),y=await e.getRollbackBreadcrumb(f),b=!1,v,x=await e.getHistory(f).catch(()=>[])??[];if(x.length>0&&n.compaction){let T=m??0,_=x.length,j=x.slice(T).reduce((U,Q)=>U+JSON.stringify(Q.params).length,0);v=Nl(j);let J=p?.currentModel,D=x.at(-1).recordedAt,L=p?.currentUsage;b=Qm({summarizedThroughEntry:T,totalEntries:_,unsummarizedChars:j,compactionInFlight:e.getCompactionInFlight(),currentModel:J,lastActivityMs:D,nowMs:Date.now(),config:n.compaction,...typeof L?.used=="number"?{agentReportedUsed:L.used}:{},...typeof L?.size=="number"?{agentReportedSize:L.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:b,...v!=null?{approxTokens:v}:{},...h!=null?{compactionState:h}:{},...y!=null?{rollbackBreadcrumb:y}:{}}}),t.post("/v1/sessions/:id/compact",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(e.get(f)){e.scheduleCompaction(f),l.code(202).send({scheduled:!0});return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}e.scheduleCompaction(f),l.code(202).send({scheduled:!0})}),t.post("/v1/sessions/:id/compact/rollback",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u;if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}try{await e.performUncompact(f),l.code(202).send({rolledBack:!0})}catch(p){let m=p instanceof Error?p.message:String(p);l.code(409).send({error:m})}}),t.get("/v1/sessions/:id/history",async(d,l)=>{let u=d.params.id,f=d.query,p=f?.follow==="1"||f?.follow==="true",m=await e.resolveCanonicalId(u)??u,h=e.get(m),y,b,v=!1,S=1e4,x=[];if(h){p&&(b=h.onBroadcast(_=>{l.raw.writableEnded||(v?l.raw.write(JSON.stringify(_)+`
259
+ `):(x.push(_),x.length>S&&x.shift()))})),d.raw.on("close",()=>{b?.(),l.raw.writableEnded||l.raw.end()});try{y=await h.getHistorySnapshot()}catch(_){throw b?.(),_}}else{let _=await e.getHistory(m);if(_===void 0)return l.code(404).send({error:"session not found"}),l;y=_}l.raw.setHeader("Content-Type","application/x-ndjson"),l.raw.setHeader("Cache-Control","no-cache"),l.raw.statusCode=200;let T=new Set;for(let _ of y??[]){l.raw.write(JSON.stringify(_)+`
260
+ `);let F=_;typeof F.recordedAt=="number"&&T.add(String(F.recordedAt))}for(;x.length>0;){let _=x.splice(0,x.length);for(let F of _){let j=F,J=typeof j.recordedAt=="number"?String(j.recordedAt):"";J&&T.has(J)||l.raw.write(JSON.stringify(F)+`
261
+ `)}}return v=!0,b||l.raw.end(),l});function r(d,l,u){let f=typeof d=="string"?d.trim():"";if(f.length===0)return null;let p;try{p=JSON.parse(f)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!p||typeof p!="object"||Array.isArray(p))return console.debug("events endpoint: skipping non-object JSONL line"),null;let m=p;if(typeof m.recordedAt!="number"||u!==void 0&&m.recordedAt<u||typeof m.params!="object"||m.params===null||Array.isArray(m.params))return null;let h=m.params;if(typeof h.update!="object"||h.update===null||Array.isArray(h.update))return null;let b=h.update.sessionUpdate;return typeof b!="string"||!l.has(b)?null:{recordedAt:m.recordedAt,entry:p}}function i(d,l,u){let p=l.params.update,m={sessionId:d,ts:new Date(l.recordedAt).toISOString(),kind:u,update:p};return p.messageId!==void 0&&p.messageId!==null&&(m.messageId=p.messageId),m}async function*o(d,l,u,f){for await(let p of l){let m=r(p,u,f);if(m){let h=m.entry.params.update.sessionUpdate;yield{ts:m.recordedAt,row:i(d,m.entry,h)}}}}async function a(d,l,u,f){let p=Wl.createInterface({input:ql.createReadStream(l),crlfDelay:1/0}),m=o(d,p,u,f),h=await m.next(),y=h.done?null:h.value;return{sessionId:d,rl:p,gen:m,current:y,exhausted:y===null}}async function c(d){let l=await d.gen.next();l.done?(d.exhausted=!0,d.current=null):d.current=l.value}t.get("/v1/sessions/events",async(d,l)=>{let u=d.query,f=u.kinds;if(!f||f.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let p=f.split(",").map(S=>S.trim());if(p.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let S of p)if(!gd.has(S))return l.code(400).send({error:`kind "${S}" is not queryable; allowed kinds: ${[...gd].join(", ")}`}),l;let m=new Set(p),h;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;h=S.getTime()}let y=await e.list({includeNonInteractive:!0}),b=h!==void 0?y.filter(S=>new Date(S.updatedAt).getTime()>=h):y;l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;let v=[];for(let S of b)try{let x=$.historyFile(S.sessionId),T=await a(S.sessionId,x,m,h);T.exhausted||v.push(T)}catch(x){if(x.code==="ENOENT")continue;throw x}d.raw.on("close",()=>{for(let S of v)try{S.rl.close()}catch{}l.raw.writableEnded||l.raw.end()});try{for(;v.length>0;){let S=-1,x=1/0;for(let _=0;_<v.length;_++){let F=v[_];F.current!==null&&F.current.ts<x&&(x=F.current.ts,S=_)}if(S===-1)break;let T=v[S];if(l.raw.write(JSON.stringify(T.current.row)+`
262
+ `),await c(T),T.exhausted){try{T.rl.close()}catch{}v.splice(S,1)}}}catch(S){for(let x of v)try{x.rl.close()}catch{}throw S}return l.raw.end(),l}),t.get("/v1/sessions/:id/events",async(d,l)=>{let u=d.params.id,f=d.query,p=await e.resolveCanonicalId(u)??u;if(!e.get(p)&&!await e.hasRecord(p))return l.code(404).send({error:"session not found"}),l;let h=f.kinds;if(!h||h.trim().length===0)return l.code(400).send({error:"kinds parameter is required"}),l;let y=h.split(",").map(_=>_.trim());if(y.length===0)return l.code(400).send({error:"kinds parameter is required"}),l;for(let _ of y)if(!gd.has(_))return l.code(400).send({error:`kind "${_}" is not queryable; allowed kinds: ${[...gd].join(", ")}`}),l;let b=new Set(y),v;if(f.since!==void 0&&f.since.trim().length>0){let _=new Date(f.since);if(isNaN(_.getTime()))return l.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),l;v=_.getTime()}let S=$.historyFile(p),x=ql.createReadStream(S),T=Wl.createInterface({input:x,crlfDelay:1/0});l.raw.setHeader("content-type","application/x-ndjson"),l.raw.statusCode=200;try{for await(let _ of T){let F=typeof _=="string"?_.trim():"";if(F.length===0)continue;let j;try{j=JSON.parse(F)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",S);continue}if(!j||typeof j!="object"||Array.isArray(j)){console.debug("events endpoint: skipping non-object JSONL line in %s",S);continue}let J=j;if(typeof J.recordedAt!="number"||typeof J.params!="object"||J.params===null||Array.isArray(J.params))continue;let D=J.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let L=D.update,U=L.sessionUpdate;if(typeof U!="string"||!b.has(U)||v!==void 0&&J.recordedAt<v)continue;let Q={ts:new Date(J.recordedAt).toISOString(),kind:U,update:L};L.messageId!==void 0&&L.messageId!==null&&(Q.messageId=L.messageId),l.raw.write(JSON.stringify(Q)+`
263
+ `)}}catch(_){if(_.code==="ENOENT")return l.raw.end(),l;throw _}return l.raw.end(),l}),t.get("/v1/sessions/:id/attention",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,p=e.get(f);return!p&&!await e.hasRecord(f)?(l.code(404).send({error:"session not found"}),l):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),t.get("/v1/sessions/attention",async(d,l)=>{let u=d.query;if(!u.source||u.source.trim().length===0)return l.code(400).send({error:"source query parameter is required"}),l;let f=await e.list({includeNonInteractive:!0}),p=[];for(let m of f){let h=e.get(m.sessionId),y;h?y=h.listAttentionFlags():y=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let b of y)b.source===u.source&&p.push({...b,sessionId:m.sessionId})}return{flags:p}}),t.post("/v1/sessions/:id/attention/clear",async(d,l)=>{let u=d.params.id,f=await e.resolveCanonicalId(u)??u,m=d.body??{},h=typeof m.source=="string"?m.source:"",y=typeof m.reason=="string"?m.reason:"";if((h.length>0||y.length>0)&&!(h.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}h.length===0&&y.length;let b=e.get(f);if(b){if(h.length>0&&y.length>0)b.clearAttentionFlag(h,y);else{let _=Array.from(b.listAttentionFlags()).map(F=>`${F.source}::${F.reason}`);for(let F of _)b.clearAttentionFlag(F.split("::")[0],F.split("::").slice(1).join("::"))}l.code(204).send();return}if(!await e.hasRecord(f)){l.code(404).send({error:"session not found"});return}let v=e.store,S=await v.read(f);if(!S){l.code(404).send({error:"session not found"});return}let x=S.attentionFlags??[],T;if(h.length>0&&y.length>0){let _=`${h}::${y}`;T=x.filter(F=>`${F.source}::${F.reason}`!==_)}else T=[];if(T.length===x.length&&T.every((_,F)=>_.source===x[F].source&&_.reason===x[F].reason)){l.code(204).send();return}await v.write({...S,attentionFlags:T}),l.code(204).send()})}xt();function gh(t,e,n,s={}){t.get("/v1/agents",async()=>ri(e)),t.get("/v1/registry",async()=>e.load()),t.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),t.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await hn(a,[],{npmRegistry:s.npmRegistry}),d=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:c.version,distribution:d,installed:!0,command:c.command})}catch(c){i.code(500).send({error:c.message})}}),t.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:c}=await n.syncFromAgent(o);return{synced:a.map(d=>({sessionId:d.sessionId,upstreamSessionId:d.upstreamSessionId,agentId:d.agentId,cwd:d.cwd,title:d.title,updatedAt:d.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===W.AgentNotInstalled){i.code(404).send({error:c.message});return}i.code(409).send({error:c.message})}})}function yh(t,e,n){t.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:n}))}var II=/^[A-Za-z0-9._-]+$/;function yd(t,e,n){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;t.get(r,async()=>({[s]:n.list()})),t.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,c=n.get(a);if(!c){o.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),t.post(r,async(i,o)=>{let a=i.body??{},c=xI(a);if("error"in c){o.code(400).send({error:c.error});return}try{let d=n.register(c.config);o.code(201).send(d)}catch(d){No(o,d)}}),t.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await n.unregister(a),o.code(204).send()}catch(c){No(o,c)}}),t.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let c=await n.startByName(a);o.code(200).send(c)}catch(c){No(o,c)}}),t.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let c=await n.stopByName(a);o.code(200).send(c)}catch(c){No(o,c)}}),t.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let c=await n.restartByName(a);o.code(200).send(c)}catch(c){No(o,c)}})}function No(t,e){let n=e.code,s=e.message??"unknown error";if(n==="NOT_FOUND"){t.code(404).send({error:s});return}if(n==="CONFLICT"){t.code(409).send({error:s});return}t.code(500).send({error:s})}function xI(t){let e=t.name;if(typeof e!="string"||!II.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let n=t.command;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=t.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=t.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=t.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:n??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function wh(t,e){yd(t,"extension",e)}function bh(t,e){yd(t,"transformer",e)}function vh(t,e){t.get("/v1/config",async()=>e)}import{z as ki}from"zod";he();import*as Ps from"fs/promises";import*as xh from"path";import{randomBytes as CI,scrypt as AI,timingSafeEqual as RI}from"crypto";import{promisify as TI}from"util";var Ch=TI(AI);function zl(){return xh.join($.home(),"password-hash")}var Sh=32768,kh=8,Ih=1,EI=64,PI=16,Ah=128*1024*1024;async function Rh(t){if(typeof t!="string"||t.length===0)throw new Error("password must be a non-empty string");let e=CI(PI),n=await Ch(t,e,EI,{N:Sh,r:kh,p:Ih,maxmem:Ah}),s=`scrypt$${Sh}$${kh}$${Ih}$${e.toString("hex")}$${n.toString("hex")}
264
+ `;await Ps.mkdir($.home(),{recursive:!0}),await Ps.writeFile(zl(),s,{encoding:"utf8",mode:384})}async function wd(){try{return(await Ps.readFile(zl(),"utf8")).trim().length>0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bd(t){if(typeof t!="string"||t.length===0)return!1;let e;try{e=(await Ps.readFile(zl(),"utf8")).trim()}catch(d){if(d.code==="ENOENT")return!1;throw d}let n=e.split("$");if(n.length!==6||n[0]!=="scrypt")return!1;let s=parseInt(n[1],10),r=parseInt(n[2],10),i=parseInt(n[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(n[4],"hex"),a=Buffer.from(n[5],"hex");if(o.length===0||a.length===0)return!1;let c=await Ch(t,o,a.length,{N:s,r,p:i,maxmem:Ah});return c.length!==a.length?!1:RI(c,a)}var MI=ki.object({password:ki.string().min(1),label:ki.string().min(1).max(256).optional(),ttlSec:ki.number().int().positive().optional()}),_I=ki.object({id:ki.string().optional()}).optional();function Th(t,e){t.post("/v1/auth/login",{config:{skipAuth:!0}},async(n,s)=>{let r=$I(n);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=MI.parse(n.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await wd())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await bd(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),t.post("/v1/auth/logout",async(n,s)=>{let r;try{r=_I.parse(n.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??n.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),t.get("/v1/auth/verify",async(n,s)=>s.code(200).send({ok:!0})),t.get("/v1/auth/sessions",async(n,s)=>s.code(200).send({sessions:e.store.list()})),t.delete("/v1/auth/sessions/:id",async(n,s)=>{let r=n.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function $I(t){return t.ip||"unknown"}pr();Ii();import{nanoid as Ql}from"nanoid";Ha();xt();Wt();import{randomBytes as Ph}from"crypto";import*as Mh from"os";function fe(t,e,n){let s=new Error(e);return s.code=t,n!==void 0&&(s.data=n),s}function NI(t){if(!t||typeof t!="object")return 512;let s=t.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let d=c.content;typeof d.text=="string"&&(r+=d.text.length)}}return r}function zt(t,e,n){let s=t.get(e);if(!s)throw fe(W.SessionNotFound,n??`session ${e} not found`);return s}async function Jl(t,e){let n=Si(t),s,r,i;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&t.mcpTokenRegistry!==void 0&&t.getDaemonOrigin!==void 0&&(s=Ph(32).toString("hex"),r=t.mcpTokenRegistry.reserve(s),i={name:"hydra-acp-recall",type:"http",url:`${t.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...n?.descriptors??[],...i!==void 0?[i]:[]],c=jl({baselineMcpServers:void 0,stdinEnabled:!1,deps:t}),d;try{d=await t.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(l){throw n!==void 0&&n.abandon(l instanceof Error?l:void 0),r!==void 0&&r.abandon(l instanceof Error?l:void 0),l}if(n!==void 0&&n.bindToSession(d),s!==void 0&&r!==void 0&&t.mcpTokenRegistry!==void 0){let l=s,u=t.mcpTokenRegistry;r.complete(d),d.onClose(()=>{u.unbind(l)})}return JI(d,t),d}function _h(t,e){t.get("/acp",{websocket:!0},async(n,s)=>{let r=Ym({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){n.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=$n(n),a=new _t(o),c={clientId:`hydra_client_${Ql(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 fe(W.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=vp.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)),zI()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},m=Array.isArray(p.commands)?p.commands.map(h=>{if(!h||typeof h!="object")return;let y=h;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(h=>h!==void 0):[];return u.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},m=typeof p.instructions=="string"?p.instructions:void 0,h=Array.isArray(p.tools)?p.tools.map(y=>{if(!y||typeof y!="object")return;let b=y;if(typeof b.name!="string"||b.name.length===0||typeof b.description!="string"||b.inputSchema===null||typeof b.inputSchema!="object")return;let v={name:b.name,description:b.description,inputSchema:b.inputSchema};return b.outputSchema!==null&&typeof b.outputSchema=="object"&&(v.outputSchema=b.outputSchema),v}).filter(y=>y!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,h),{ok:!0,registered:h.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.method=="string"?f.method:void 0,h=f.envelope,y=f.route;if(!p)throw fe(-32602,"emit_message requires sessionId");if(!m&&y!=="client_broadcast")throw fe(-32602,"emit_message requires method");let b=zt(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return b.dischargeClaim(v,h),{ok:!0};if(y==="chain")return{ok:!0,response:await b.emitToChain(i.name,m,h)};if(y==="daemon")return{ok:!0,response:await b.emitToChain(i.name,m,h)};if(y==="client_broadcast"){if(!h||typeof h!="object")throw fe(-32602,"client_broadcast requires an envelope object");return b.broadcastClientUpdate(h),{ok:!0}}throw fe(-32602,`unsupported route: ${JSON.stringify(y)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw fe(-32602,"hydra-acp/session/request_permission requires sessionId");return zt(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>UI(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,m=typeof f.cwd=="string"?f.cwd:void 0,h=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,y=f._meta&&typeof f._meta=="object"?f._meta:void 0,b=y&&y["hydra-acp"]&&typeof y["hydra-acp"]=="object"?y["hydra-acp"]:void 0,v=b&&typeof b.title=="string"?b.title:void 0,S=b&&typeof b.model=="string"?b.model:void 0;if(!m&&h){let _=e.manager.get(h);_&&(m=_.cwd)}if(!m)throw fe(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let x=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:h,interactive:x,transformChain:[],title:v,model:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw fe(W.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,m=typeof f.cwd=="string"?f.cwd:void 0,h=typeof f.agentId=="string"?f.agentId:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw fe(W.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw fe(W.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,m=f.until==="idle"?"idle":"turn_complete",h=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw fe(-32602,"await_child requires childSessionId");let y=zt(e.manager,p,`child session ${p} not found`);return new Promise(b=>{let x=[],T=[],_=0,F=!1,j,J,D=!1,L=()=>{D||(D=!0,clearTimeout(U),j?.(),J?.(),b(F?{entries:x,truncated:!0}:{entries:x}))};j=y.onBroadcast(Q=>{let V=NI(Q);for(x.push(Q),T.push(V),_+=V;x.length>0&&(x.length>1e3||_>1048576);)x.shift(),_-=T.shift()??0,F=!0;m==="turn_complete"&&Q.params?.update?.sessionUpdate==="turn_complete"&&L()});let U=setTimeout(L,h);typeof U.unref=="function"&&U.unref(),J=y.onClose(()=>L())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw fe(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async u=>jI(u,i.name,e)),a.onRequest("hydra-acp/attention/clear",async u=>qI(u,i.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,m=typeof f.sessionId=="string"?f.sessionId:void 0,h=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,h),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw fe(W.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,m=await e.manager.loadToolBlob(p,f.hash);if(m===null)throw fe(W.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async u=>DI(u,e)),a.onRequest("session/new",async u=>{let f=Sp.parse(u),p=qt(u?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(U=>typeof U=="string")?p.transformers:e.manager.defaultTransformers??[],h=e.transformers?.resolveChain(m)??[],y,b,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){y=Ph(32).toString("hex"),b=e.mcpTokenRegistry.reserve(y);let Q={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${y}`}]};v=[...f.mcpServers??[],Q]}let S,x,T=Si(e);T!==void 0&&(v=[...v??[],...T.descriptors]);let _=jl({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),F;try{F=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Eh(a),transformChain:h,originatingClient:c.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},..._?{mintMcpServersForSwap:_}:{}})}catch(U){throw b!==void 0&&b.abandon(U instanceof Error?U:void 0),x!==void 0&&x.abandon(U instanceof Error?U:void 0),T!==void 0&&T.abandon(U instanceof Error?U:void 0),U}if(y!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let U=y,Q=e.mcpTokenRegistry;b.complete(F),F.onClose(()=>{Q.unbind(U)})}if(S!==void 0&&x!==void 0&&e.mcpTokenRegistry!==void 0){let U=S,Q=e.mcpTokenRegistry;x.complete(F),F.onClose(()=>{Q.unbind(U)})}T!==void 0&&T.bindToSession(F);let j,J;try{j=vd(a,F,c),{entries:J}=await F.attach(j,"full")}catch(U){throw await F.close({deleteRecord:!1}).catch(()=>{}),U}c.attached.set(F.sessionId,{sessionId:F.sessionId,clientId:j.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let U of J){if(a.isClosed())break;await a.notify(U.method,U.params).catch(()=>{})}})()});let D=Kl(F),L=Vl(F);return{sessionId:F.sessionId,...D?{modes:D}:{},...L?{models:L}:{},configOptions:F.buildConfigOptions(),_meta:Yl(e.manager,F,{clientId:j.clientId})}}),a.onRequest("session/attach",async u=>{let f=Ip.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=qt(f._meta),h=m.resume,y=m.readonly===!0,b=m.env;t.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!h} readonly=${y}`);let v=h?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,S=e.manager.get(v);if(!S&&y){let L=await e.manager.loadFromDisk(v);if(!L)throw fe(W.SessionNotFound,`session ${f.sessionId} not found`);let U=await e.manager.loadHistory(v),Q=f.clientId??`cli_${Ql(8)}`;c.attached.set(L.hydraSessionId,{sessionId:L.hydraSessionId,clientId:Q,readonly:!0}),t.log.info(`session/attach OK (viewer) sessionId=${L.hydraSessionId} clientId=${Q} attachedCount=${c.attached.size} replayed=${U.length}`);for(let V of U)await a.notify(V.method,V.params).catch(()=>{});return{sessionId:L.hydraSessionId,clientId:Q,connectedClients:[Q],historyPolicy:"full",replayed:U.length,_meta:WI(L)}}let x=!S;if(!S){let L=await e.manager.loadFromDisk(v),U=L;if(h&&(U={...L,hydraSessionId:f.sessionId,upstreamSessionId:h.upstreamSessionId,agentId:h.agentId,cwd:h.cwd,...h.title!==void 0?{title:h.title}:{},...h.agentArgs!==void 0?{agentArgs:h.agentArgs}:{}}),!U)throw fe(W.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);let Q=U.originatingClient?U:{...U,originatingClient:c.clientInfo},V=b!==void 0?{...Q,forwardedEnv:b}:Q;S=await Jl(e,{...V,onInstallProgress:Eh(a)})}let T=vd(a,S,c,f.clientInfo,f.clientId),_=m.replayMode==="drip",{entries:F,appliedPolicy:j}=await S.attach(T,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:_,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:T.clientId,readonly:y}),b!==void 0&&await e.manager.setForwardedEnv(S.sessionId,b).catch(()=>{}),t.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${T.clientId} attachedCount=${c.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${j} replayed=${F.length} readonly=${y}${_?" replayMode=drip":""}`),_){let L=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,U=750;(async()=>{let Q=null;for(let V of F){let be=typeof V.recordedAt=="number"?V.recordedAt:null;if(Q!==null&&be!==null){let Y=Math.min(U,Math.max(0,(be-Q)/L));Y>0&&await new Promise(ye=>setTimeout(ye,Y))}be!==null&&(Q=be);try{await a.notify(V.method,V.params)}catch{return}}})()}else for(let L=0;L<F.length&&!a.isClosed();L++){let U=F[L],Q=a.notify(U.method,U.params).catch(()=>{});(L+1)%200===0&&await Q}S.replayPendingPermissions(T);let J=Kl(S),D=Vl(S);return{sessionId:S.sessionId,clientId:T.clientId,connectedClients:S.connectedClients(T.clientId),historyPolicy:j,replayed:F.length,...J?{modes:J}:{},...D?{models:D}:{},configOptions:S.buildConfigOptions(),_meta:Yl(e.manager,S,{resurrected:x})}}),a.onRequest("session/detach",async u=>{let f=xp.parse(u),p=c.attached.get(f.sessionId);if(!p)throw fe(W.SessionNotFound,"client not attached to that session");let m=e.manager.get(f.sessionId);return m?.detach(p.clientId),c.attached.delete(f.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[ht]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Cp.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(y=>y.originatingClient?.name!==hr).map(Ap)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw fe(W.InternalError,"agent registry unavailable");return ri(e.registry)}),a.onRequest("session/prompt",async u=>{let f=Rp.parse(u);d(f.sessionId,"session/prompt");let p=c.attached.get(f.sessionId);if(!p)throw t.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),fe(W.SessionNotFound,"not attached to session");let m=e.manager.get(f.sessionId);if(!m){let h=await e.manager.loadFromDisk(f.sessionId);if(!h)throw fe(W.SessionNotFound,`session ${f.sessionId} not found`);t.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),m=await Jl(e,h);let y=vd(a,m,c,void 0,p.clientId);await m.attach(y,"none")}return m.prompt(p.clientId,f)});let l=u=>{let f;try{f=Fa.parse(u)}catch(h){t.log.warn(`session/cancel: invalid params: ${h.message}`);return}let p=c.attached.get(f.sessionId);if(!p)return;if(p.readonly){t.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let m=e.manager.get(f.sessionId);m&&m.cancel(p.clientId).catch(h=>{t.log.warn(`session/cancel for ${f.sessionId}: ${h.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=Fa.parse(u);return d(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Ep.parse(u);return d(f.sessionId,"hydra-acp/prompt/cancel"),zt(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=Fa.parse(u);return d(f.sessionId,"hydra-acp/session/force_cancel"),zt(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Pp.parse(u);return d(f.sessionId,"hydra-acp/prompt/update"),zt(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Mp.parse(u);d(f.sessionId,"hydra-acp/prompt/amend");let p=c.attached.get(f.sessionId);if(!p)throw fe(W.SessionNotFound,"not attached to session");return zt(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw fe(W.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,h=e.manager.get(m);if(!h){let x=await e.manager.loadFromDisk(m);if(!x)throw fe(W.SessionNotFound,`session ${p} not found in memory or on disk`);h=await Jl(e,x)}let y=vd(a,h,c),{entries:b}=await h.attach(y,"pending_only");c.attached.set(h.sessionId,{sessionId:h.sessionId,clientId:y.clientId,readonly:!1});for(let x of b){if(a.isClosed())break;await a.notify(x.method,x.params).catch(()=>{})}h.replayPendingPermissions(y);let v=Kl(h),S=Vl(h);return{sessionId:h.sessionId,...v?{modes:v}:{},...S?{models:S}:{},configOptions:h.buildConfigOptions(),_meta:Yl(e.manager,h,{clientId:y.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&d(f,"session/set_model");let p=HI(u,e.manager);if(p.kind==="error")throw t.log.warn(p.logMessage),fe(p.code,p.message);if(p.kind==="no_op")return t.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;t.log.info(p.logMessage);let{modelId:m}=p,h=await p.session.forwardRequest("session/set_model",{...u,modelId:m});return p.session.applyModelChange(m),h}),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 fe(W.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw fe(W.InvalidParams,"session/set_mode requires string modeId");let m=zt(e.manager,f.sessionId),h=await m.forwardRequest("session/set_mode",u);return m.applyModeChange(f.modeId),h}),a.onRequest("session/set_config_option",async u=>{let f=u,p=b=>fe(W.InvalidParams,b),m=f?.sessionId;if(typeof m=="string"&&d(m,"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 h=zt(e.manager,f.sessionId),y=h.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!==h.currentModel&&await h.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),h.applyModelChange(f.value);break}case"mode":{f.value!==h.currentMode&&await h.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),h.applyModeChange(f.value);break}case"agent":{f.value!==h.agentId&&await h.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:h.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=f.startsWith("session/"),h=f.startsWith("hydra-acp/");if(!m&&!h||u===null||typeof u!="object"||p.has(f))throw fe(W.MethodNotFound,`Method not found: ${f}`);let y=u.sessionId;if(typeof y!="string")throw fe(W.MethodNotFound,`Method not found: ${f}`);return d(y,f),zt(e.manager,y).forwardRequest(f,u)})})}async function DI(t,e){let n=t??{};if(typeof n.methodId!="string"||n.methodId.length===0)throw fe(W.InvalidParams,"authenticate requires a non-empty methodId string");let s=n.methodId,r=n._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let f=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(f)}let c=a.authMethods??[],d=c.find(f=>f.id===s);if(!d){let f=c.map(p=>p.id);throw fe(W.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${f.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=d._meta?.type;if((d.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let f=d._meta?.args,p=[];if(f!==void 0){if(!Array.isArray(f))throw fe(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${f===null?"null":typeof f}`);for(let b of f)if(typeof b!="string")throw fe(W.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(b)}`);p=f}let m=await e.manager.planSpawnForAgent(a.agentId),h={};for(let[b,v]of Object.entries(process.env))typeof v=="string"&&(h[b]=v);Object.assign(h,m.env);let y=Mh.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m.command,args:[...m.args,...p],env:h,cwd:y}}try{return await a.connection.request("authenticate",{methodId:s})}catch(f){throw As(f,a)}}function Eh(t){return e=>{let n={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(n.receivedBytes=e.receivedBytes),"totalBytes"in e&&(n.totalBytes=e.totalBytes),"packageSpec"in e&&(n.packageSpec=e.packageSpec),t.notify(Oa,n).catch(()=>{})}}function Kl(t){let e=t.availableModes();if(e.length===0)return;let n=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:t.currentMode??e[0].id,availableModes:n}}function Vl(t){let e=t.availableModels();if(e.length===0)return;let n=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:t.currentModel??e[0].modelId,availableModels:n}}function HI(t,e){if(!t||typeof t!="object")return{kind:"error",code:W.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let n=t;if(typeof n.sessionId!="string")return{kind:"error",code:W.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof n.modelId!="string")return{kind:"error",code:W.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${n.sessionId}`};let s=e.get(n.sessionId);if(!s)return{kind:"error",code:W.SessionNotFound,message:`session ${n.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${n.sessionId}`};let r=s.availableModels(),i=di(n.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:n.modelId,logMessage:`session/set_model accepted sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(c=>c.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:n.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${n.sessionId} requested=${JSON.stringify(n.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:W.InvalidParams,message:`model "${n.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${n.sessionId} modelId=${JSON.stringify(n.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function UI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw fe(W.InvalidParams,"transformer/attach requires sessionId");if(!n.transformers)throw fe(W.InternalError,"transformer manager not configured");let i=n.transformers.resolveChain([e])[0];if(!i)throw fe(W.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return zt(n.manager,r).addTransformer(i),{ok:!0}}async function jI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw fe(W.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!i)throw fe(W.InvalidParams,"hydra-acp/attention/set requires string reason");return zt(n.manager,r).setAttentionFlag(e,i,s.payload),{ok:!0}}async function qI(t,e,n){let s=t??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,i=typeof s.reason=="string"?s.reason:void 0;if(!r)throw fe(W.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!i)throw fe(W.InvalidParams,"hydra-acp/attention/clear requires string reason");return zt(n.manager,r).clearAttentionFlag(e,i),{ok:!0}}function WI(t){let e={sessionId:t.hydraSessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,originatingClient:t.originatingClient,interactive:t.interactive,updatedAt:t.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},n={currentMode:t.currentMode,agentArgs:t.agentArgs,availableCommands:t.agentCommands,availableModes:t.agentModes,availableModels:t.agentModels};return{[ht]:_a(e,n)}}function Yl(t,e,n={}){let s=t.liveListEntry(e),r={clientId:n.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...n.resurrected===!0?{resurrected:!0}:{}};return go(e.agentMeta,_a(s,r))}function zI(){return{protocolVersion:1,agentInfo:{name:"hydra",version:pe},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:go(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function JI(t,e){if(!(!e.transformers||!e.manager))for(let n of e.manager.defaultTransformers){let s=e.transformers.resolveChain([n])[0];s&&t.addTransformer(s)}}function vd(t,e,n,s,r){return{clientId:r??`cli_${Ql(8)}`,connection:t,clientInfo:s}}var Sd=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let n,s,r=new Promise((o,a)=>{n=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,n(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,n){let{complete:s}=this.reserve(e);s(n)}lookup(e){return this.byToken.get(e)}addDisposer(e,n){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(n)}async unbind(e){let n=this.byToken.get(e);if(n!==void 0){this.byToken.delete(e);for(let s of n.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as KI}from"crypto";import{McpServer as VI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as YI}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as gt}from"zod";function*Gl(t){for(let e=0;e<t.length;e++){let n=t[e];if(!n)continue;let s=n;if(s.method!=="session/update")continue;let i=s.params?.update;!i||typeof i.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:i.sessionUpdate,update:i})}}function Jt(t){return{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}var $h="Bearer ";function xi(t){let e=t.headers.authorization;if(typeof e!="string"||!e.startsWith($h))return;let n=e.slice($h.length).trim();return n.length>0?n:void 0}function QI(t){let e=new VI({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:gt.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:n})=>{let s=t.streamTail(n);return Jt(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:gt.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:n})=>{let s=t.streamHead(n);return Jt(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:gt.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:gt.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:gt.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:n,max_bytes:s,wait_ms:r})=>{let i=await t.streamRead(n,s,r);return Jt(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:gt.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:gt.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:n,timeout_ms:s})=>{let r=await t.streamWaitFor(n,s),i=t.streamInfo();return Jt({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:gt.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:gt.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:gt.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:gt.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:gt.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:gt.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:gt.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:gt.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:gt.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async n=>{let s={pattern:n.pattern};n.regex!==void 0&&(s.regex=n.regex),n.case_insensitive!==void 0&&(s.caseInsensitive=n.case_insensitive),n.invert!==void 0&&(s.invert=n.invert),n.max_matches!==void 0&&(s.maxMatches=n.max_matches),n.max_bytes!==void 0&&(s.maxBytes=n.max_bytes),n.context_before!==void 0&&(s.contextBefore=n.context_before),n.context_after!==void 0&&(s.contextAfter=n.context_after),n.cursor!==void 0&&(s.cursor=n.cursor);let r=t.streamGrep(s);return Jt(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let n=t.streamInfo();return Jt(n)}),e}var GI=1e4;function Fh(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=QI(a),l=new YI({sessionIdGenerator:()=>KI()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=xi(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(h=>{f=setTimeout(()=>h(void 0),GI)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}l=m}let u=await s(c,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}Ua();import{randomUUID as XI}from"crypto";import{McpServer as ZI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as ex}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Ms}from"zod";function tx(t){switch(t){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function nx(t,e){if(t.length<=148)return t;let r=Math.floor(148/2),i=e-r;i<0&&(i=0);let o=i+148;o>t.length&&(i=t.length-148,i<0&&(i=0));let a=t.slice(i,o);return i>0&&(a="\u2026"+a),o<t.length&&(a=a+"\u2026"),a}function sx(t){let e=new ZI({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `recall_search` to find entries by keyword, `recall_range` to pull a contiguous slice verbatim, and `recall_tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("recall_search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via recall_range. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:Ms.string().min(1).describe("Case-insensitive substring to search for."),limit:Ms.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:Ms.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:n,limit:s=10,include_tool_calls:r=!0})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Jt({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. recall_search retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let o=await i.getHistorySnapshot(),a=[];for(let{entryId:d,entry:l,kind:u}of Gl(o)){if(u==="tool_call"&&!r)continue;let f=ci([l]),p=f.toLowerCase().indexOf(n.toLowerCase());if(p<0)continue;let m=tx(u),h=nx(f,p),y=typeof l.recordedAt=="number"?String(l.recordedAt):void 0;if(a.push({entryId:d,speaker:m,snippet:h,timestamp:y}),a.length>=s)break}let c=a.length>=s&&a.length<o.length;return Jt({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("recall_range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after recall_search narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:Ms.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:Ms.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:n,to_entry:s})=>{let r=await t();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return Jt({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. recall_range retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<n)throw new Error(`recall_range: to_entry (${s}) must be >= from_entry (${n})`);let i=s-n+1;if(i>50)throw new Error(`recall_range: range size (${i}) exceeds maximum of 50 entries`);let o=await r.getHistorySnapshot(),a=Math.min(n,o.length-1),c=Math.min(s,o.length-1),d=a>n||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:d}};let l=o.slice(a,c+1),u=ci(l);return{content:[{type:"text",text:u}],structuredContent:{text:u,entry_count:l.length,truncated:d}}}),e.registerTool("recall_tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:Ms.string().optional(),file_path:Ms.string().optional(),limit:Ms.number().int().min(1).max(100).optional()}},async({tool_name:n,file_path:s,limit:r=20})=>{let i=await t();if(!i.summarizedThroughEntry||i.summarizedThroughEntry===0)return Jt({calls:[],truncated:!1,note:"This session has no compacted history. recall_tool_calls retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let o=typeof n=="string"&&n.length>0,a=typeof s=="string"&&s.length>0;if(!o&&!a)throw new Error("recall_tool_calls: at least one of tool_name or file_path must be provided");let c=await i.getHistorySnapshot(),d=[];for(let{entryId:u,entry:f,kind:p,update:m}of Gl(c)){if(p!=="tool_call")continue;let h;if(typeof m.name=="string"&&m.name.length>0?h=m.name:typeof m.title=="string"&&m.title.length>0?h=m.title:h="(unnamed)",n!==void 0&&h.toLowerCase()!==n.toLowerCase())continue;let y=m.rawInput,b={};if(y&&typeof y=="object"&&!Array.isArray(y))for(let[x,T]of Object.entries(y))typeof T=="string"?b[x]=T.length>500?T.slice(0,497)+"\u2026":T:(typeof T=="number"||typeof T=="boolean")&&(b[x]=T);if(a&&y&&typeof y=="object"&&!Array.isArray(y)){let x=s.toLowerCase(),T=["file_path","path"],_=!1;for(let F of T){let j=y[F];if(typeof j=="string"&&j.toLowerCase()===x){_=!0;break}}if(!_)continue}let v="in_progress";typeof m.status=="string"&&(v=m.status);let S=typeof f.recordedAt=="number"?String(f.recordedAt):void 0;if(d.push({entryId:u,tool:h,args:b,status:v,timestamp:S}),d.length>=r)break}let l=d.length>=r;return Jt({calls:d,truncated:l})}),e}var rx=1e4;function Oh(t,e){let n=new Map;async function s(o,a){let c=n.get(o);if(c!==void 0)return c.transport;let d=sx(a),l=new ex({sessionIdGenerator:()=>XI()});await d.connect(l);let u={server:d,transport:l};return n.set(o,u),e.addDisposer(o,async()=>{n.delete(o);try{await l.close()}catch{}try{await d.close()}catch{}}),l}async function r(o,a){let c=xi(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(h=>{f=setTimeout(()=>h(void 0),rx)}),m=await Promise.race([d.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};t.post("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.get("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)}),t.delete("/mcp/hydra-acp-recall",i,async(o,a)=>{await r(o,a)})}var kd=class{byName=new Map;changeHandlers=[];register(e,n,s,r){this.byName.set(e,{connection:n,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let n=this.changeHandlers.indexOf(e);n>=0&&this.changeHandlers.splice(n,1)}}fireChanged(e,n){for(let s of this.changeHandlers)try{s(e,n)}catch{}}};import{StreamableHTTPServerTransport as fx}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as px}from"crypto";import{Server as ix}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as ox,ListToolsRequestSchema as ax}from"@modelcontextprotocol/sdk/types.js";function Lh(t,e,n){let s=typeof n=="function"?async()=>n():async()=>n,r=new ix({name:t,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=new Map(e.tools.map(o=>[o.name,o]));return r.setRequestHandler(ax,async()=>({tools:e.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema,...o.outputSchema!==void 0?{outputSchema:o.outputSchema}:{}}))})),r.setRequestHandler(ox,async(o,a)=>{let c=o.params.name;if(!i.has(c))return Id(`unknown tool: ${c}`);let d=a._meta?.progressToken??a.requestId,l=cx(d,a.sendNotification);try{let u=await s(),f=await lx(e.connection,t,c,o.params.arguments??{},u);return ux(f,c)}catch(u){return Id(u instanceof Error?u.message:String(u))}finally{l()}}),r}var dx=15e3;function cx(t,e,n=dx){if(t===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:t,progress:s}}).catch(()=>{})},n);return r.unref?.(),()=>clearInterval(r)}async function lx(t,e,n,s,r){return await t.request("hydra-acp/mcp_tools/invoke",{server:e,tool:n,args:s,sessionId:r})}function ux(t,e){if(t===null||typeof t!="object")return Id(`extension ${e} returned non-object`);let n=t;return Array.isArray(n.content)?n:Id(`extension ${e} omitted content array`)}function Id(t){return{content:[{type:"text",text:t}],isError:!0}}var mx=1e4;function Bh(t,e,n){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function i(d){for(let l of s.values()){let u=l.get(d);u!==void 0&&(l.delete(d),r(u))}}n.onChange(d=>{i(d)});async function o(d,l){let u=s.get(d);u===void 0&&(u=new Map,s.set(d,u),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let v of b.values())await r(v)}}));let f=u.get(l);if(f!==void 0)return f.transport;let p=n.lookup(l);if(p===void 0)return;let h=Lh(l,p,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let v,S=new Promise(T=>{v=setTimeout(()=>T(void 0),mx)}),x=await Promise.race([b.sessionReady.catch(()=>{}),S]);if(v!==void 0&&clearTimeout(v),x===void 0)throw new Error("session not ready");return x.sessionId}),y=new fx({sessionIdGenerator:()=>px()});return await h.connect(y),u.set(l,{server:h,transport:y}),y}async function a(d,l){let u=xi(d);if(u===void 0){l.code(401).send({error:"missing bearer token"});return}if(e.lookup(u)===void 0){l.code(404).send({error:"unknown mcp token"});return}let p=d.params.name,m=await o(u,p);if(m===void 0){l.code(404).send({error:`unknown mcp server: ${p}`});return}l.hijack(),await m.handleRequest(d.raw,l.raw,d.body)}let c={config:{skipAuth:!0}};t.post("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.get("/mcp/:name",c,async(d,l)=>{await a(d,l)}),t.delete("/mcp/:name",c,async(d,l)=>{await a(d,l)})}async function jh(t,e){vx(t);let n=t.daemon.tls?await Ci.readFile(Je(t.daemon.tls.key)):void 0,s=t.daemon.tls?await Ci.readFile(Je(t.daemon.tls.cert)):void 0;await Ci.mkdir($.home(),{recursive:!0});let{stream:r,fileStream:i}=await wx(t.daemon.logLevel),o=hx({logger:{level:t.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await o.register(gx,{options:{handleProtocols:tp}}),jc(Z=>{o.log.info(Z)}),zc(Z=>{o.log.info(Z)});let a=await id.load(),c=new ld,d=new cd,l=new dd([new od(e),new ad(a),d]),u=Vm({validator:l});o.addHook("onRequest",async(Z,Oe)=>{Z.routeOptions.config?.skipAuth||Z.url==="/acp"||Z.url?.startsWith("/acp?")||await u(Z,Oe)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{c.sweepExpired()},300*1e3);p.unref();let m=new Ea(t,{onFetched:()=>{Dm(m,v)}});Ol(Z=>o.log.info(Z));let h={info:Z=>o.log.info(Z),warn:Z=>o.log.warn(Z)},y=Z=>Cs.spawn({...Z,stderrTailBytes:t.daemon.agentStderrTailBytes,logger:h});ip(t.compressToolContent);let b=new sd,v=new Ga(m,y,void 0,{idleTimeoutMs:t.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:t.defaultModels,synopsisAgent:t.synopsisAgent,synopsisModel:t.synopsisModel,compactionAgent:t.compaction?.agent,compactionModel:t.compaction?.model,defaultTransformers:t.defaultTransformers,sessionHistoryMaxEntries:t.daemon.sessionHistoryMaxEntries,logger:h,npmRegistry:t.npmRegistry,extensionCommands:b,defaultCwd:t.defaultCwd}),S=new td(Ef(t),void 0,{tokenRegistry:d}),x=new nd(Pf(t),void 0,{tokenRegistry:d});yh(o,pe,Ts(t));let T=new Sd,_=new kd,F,j=()=>{if(F!==void 0)return F;let Z=o.server.address();return F=`http://127.0.0.1:${Z&&typeof Z=="object"?Z.port:t.daemon.port}`,F};hh(o,v,{agentId:t.defaultAgent,cwd:t.defaultCwd,publicHost:t.daemon.publicHost,host:t.daemon.host,port:t.daemon.port,compaction:t.compaction},{extensionMcp:_,mcpTokenRegistry:T,getDaemonOrigin:j}),gh(o,m,v,{npmRegistry:t.npmRegistry}),wh(o,S),bh(o,x),vh(o,{defaultAgent:t.defaultAgent,defaultCwd:t.defaultCwd,defaultModels:{...t.defaultModels},...t.synopsisAgent!==void 0?{synopsisAgent:t.synopsisAgent}:{},...t.synopsisModel!==void 0?{synopsisModel:t.synopsisModel}:{},defaultTransformers:[...t.defaultTransformers]}),Th(o,{store:a,rateLimiter:c}),Fh(o,T),Oh(o,T),Bh(o,T,_),_h(o,{validator:l,manager:v,defaultAgent:t.defaultAgent,processRegistry:d,onExtensionVersion:(Z,Oe)=>S.reportVersion(Z,Oe),onTransformerVersion:(Z,Oe)=>x.reportVersion(Z,Oe),transformers:x,extensionCommands:b,mcpTokenRegistry:T,extensionMcp:_,getDaemonOrigin:j,registry:m});let J=!!t.daemon.tls;await o.listen({host:J?"127.0.0.1":t.daemon.host,port:J?0:t.daemon.port});let D=o.server.address(),L=D&&typeof D=="object"?D.port:t.daemon.port,U,Q=t.daemon.host,V=L;if(J&&n&&s){U=bx({listenHost:t.daemon.host,listenPort:t.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:L,tlsOptions:{key:n,cert:s},logger:o.log});let Z=U.address();Z&&typeof Z=="object"&&(V=Z.port)}await Ci.mkdir($.home(),{recursive:!0}),await Nf({pid:process.pid,host:Q,port:V,loopbackPort:L,startedAt:new Date().toISOString()});let be={daemonUrl:`http://127.0.0.1:${L}`,daemonHost:"127.0.0.1",daemonPort:L,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${L}/acp`,hydraHome:$.home()};S.setContext(be),x.setContext(be),await S.start(),await x.start();try{await v.reconcilePermissionFlags()}catch(Z){o.log.warn(`permission flag reconcile failed: ${Z.message}`)}v.resurrectPendingQueues().catch(Z=>{o.log.warn(`queue replay scan failed: ${Z.message}`)}),v.resumePendingCompactions().catch(Z=>{o.log.warn(`compaction resume scan failed: ${Z.message}`)});let Y=t.daemon.agentSyncIntervalMinutes*60*1e3,ye=Y>0?Hm({registry:m,manager:v,intervalMs:Y,logger:h}):void 0,Qe=t.daemon.sessionGcIntervalMinutes*60*1e3,qs=t.daemon.sessionGcMaxAgeDays*24*60*60*1e3,At=Qe>0?Um({manager:v,intervalMs:Qe,maxAgeMs:qs,logger:h}):void 0;return{app:o,manager:v,registry:m,extensions:S,transformers:x,mcpTokenRegistry:T,extensionMcp:_,processRegistry:d,shutdown:async()=>{At&&At(),ye&&ye(),clearInterval(f),clearInterval(p);let Z=async(Oe,wn)=>{try{await wn()}catch(Te){o.log.warn(`shutdown step ${Oe} failed: ${Te instanceof Error?Te.message:String(Te)}`)}};await Z("sessionTokenStore.flush",()=>a.flush()),await Z("extensions.stop",()=>S.stop()),await Z("transformers.stop",()=>x.stop()),await Z("manager.closeAll",()=>v.closeAll()),await Z("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await Z("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await Z("manager.flushMetaWrites",()=>v.flushMetaWrites()),await Z("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),jc(null),zc(null),Ol(null),U&&await Z("tlsTerminator.close",()=>new Promise(Oe=>U.close(()=>Oe()))),await Z("app.close",()=>o.close());try{Dh.unlinkSync($.pidFile())}catch{}await Z("fileStream.flushSync",()=>i.flushSync())}}}async function wx(t){let e=await yx({file:$.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),n=Nh.destination(2);return{stream:Nh.multistream([{stream:e,level:t},{stream:n,level:t}]),fileStream:e}}function bx(t){let e=Uh.createServer(t.tlsOptions,n=>{let s=Hh.connect({host:t.upstreamHost,port:t.upstreamPort}),r=!1,i=o=>{if(!r){r=!0,o&&t.logger.warn(`tls terminator forwarder error: ${o.message??String(o)}`);try{n.destroy()}catch{}try{s.destroy()}catch{}}};n.on("error",i),s.on("error",i),n.on("close",()=>i()),s.on("close",()=>i()),n.pipe(s),s.pipe(n)});return e.on("tlsClientError",n=>{t.logger.warn(`tls handshake error: ${n.message}`)}),e.listen({host:t.listenHost,port:t.listenPort}),e}function vx(t){let e=t.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!t.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}Sr();Wt();Fo();import*as Wh from"fs";import*as Ai from"fs/promises";async function Ri(t,e,n){let s=Cx(e),r;try{r=await Ai.stat(t)}catch(c){if(c.code==="ENOENT"){process.stderr.write(`${n} (${t})
265
+ `),process.exit(1);return}throw c}let i=await xx(t,r.size,s.tail);if(!s.follow)return;process.stdout.write(`-- following ${t} --
266
+ `);let o=!1,a=Wh.watch(t,()=>{o||(o=!0,setImmediate(async()=>{o=!1;try{let c=await Ai.stat(t);if(c.size<=i){c.size<i&&(i=c.size);return}let d=await Ai.open(t,"r");try{let l=Buffer.alloc(c.size-i);await d.read(l,0,l.length,i),process.stdout.write(l),i=c.size}finally{await d.close()}}catch{}}))});await new Promise(c=>{let d=()=>{a.close(),c()};process.once("SIGINT",d),process.once("SIGTERM",d)})}async function xx(t,e,n){if(n<=0||e===0)return e;let s=64*1024,r=await Ai.open(t,"r");try{let i=e,o="",a=0;for(;i>0&&a<=n;){let l=Math.min(s,i);i-=l;let u=Buffer.alloc(l);await r.read(u,0,l,i),o=u.toString("utf8")+o,a=(o.match(/\n/g)??[]).length}let d=o.split(`
267
267
  `).slice(-n-1);process.stdout.write(d.join(`
268
268
  `)),o.endsWith(`
269
269
  `)||process.stdout.write(`
270
- `)}finally{await r.close()}return e}function md(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function sx(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
270
+ `)}finally{await r.close()}return e}function Rd(t){let e=new Set(["--tail","-n"]),n,s=[],r=0;for(;r<t.length;){let i=t[r];if(i===void 0)break;if(i.startsWith("-")){if(s.push(i),e.has(i)&&r+1<t.length){let o=t[r+1];o!==void 0&&s.push(o),r+=2;continue}r+=1;continue}if(n===void 0){n=i,r+=1;continue}s.push(i),r+=1}return{name:n,rest:s}}function Cx(t){let e=50,n=!1,s=0;for(;s<t.length;){let r=t[s];if(r==="--tail"||r==="-n"){let i=t[s+1],o=Number.parseInt(i??"",10);(!Number.isInteger(o)||o<0)&&(process.stderr.write(`Invalid --tail value: ${i}
271
271
  `),process.exit(2)),e=o,s+=2;continue}if(r==="--follow"||r==="-f"){n=!0,s+=1;continue}return process.stderr.write(`Unknown flag: ${r}
272
- `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function Mh(t={}){let e=await ye(),n=await Xi();if(await ud(e)){let r=await yi();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
273
- `);return}if(Br(t,"foreground")){process.title="hydra-daemon";let r=await Rh(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
272
+ `),process.exit(2),{tail:50,follow:!1}}return{tail:e,follow:n}}async function Jh(t={}){let e=await we(),n=await co();if(await xd(e)){let r=await Ti();process.stdout.write(`Daemon already running${r?` (pid ${r.pid})`:""}. Run \`hydra-acp daemon restart\` to restart it.
273
+ `);return}if(Vr(t,"foreground")){process.title="hydra-daemon";let r=await jh(e,n);process.stdout.write(`hydra-acp daemon listening on ${e.daemon.host}:${e.daemon.port}
274
274
  `);let i=1e4,o=!1,a=async()=>{o&&(process.stderr.write(`Second signal received; exiting immediately.
275
275
  `),process.exit(1)),o=!0,process.stdout.write(`Shutting down...
276
276
  `);let c=setTimeout(()=>{process.stderr.write(`Graceful shutdown did not complete within ${i}ms; forcing exit.
277
277
  `),process.exit(1)},i);c.unref();try{await r.shutdown()}catch(d){process.stderr.write(`shutdown failed: ${d instanceof Error?d.message:String(d)}
278
- `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}fd(),await pd(e);let s=await yi();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
279
- `)}async function _h(){let t=await yi();if(!t){process.stdout.write(`No running daemon found.
278
+ `)}clearTimeout(c),process.exit(0)};process.on("SIGINT",()=>{a()}),process.on("SIGTERM",()=>{a()}),process.on("SIGHUP",()=>{});return}Cd(),await Ad(e);let s=await Ti();process.stdout.write(`Daemon started on ${e.daemon.host}:${e.daemon.port}`+(s?` pid=${s.pid}`:"")+`
279
+ `)}async function Kh(){let t=await Ti();if(!t){process.stdout.write(`No running daemon found.
280
280
  `);return}try{process.kill(t.pid,"SIGTERM"),process.stdout.write(`Sent SIGTERM to daemon pid ${t.pid}
281
281
  `)}catch(e){process.stderr.write(`Failed to signal daemon: ${e.message}
282
- `)}}async function $h(){let t=await ye();await Xi();let e=await yi();if(e&&dn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
282
+ `)}}async function Vh(){let t=await we();await co();let e=await Ti();if(e&&mn(e.pid)){process.stdout.write(`Stopping daemon pid ${e.pid}...
283
283
  `);try{process.kill(e.pid,"SIGTERM")}catch(n){process.stderr.write(`Failed to signal daemon: ${n.message}
284
- `),process.exit(1)}await ix(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
284
+ `),process.exit(1)}await Rx(e.pid)||(process.stderr.write(`Daemon pid ${e.pid} did not exit after SIGTERM; aborting restart.
285
285
  `),process.exit(1))}else process.stdout.write(`No running daemon found; starting a fresh one.
286
- `);if(fd(),await pd(t),await ud(t)){let n=await yi();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
287
- `)}}async function ix(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!dn(t))return!0;await rx(50)}return!1}async function Oh(t){await gi(_.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Fh(){let t=await yi();if(!t){process.stdout.write(`Daemon: not running
288
- `),process.stdout.write(`CLI version: ${fe}
289
- `);return}let e=dn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
290
- `);let n,s;if(e)try{let o=await ye();n=await cr(o),s=gs(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${fe}
286
+ `);if(Cd(),await Ad(t),await xd(t)){let n=await Ti();process.stdout.write(`Daemon restarted on ${t.daemon.host}:${t.daemon.port}`+(n?` pid=${n.pid}`:"")+`
287
+ `)}}async function Rx(t,e=5e3){let n=Date.now()+e;for(;Date.now()<n;){if(!mn(t))return!0;await Ax(50)}return!1}async function Yh(t){await Ri($.currentLogFile(),t,"No daemon log file (daemon never ran?)")}async function Qh(){let t=await Ti();if(!t){process.stdout.write(`Daemon: not running
288
+ `),process.stdout.write(`CLI version: ${pe}
289
+ `);return}let e=mn(t.pid);process.stdout.write(`Daemon: ${e?"running":"stale pid file"} pid=${t.pid} host=${t.host} port=${t.port} started=${t.startedAt}
290
+ `);let n,s;if(e)try{let o=await we();n=await vr(o),s=Ts(o)}catch{}if(!n||n.version===void 0){process.stdout.write(`CLI version: ${pe}
291
291
  `),e&&process.stdout.write(`Daemon version: unknown (health endpoint unreachable)
292
- `);return}let r=n.version===fe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${fe}
293
- `);return}process.stdout.write(`CLI version: ${fe}
292
+ `);return}let r=n.version===pe,i=n.configDigest!==void 0&&s!==void 0&&n.configDigest===s;if(r&&i){process.stdout.write(`Version: ${pe}
293
+ `);return}process.stdout.write(`CLI version: ${pe}
294
294
  `),process.stdout.write(`Daemon version: ${n.version}
295
- `),r||process.stdout.write(Ph.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(Ph.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function yi(){return zn()}Ne();qn();Ss();tr();eo();xn();Po();or();import*as Kt from"fs/promises";import*as Yh from"os";import*as Yt from"path";Sd();async function Vh(t={}){let e=await ye(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Ee(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(w=>!w.importedFromMachine||!!w.upstreamSessionId):i.filter(w=>w.importedFromMachine===o&&!w.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
295
+ `),r||process.stdout.write(zh.yellow("Version mismatch \u2014 run `hydra-acp daemon restart` to upgrade the daemon.\n")),r&&!i&&process.stdout.write(zh.yellow("Config changed since daemon started \u2014 run `hydra-acp daemon restart` to apply.\n"))}async function Ti(){return Zn()}je();Gn();$s();ur();uo();En();Ho();yr();import*as en from"fs/promises";import*as cg from"os";import*as tn from"path";Fd();async function lg(t={}){let e=await we(),n=t.includeNonInteractive||t.all?"?includeNonInteractive=true":"",r=(await Fe(`/v1/sessions${n}`,{expectStatus:200})).body,i=r.sessions,o=t.host??"local",a=o==="all"?i:o==="local"?i.filter(y=>!y.importedFromMachine||!!y.upstreamSessionId):i.filter(y=>y.importedFromMachine===o&&!y.upstreamSessionId);if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
296
296
  `);return}if(a.length===0){if(o==="local"&&r.sessions.length>0){process.stdout.write(`No local sessions. Use --host=all to include imported sessions.
297
297
  `);return}if(o!=="local"&&o!=="all"){process.stdout.write(`No sessions from ${o}.
298
298
  `);return}process.stdout.write(`No active sessions.
299
- `);return}let c=a.slice().sort((w,b)=>{let v=(b.status==="live"?1:0)-(w.status==="live"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(w.updatedAt||""))}),d=c,l=0;if(!t.all){let w=c.filter(x=>x.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(w,w+b),S=c.length-w-v.length;d=[...c.slice(0,w),...v],l=S}let f=Date.now(),u=d.map(w=>Ii(w,f)),p={columns:t.columns??e.tui.sessionColumns??Si,cwdMaxWidth:e.tui.cwdColumnMaxWidth},m=xi(u,p),h=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ks(ki,m,h,p)+`
300
- `);for(let w of u)process.stdout.write(ks(w,m,h,p)+`
299
+ `);return}let c=a.slice().sort((y,b)=>{let v=(b.status==="live"?1:0)-(y.status==="live"?1:0);return v!==0?v:String(b.updatedAt||"").localeCompare(String(y.updatedAt||""))}),d=c,l=0;if(!t.all){let y=c.filter(x=>x.status!=="cold").length,b=e.sessionListColdLimit,v=c.slice(y,y+b),S=c.length-y-v.length;d=[...c.slice(0,y),...v],l=S}let u=Date.now(),f=d.map(y=>Fi(y,u)),p={columns:t.columns??e.tui.sessionColumns??_i,cwdMaxWidth:e.tui.cwdColumnMaxWidth},m=Oi(f,p),h=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Fs($i,m,h,p)+`
300
+ `);for(let y of f)process.stdout.write(Fs(y,m,h,p)+`
301
301
  `);l>0&&process.stdout.write(`
302
302
  ... ${l} more cold session${l===1?"":"s"} hidden. Use --all to show.
303
- `)}async function Gh(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
304
- `),process.exit(2));let e=await Ee(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
303
+ `)}async function ug(t){t||(process.stderr.write(`Usage: hydra-acp sessions kill <session-id>
304
+ `),process.exit(2));let e=await Fe(`/v1/sessions/${t}/kill`,{method:"POST"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
305
305
  `),process.exit(1)),process.stdout.write(`Killed ${t}
306
- `)}async function Qh(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
307
- `),process.exit(2));let e=await Ee(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
306
+ `)}async function fg(t){t||(process.stderr.write(`Usage: hydra-acp sessions remove <session-id>
307
+ `),process.exit(2));let e=await Fe(`/v1/sessions/${t}`,{method:"DELETE"});!e.ok&&e.status!==204&&(process.stderr.write(`Daemon returned HTTP ${e.status}
308
308
  `),process.exit(1)),process.stdout.write(`Removed ${t}
309
- `)}async function Xh(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Ee("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
309
+ `)}async function pg(t){let e=t.maxAgeDays!==void 0?t.maxAgeDays:0,n={maxAgeDays:e};t.limit!==void 0&&(n.limit=t.limit),n.selection=t.keepUndecided?"explicit":"unpromoted";let r=(await Fe("/v1/sessions/collect",{method:"POST",body:n,expectStatus:200})).body;if(t.json){process.stdout.write(`${JSON.stringify(r,null,2)}
310
310
  `);return}let i=t.keepUndecided?"non-interactive":"unpromoted (cat one-shots + editor ghosts)";if(r.considered===0){let a=e>0?` older than ${e}d`:"";process.stdout.write(`No ${i} sessions${a} found.
311
- `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${bi(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
311
+ `);return}let o=r.oldestLastUsedMs!==void 0?` (oldest: ${Pi(r.oldestLastUsedMs)})`:"";process.stdout.write(`Collected ${r.deleted} of ${r.considered} ${i} session(s)${o}.
312
312
  `),r.failed>0&&process.stdout.write(` ${r.failed} failed (see daemon log).
313
313
  `),r.deferred>0&&process.stdout.write(` ${r.deferred} deferred \u2014 re-run \`hydra sessions collect\` to drain.
314
- `)}async function Zh(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
315
- `),process.exit(2));let s=await Gs(),r=await wi(),i=n==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
314
+ `)}async function mg(t,e,n){t||(process.stderr.write(`Usage: hydra-acp sessions export <session-id> [--out <file>] [--tools inline|summary]
315
+ `),process.exit(2));let s=await or(),r=await Ei(),i=n==="summary"?"?tools=summary":"",o=await fetch(`${r}/v1/sessions/${encodeURIComponent(t)}/export${i}`,{headers:{Authorization:`Bearer ${s}`}});if(!o.ok){let d=await o.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${o.status}: ${d}
316
316
  `),process.exit(1)}let a=await o.text();if(!e){process.stdout.write(a),a.endsWith(`
317
317
  `)||process.stdout.write(`
318
- `);return}let c=e==="."?Ix(o,t):e;await Kt.mkdir(Yt.dirname(Yt.resolve(c)),{recursive:!0}),await Kt.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
319
- `)}async function eg(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
320
- `),process.exit(2));let n,s,r=await wx(t);if(r!==null){let o=bx(r.raw);n=td(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${Yt.basename(t,Yt.extname(t))}-${a}.md`}else{let o=await Gs(),a=await wi(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
318
+ `);return}let c=e==="."?zx(o,t):e;await en.mkdir(tn.dirname(tn.resolve(c)),{recursive:!0}),await en.writeFile(c,a,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${c}
319
+ `)}async function hg(t,e){t||(process.stderr.write(`Usage: hydra-acp sessions transcript <session-id>|<file> [--out <file>|.]
320
+ `),process.exit(2));let n,s,r=await Hx(t);if(r!==null){let o=Ux(r.raw);n=md(o);let a=new Date().toISOString().replace(/[:.]/g,"-");s=`${tn.basename(t,tn.extname(t))}-${a}.md`}else{let o=await or(),a=await Ei(),c=await fetch(`${a}/v1/sessions/${encodeURIComponent(t)}/transcript`,{headers:{Authorization:`Bearer ${o}`}});if(!c.ok){let l=await c.text().catch(()=>"");process.stderr.write(`Daemon returned HTTP ${c.status}: ${l}
321
321
  `),process.exit(1)}n=await c.text();let d=new Date().toISOString().replace(/[:.]/g,"-");s=`hydra-${t}-${d}.md`}if(!e){process.stdout.write(n),n.endsWith(`
322
322
  `)||process.stdout.write(`
323
- `);return}let i=e==="."?s:e;await Kt.mkdir(Yt.dirname(Yt.resolve(i)),{recursive:!0}),await Kt.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
324
- `)}async function wx(t){try{if(!(await Kt.stat(t)).isFile())return null}catch{return null}let e=await Kt.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
325
- `),process.exit(1)}}function bx(t){try{return ln(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
326
- `),process.exit(1)}}async function tg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
327
- `),process.exit(2));let n;if(e.cwd!==void 0){let a=Yt.resolve(e.cwd);try{(await Kt.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
323
+ `);return}let i=e==="."?s:e;await en.mkdir(tn.dirname(tn.resolve(i)),{recursive:!0}),await en.writeFile(i,n,{encoding:"utf8",mode:384}),process.stdout.write(`Wrote ${i}
324
+ `)}async function Hx(t){try{if(!(await en.stat(t)).isFile())return null}catch{return null}let e=await en.readFile(t,"utf8");try{return{raw:JSON.parse(e)}}catch(n){process.stderr.write(`Failed to parse bundle file: ${n.message}
325
+ `),process.exit(1)}}function Ux(t){try{return gn(t)}catch(e){process.stderr.write(`Not a valid bundle: ${e.message}
326
+ `),process.exit(1)}}async function gg(t,e={}){t||(process.stderr.write(`Usage: hydra-acp sessions import <file>|- [--replace] [--cwd <path>] [--info]
327
+ `),process.exit(2));let n;if(e.cwd!==void 0){let a=tn.resolve(e.cwd);try{(await en.stat(a)).isDirectory()||(process.stderr.write(`--cwd ${a} is not a directory
328
328
  `),process.exit(1))}catch{process.stderr.write(`--cwd ${a} does not exist
329
- `),process.exit(1)}n=a}let s;t==="-"?s=await kx():s=await Kt.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
330
- `),process.exit(1)}if(e.info===!0){let a=await ye();Sx(r,a.tui.cwdColumnMaxWidth);return}let i=await Ee("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
329
+ `),process.exit(1)}n=a}let s;t==="-"?s=await Wx():s=await en.readFile(t,"utf8");let r;try{r=JSON.parse(s)}catch(a){process.stderr.write(`Failed to parse bundle: ${a.message}
330
+ `),process.exit(1)}if(e.info===!0){let a=await we();qx(r,a.tui.cwdColumnMaxWidth);return}let i=await Fe("/v1/sessions/import",{method:"POST",body:{bundle:r,replace:e.replace===!0,...n!==void 0?{cwd:n}:{}}});if(i.status===409){let a=i.body??{};process.stderr.write(`Bundle already imported as ${a.existingSessionId??"unknown"}. Use --replace to overwrite.
331
331
  `),process.exit(1)}i.ok||(process.stderr.write(`Daemon returned HTTP ${i.status}
332
332
  `),process.exit(1));let o=i.body;process.stdout.write(o.replaced?`Replaced ${o.sessionId} (from ${o.importedFromSessionId})
333
333
  `:`Imported as ${o.sessionId} (from ${o.importedFromSessionId})
334
- `)}function vx(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold",compactionState:t.session.compactionState}}function Sx(t,e){let n;try{n=ln(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
335
- `),process.exit(1)}let s=vx(n),r=Ii(s),i={columns:vd,cwdMaxWidth:e},o=xi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(ks(ki,o,a,i)+`
336
- `),process.stdout.write(ks(r,o,a,i)+`
334
+ `)}function jx(t){return{sessionId:t.session.sessionId,cwd:t.session.cwd,agentId:t.session.agentId,currentUsage:t.session.currentUsage,title:t.session.title,importedFromMachine:t.exportedFrom.machine,attachedClients:0,updatedAt:t.session.updatedAt,status:"cold",compactionState:t.session.compactionState}}function qx(t,e){let n;try{n=gn(t)}catch(d){process.stderr.write(`Not a valid bundle: ${d.message}
335
+ `),process.exit(1)}let s=jx(n),r=Fi(s),i={columns:$d,cwdMaxWidth:e},o=Oi([r],i),a=process.stdout.isTTY?process.stdout.columns:void 0;process.stdout.write(Fs($i,o,a,i)+`
336
+ `),process.stdout.write(Fs(r,o,a,i)+`
337
337
  `);let c=n.session.upstreamSessionId??"-";process.stdout.write(`
338
338
  lineage: ${n.session.lineageId}
339
339
  exported: ${n.exportedAt} from ${n.exportedFrom.machine} (hydra ${n.exportedFrom.hydraVersion})
@@ -341,108 +341,108 @@ origin session: ${n.session.sessionId}
341
341
  origin upstream: ${c}
342
342
  history entries: ${n.history.length}`+(n.promptHistory?`, prompt history: ${n.promptHistory.length}
343
343
  `:`
344
- `))}async function kx(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function Ix(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function ng(t,e={}){let n=await ye(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Et(n),l=e.cwd?Yt.resolve(e.cwd):process.cwd(),f=await En(d,{cwd:l,all:!0}),u=wd(f,l);u||(process.stderr.write(`No sessions found for ${l}.
345
- `),process.exit(1)),s=u.sessionId}let{host:r,port:i,isFallback:o}=xx(e.host,n),a=Ve(s),c=kf({host:r,port:i,sessionId:a});process.stdout.write(c+`
344
+ `))}async function Wx(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function zx(t,e){let n=t.headers.get("content-disposition");if(n){let r=n.match(/filename="([^"]+)"/);if(r)return r[1]}let s=new Date().toISOString().replace(/[:.]/g,"-");return`hydra-${e}-${s}.hydra`}async function yg(t,e={}){let n=await we(),s;if(t!==void 0&&t.length>0)s=t;else{let d=await Mt(n),l=e.cwd?tn.resolve(e.cwd):process.cwd(),u=await Fn(d,{cwd:l,all:!0}),f=Md(u,l);f||(process.stderr.write(`No sessions found for ${l}.
345
+ `),process.exit(1)),s=f.sessionId}let{host:r,port:i,isFallback:o}=Jx(e.host,n),a=et(s),c=Of({host:r,port:i,sessionId:a});process.stdout.write(c+`
346
346
  `),o&&process.stderr.write(`Note: this URL points at loopback (127.0.0.1) and only works from the same machine. Set daemon.publicHost in config.json or pass --host <name> to advertise an externally-reachable hostname.
347
- `)}function xx(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=Kh(t,an);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=Kh(e.daemon.publicHost,an);return{host:n,port:s,isFallback:!1}}return Cx(e.daemon.host)?{host:Ax(),port:e.daemon.port,isFallback:!1}:Xs(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function Cx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function Ax(){let t=Yh.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function Kh(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}ou();Sd();nu();Ne();pe();Ss();var dC={extension:{singular:"extension",plural:"extensions",logFile:t=>_.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>_.transformerLogFile(t)}};function Rd(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Ti(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Td(t){let e=dC[t],n=`/v1/${e.plural}`;async function s(){let f=(await Ee(n,{expectStatus:200})).body[e.plural]??[];if(f.length===0){process.stdout.write(`No ${e.plural} configured.
348
- `);return}let u=f.map(w=>({name:w.name,status:w.status.toUpperCase(),version:w.version??"-",pid:w.pid!=null?String(w.pid):"-",restarts:String(w.restartCount),started:w.startedAt?bi(w.startedAt):"-",log:w.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},m={name:Ti(p.name,u.map(w=>w.name)),status:Ti(p.status,u.map(w=>w.status)),version:Ti(p.version,u.map(w=>w.version)),pid:Ti(p.pid,u.map(w=>w.pid)),restarts:Ti(p.restarts,u.map(w=>w.restarts)),started:Ti(p.started,u.map(w=>w.started))},h=w=>[w.name.padEnd(m.name),w.status.padEnd(m.status),w.version.padEnd(m.version),w.pid.padStart(m.pid),w.restarts.padStart(m.restarts),w.started.padEnd(m.started),w.log].join(" ");process.stdout.write(h(p)+`
349
- `);for(let w of u)process.stdout.write(h(w)+`
350
- `);for(let w of f)w.failureReason&&process.stdout.write(` \u21B3 ${w.name}: ${w.failureReason}
347
+ `)}function Jx(t,e){if(t!==void 0&&t.length>0){let{host:n,port:s}=dg(t,pn);return{host:n,port:s,isFallback:!1}}if(e.daemon.publicHost&&e.daemon.publicHost.length>0){let{host:n,port:s}=dg(e.daemon.publicHost,pn);return{host:n,port:s,isFallback:!1}}return Kx(e.daemon.host)?{host:Vx(),port:e.daemon.port,isFallback:!1}:dr(e.daemon.host)?{host:"127.0.0.1",port:e.daemon.port,isFallback:!0}:{host:e.daemon.host,port:e.daemon.port,isFallback:!1}}function Kx(t){return t==="0.0.0.0"||t==="::"||t==="0.0.0.0/0"}function Vx(){let t=cg.hostname();return!t||t.length===0?"127.0.0.1":t.includes(".")?t:`${t}.local`}function dg(t,e){if(t.startsWith("[")){let s=t.indexOf("]");if(s>0){let r=t.slice(1,s),i=t.slice(s+1);if(i.startsWith(":")){let o=Number(i.slice(1));return{host:r,port:Number.isInteger(o)&&o>0?o:e}}return{host:r,port:e}}}let n=t.lastIndexOf(":");if(n>0&&t.indexOf(":")===n){let s=t.slice(0,n),r=Number(t.slice(n+1));if(Number.isInteger(r)&&r>0)return{host:s,port:r}}return{host:t,port:e}}yu();Fd();pu();je();he();$s();var PC={extension:{singular:"extension",plural:"extensions",logFile:t=>$.extensionLogFile(t)},transformer:{singular:"transformer",plural:"transformers",logFile:t=>$.transformerLogFile(t)}};function Hd(t){if(t&&typeof t=="object"&&"error"in t){let e=t.error;if(typeof e=="string"&&e.length>0)return`: ${e}`}return""}function Di(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}function Ud(t){let e=PC[t],n=`/v1/${e.plural}`;async function s(){let u=(await Fe(n,{expectStatus:200})).body[e.plural]??[];if(u.length===0){process.stdout.write(`No ${e.plural} configured.
348
+ `);return}let f=u.map(y=>({name:y.name,status:y.status.toUpperCase(),version:y.version??"-",pid:y.pid!=null?String(y.pid):"-",restarts:String(y.restartCount),started:y.startedAt?Pi(y.startedAt):"-",log:y.logPath})),p={name:"NAME",status:"STATUS",version:"VERSION",pid:"PID",restarts:"RESTARTS",started:"STARTED",log:"LOG"},m={name:Di(p.name,f.map(y=>y.name)),status:Di(p.status,f.map(y=>y.status)),version:Di(p.version,f.map(y=>y.version)),pid:Di(p.pid,f.map(y=>y.pid)),restarts:Di(p.restarts,f.map(y=>y.restarts)),started:Di(p.started,f.map(y=>y.started))},h=y=>[y.name.padEnd(m.name),y.status.padEnd(m.status),y.version.padEnd(m.version),y.pid.padStart(m.pid),y.restarts.padStart(m.restarts),y.started.padEnd(m.started),y.log].join(" ");process.stdout.write(h(p)+`
349
+ `);for(let y of f)process.stdout.write(h(y)+`
350
+ `);for(let y of u)y.failureReason&&process.stdout.write(` \u21B3 ${y.name}: ${y.failureReason}
351
351
  `)}async function r(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} add <name> [--command CMD] [--args A,B,C] [--env K=V]... [--disabled]
352
352
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(d)){process.stderr.write(`Invalid ${e.singular} name '${d}': must match [A-Za-z0-9._-]+
353
- `),process.exit(2);return}await ye();let f=await vi(),u=f;(!u[e.plural]||typeof u[e.plural]!="object")&&(u[e.plural]={});let p=u[e.plural];if(p[d]){process.stderr.write(`${wg(e.singular)} '${d}' already exists in config.
354
- `),process.exit(1);return}let m=gd(l,e.singular),h=m.command,w={};h.length>0&&(w.command=h),m.args.length>0&&(w.args=m.args),Object.keys(m.env).length>0&&(w.env=m.env),m.enabled||(w.enabled=!1),p[d]=w,await jl(f),process.stdout.write(`Added ${e.singular} '${d}' to ${_.config()}
355
- `);let b={name:d,...w};try{let v=await Ee(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,x=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${x}
356
- `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${Rd(v.body)}). Restart the daemon to apply.
353
+ `),process.exit(2);return}await we();let u=await Mi(),f=u;(!f[e.plural]||typeof f[e.plural]!="object")&&(f[e.plural]={});let p=f[e.plural];if(p[d]){process.stderr.write(`${$g(e.singular)} '${d}' already exists in config.
354
+ `),process.exit(1);return}let m=Ed(l,e.singular),h=m.command,y={};h.length>0&&(y.command=h),m.args.length>0&&(y.args=m.args),Object.keys(m.env).length>0&&(y.env=m.env),m.enabled||(y.enabled=!1),p[d]=y,await Zl(u),process.stdout.write(`Added ${e.singular} '${d}' to ${$.config()}
355
+ `);let b={name:d,...y};try{let v=await Fe(n,{method:"POST",body:b,rethrowNetworkError:!0});if(v.ok){let S=v.body,x=S.pid!=null?` pid=${S.pid}`:"";process.stdout.write(`${d}: ${S.status}${x}
356
+ `);return}process.stderr.write(`Daemon refused to register ${d} (HTTP ${v.status}${Hd(v.body)}). Restart the daemon to apply.
357
357
  `)}catch{}}async function i(d){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} remove <name>
358
- `),process.exit(2);return}await ye();let l=await vi(),f=l,u=f[e.plural]??{};if(!u[d]){process.stderr.write(`${wg(e.singular)} '${d}' not found in config.
359
- `),process.exit(1);return}delete u[d],f[e.plural]=u,await jl(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${_.config()}
360
- `);try{let p=await Ee(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
361
- `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Rd(p.body)}).
358
+ `),process.exit(2);return}await we();let l=await Mi(),u=l,f=u[e.plural]??{};if(!f[d]){process.stderr.write(`${$g(e.singular)} '${d}' not found in config.
359
+ `),process.exit(1);return}delete f[d],u[e.plural]=f,await Zl(l),process.stdout.write(`Removed ${e.singular} '${d}' from ${$.config()}
360
+ `);try{let p=await Fe(`${n}/${encodeURIComponent(d)}`,{method:"DELETE",rethrowNetworkError:!0});if(p.status===204||p.status===404){process.stdout.write(`${d}: stopped
361
+ `);return}process.stderr.write(`Daemon refused to unregister ${d} (HTTP ${p.status}${Hd(p.body)}).
362
362
  `)}catch(p){process.stderr.write(`Daemon not reachable (${p.message}). Config saved.
363
363
  `)}}async function o(d,l){if(!d){process.stderr.write(`Usage: hydra-acp ${e.plural} ${l} <name|all>
364
- `),process.exit(2);return}if(d==="all"){await a(l);return}let f=await Ee(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!f.ok){process.stderr.write(`HTTP ${f.status}${Rd(f.body)}
365
- `),process.exit(1);return}let u=f.body,p=u.pid!=null?` pid=${u.pid}`:"";process.stdout.write(`${d}: ${u.status}${p}
366
- `)}async function a(d){let p=((await Ee(n,{expectStatus:200})).body[e.plural]??[]).filter(h=>d==="start"?h.enabled&&h.status!=="running":h.status==="running");if(p.length===0){let h=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${h}.
367
- `);return}let m=0;for(let h of p)try{let w=await Ee(`${n}/${encodeURIComponent(h.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!w.ok){process.stdout.write(`${h.name}: ERROR HTTP ${w.status}${Rd(w.body)}
368
- `),m+=1;continue}let b=w.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${h.name}: ${b.status}${v}
369
- `)}catch(w){process.stdout.write(`${h.name}: ERROR ${w.message}
370
- `),m+=1}m>0&&process.exit(1)}async function c(d){let{name:l,rest:f}=md(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
371
- `),process.exit(2);return}let u=e.logFile(l);await gi(u,f,`No log file (${e.singular} never ran?)`)}return{list:s,add:r,remove:i,start:d=>o(d,"start"),stop:d=>o(d,"stop"),restart:d=>o(d,"restart"),logs:c}}function wg(t){return t.charAt(0).toUpperCase()+t.slice(1)}var fr=Td("extension"),bg=fr.list,vg=fr.add,Sg=fr.remove,kg=fr.start,Ig=fr.stop,xg=fr.restart,Cg=fr.logs;var pr=Td("transformer"),Ag=pr.list,Rg=pr.add,Tg=pr.remove,Eg=pr.start,Pg=pr.stop,Mg=pr.restart,_g=pr.logs;Ne();pe();Ss();async function Fg(){let e=(await Ee("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
372
- `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:Kn(s.id,n.map(a=>a.id)),name:Kn(s.name,n.map(a=>a.name)),version:Kn(s.version,n.map(a=>a.version)),source:Kn(s.source,n.map(a=>a.source)),distributions:Kn(s.distributions,n.map(a=>a.distributions)),installed:Kn(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
364
+ `),process.exit(2);return}if(d==="all"){await a(l);return}let u=await Fe(`${n}/${encodeURIComponent(d)}/${l}`,{method:"POST"});if(!u.ok){process.stderr.write(`HTTP ${u.status}${Hd(u.body)}
365
+ `),process.exit(1);return}let f=u.body,p=f.pid!=null?` pid=${f.pid}`:"";process.stdout.write(`${d}: ${f.status}${p}
366
+ `)}async function a(d){let p=((await Fe(n,{expectStatus:200})).body[e.plural]??[]).filter(h=>d==="start"?h.enabled&&h.status!=="running":h.status==="running");if(p.length===0){let h=d==="start"?`no enabled ${e.plural} are stopped`:`no ${e.plural} are running`;process.stdout.write(`Nothing to ${d}: ${h}.
367
+ `);return}let m=0;for(let h of p)try{let y=await Fe(`${n}/${encodeURIComponent(h.name)}/${d}`,{method:"POST",rethrowNetworkError:!0});if(!y.ok){process.stdout.write(`${h.name}: ERROR HTTP ${y.status}${Hd(y.body)}
368
+ `),m+=1;continue}let b=y.body,v=b.pid!=null?` pid=${b.pid}`:"";process.stdout.write(`${h.name}: ${b.status}${v}
369
+ `)}catch(y){process.stdout.write(`${h.name}: ERROR ${y.message}
370
+ `),m+=1}m>0&&process.exit(1)}async function c(d){let{name:l,rest:u}=Rd(d);if(!l){process.stderr.write(`Usage: hydra-acp ${e.plural} log <name> [--tail N] [--follow]
371
+ `),process.exit(2);return}let f=e.logFile(l);await Ri(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 $g(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Ir=Ud("extension"),Fg=Ir.list,Og=Ir.add,Lg=Ir.remove,Bg=Ir.start,Ng=Ir.stop,Dg=Ir.restart,Hg=Ir.logs;var xr=Ud("transformer"),Ug=xr.list,jg=xr.add,qg=xr.remove,Wg=xr.start,zg=xr.stop,Jg=xr.restart,Kg=xr.logs;je();he();$s();async function Qg(){let e=(await Fe("/v1/agents",{expectStatus:200})).body;if(e.agents.length===0){process.stdout.write(`No agents in registry.
372
+ `);return}let n=e.agents.map(a=>({id:a.id,name:a.name,version:a.version,source:a.source??"registry",distributions:a.distributions.join(","),installed:a.installed,description:a.description??""})),s={id:"ID",name:"NAME",version:"VERSION",source:"SOURCE",distributions:"DIST",installed:"INSTALLED",description:"DESCRIPTION"},r={id:ts(s.id,n.map(a=>a.id)),name:ts(s.name,n.map(a=>a.name)),version:ts(s.version,n.map(a=>a.version)),source:ts(s.source,n.map(a=>a.source)),distributions:ts(s.distributions,n.map(a=>a.distributions)),installed:ts(s.installed,n.map(a=>a.installed))},i=a=>[a.id.padEnd(r.id),a.name.padEnd(r.name),a.version.padEnd(r.version),a.source.padEnd(r.source),a.distributions.padEnd(r.distributions),a.installed.padEnd(r.installed),a.description].join(" ");process.stdout.write(i(s)+`
373
373
  `);for(let a of n)process.stdout.write(i(a)+`
374
- `);let o=e.fetchedAt!==void 0?` (synced ${bi(e.fetchedAt)})`:"";process.stdout.write(`
374
+ `);let o=e.fetchedAt!==void 0?` (synced ${Pi(e.fetchedAt)})`:"";process.stdout.write(`
375
375
  Registry version: ${e.version}${o}
376
- `)}async function du(t){if((await ye()).agents[t]!==void 0)return;let n;try{let s=await Ee("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;n=s.body.agents.map(i=>i.id)}catch{return}n.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
377
- `),process.exit(2))}async function Lg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
376
+ `)}async function bu(t){if((await we()).agents[t]!==void 0)return;let n;try{let s=await Fe("/v1/agents",{rethrowNetworkError:!0});if(!s.ok)return;n=s.body.agents.map(i=>i.id)}catch{return}n.includes(t)||(process.stderr.write(`hydra-acp: unknown agent '${t}'. Run 'hydra-acp agent list' to see available agents.
377
+ `),process.exit(2))}async function Gg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent install <agent-id>
378
378
  `),process.exit(2);return}process.stdout.write(`Installing ${t}\u2026
379
- `);let n=(await Ee(`/v1/agents/${encodeURIComponent(t)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!n.installed){process.stdout.write(`${n.agentId} (${n.version}, ${n.distribution}): ${n.message??"nothing to install"}
379
+ `);let n=(await Fe(`/v1/agents/${encodeURIComponent(t)}/install`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent install ${t}:`})).body;if(!n.installed){process.stdout.write(`${n.agentId} (${n.version}, ${n.distribution}): ${n.message??"nothing to install"}
380
380
  `);return}process.stdout.write(`Installed ${n.agentId} (${n.version}, ${n.distribution})
381
381
  `),n.command&&process.stdout.write(` \u2192 ${n.command}
382
- `)}async function Bg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
383
- `),process.exit(2);return}let n=(await Ee(`/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(n.synced.length===0){process.stdout.write(`Nothing new to sync (${n.skipped} already tracked).
384
- `);return}let s=n.synced.map(a=>({id:a.sessionId,upstream:a.upstreamSessionId,cwd:a.cwd,title:a.title??"-"})),r={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},i={id:Kn(r.id,s.map(a=>a.id)),upstream:Kn(r.upstream,s.map(a=>a.upstream)),cwd:Kn(r.cwd,s.map(a=>a.cwd))},o=a=>[a.id.padEnd(i.id),a.upstream.padEnd(i.upstream),a.cwd.padEnd(i.cwd),a.title].join(" ");process.stdout.write(o(r)+`
382
+ `)}async function Xg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent sync <agent-id>
383
+ `),process.exit(2);return}let n=(await Fe(`/v1/agents/${encodeURIComponent(t)}/sync`,{method:"POST",expectStatus:200,errorPrefix:`hydra agent sync ${t}:`})).body;if(n.synced.length===0){process.stdout.write(`Nothing new to sync (${n.skipped} already tracked).
384
+ `);return}let s=n.synced.map(a=>({id:a.sessionId,upstream:a.upstreamSessionId,cwd:a.cwd,title:a.title??"-"})),r={id:"ID",upstream:"UPSTREAM",cwd:"CWD",title:"TITLE"},i={id:ts(r.id,s.map(a=>a.id)),upstream:ts(r.upstream,s.map(a=>a.upstream)),cwd:ts(r.cwd,s.map(a=>a.cwd))},o=a=>[a.id.padEnd(i.id),a.upstream.padEnd(i.upstream),a.cwd.padEnd(i.cwd),a.title].join(" ");process.stdout.write(o(r)+`
385
385
  `);for(let a of s)process.stdout.write(o(a)+`
386
386
  `);process.stdout.write(`
387
387
  Synced ${n.synced.length} session(s); skipped ${n.skipped} already tracked.
388
- `)}async function Ng(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
389
- `),process.exit(2);return}let n=_.agentLogFile(t);await gi(n,e,"No log file (agent never ran?)")}async function Dg(t,e){let n=await ye();if(!t){let c=await Og()??au(await vi());process.stdout.write(`${$g(c)}
390
- `);return}let s;try{let a=await Ee("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
391
- `),process.exit(1);return}e!==void 0?await wf(t,e):await da(t);let i=au(await vi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
392
- `),process.stdout.write(`${$g(i)}
393
- `);let o=await Og();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${Hg(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
394
- `))}function $g(t){return`Default agent is ${Hg(t)}`}function Hg(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function au(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Og(){try{let t=await Ee("/v1/config",{rethrowNetworkError:!0});return t.ok?au(t.body):void 0}catch{return}}async function cu(){let e=(await Ee("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
395
- `)}async function Ug(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
396
- `),process.exit(2);return}await bf(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
388
+ `)}async function Zg(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent log <id> [--tail N] [--follow]
389
+ `),process.exit(2);return}let n=$.agentLogFile(t);await Ri(n,e,"No log file (agent never ran?)")}async function ey(t,e){let n=await we();if(!t){let c=await Yg()??wu(await Mi());process.stdout.write(`${Vg(c)}
390
+ `);return}let s;try{let a=await Fe("/v1/agents",{rethrowNetworkError:!0});a.ok&&(s=a.body.agents.map(d=>d.id))}catch{}if(!(n.agents[t]!==void 0)&&s!==void 0&&!s.includes(t)){process.stderr.write(`hydra agent set: '${t}' is not in the registry or config.agents. Known ids: ${s.join(", ")}
391
+ `),process.exit(1);return}e!==void 0?await Mf(t,e):await Sa(t);let i=wu(await Mi());e!==void 0&&t!==i.agent&&process.stdout.write(`Default model for ${t} is now ${e}.
392
+ `),process.stdout.write(`${Vg(i)}
393
+ `);let o=await Yg();o!==void 0&&(o.agent===i.agent&&o.model===i.model||process.stdout.write(`Daemon still has ${ty(o)} \u2014 restart with \`hydra-acp daemon restart\` to apply.
394
+ `))}function Vg(t){return`Default agent is ${ty(t)}`}function ty(t){return t.model!==void 0?`${t.agent} with ${t.model}`:t.agent}function wu(t){let e=typeof t.defaultAgent=="string"?t.defaultAgent:"(unset)",s=(t.defaultModels&&typeof t.defaultModels=="object"?t.defaultModels:{})[e];return typeof s=="string"?{agent:e,model:s}:{agent:e}}async function Yg(){try{let t=await Fe("/v1/config",{rethrowNetworkError:!0});return t.ok?wu(t.body):void 0}catch{return}}async function vu(){let e=(await Fe("/v1/registry/refresh",{method:"POST",expectStatus:200})).body;process.stdout.write(`Refreshed registry: ${e.agentCount} agents (version ${e.version})
395
+ `)}async function ny(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent pin <id> [packageSpec] (omit packageSpec to clear)
396
+ `),process.exit(2);return}await _f(t,e),e===void 0?process.stdout.write(`Cleared version pin for ${t}.
397
397
  `):process.stdout.write(`Pinned ${t} to ${e}.
398
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function jg(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
398
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function sy(t,e){if(!t){process.stderr.write(`Usage: hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]...
399
399
  `),process.exit(2);return}if(!/^[A-Za-z0-9._-]+$/.test(t)){process.stderr.write(`Invalid agent id '${t}': must match [A-Za-z0-9._-]+
400
- `),process.exit(2);return}let n=gd(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await fc(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
401
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function qg(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
402
- `),process.exit(2);return}await fc(t,void 0),process.stdout.write(`Removed local agent ${t}.
403
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function lu(t){await vf(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
404
- `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function Kn(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Eo();fi();sr();Ne();tr();lr();It();Nt();wa();mu();import CC from"os";import{spawn as AC}from"child_process";async function RC({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){try{return await t.request("session/new",{cwd:CC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
405
- `),{exitCode:0}}catch(i){if(i instanceof Error&&"code"in i&&i.code===z.AuthRequired){let o=i.data,a=o?._meta?.["hydra-acp"]?.authMethods??n,c=o?._meta?.["hydra-acp"]?.agentId??e,d=await TC(a,s),f=await pu(d,{authenticate:u=>t.request("authenticate",{methodId:u,_meta:{"hydra-acp":{agentId:c}}}),runTerminalAuth:u=>new Promise(p=>{let m=r(u.command,u.args,{stdio:"inherit",env:u.env,cwd:u.cwd});m.on("exit",h=>{p({exitCode:h})}),m.on("error",()=>{p({exitCode:-1})})})});return f.kind==="terminal-completed"?{exitCode:0}:f.kind==="retry"?(process.stderr.write(`auth method completed without terminal step; you may need to retry session/new
406
- `),{exitCode:0}):f.kind==="error"?(process.stderr.write(`${f.message}
407
- `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${f.exitCode}
408
- `),{exitCode:1})}throw i}}async function TC(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
400
+ `),process.exit(2);return}let n=Ed(e,"agent"),s=n.command,r={};s!==void 0&&(r.command=s),n.args.length>0&&(r.args=n.args),Object.keys(n.env).length>0&&(r.env=n.env),await Ic(t,r);let i=s??`${t} (default \u2014 resolved off PATH)`;process.stdout.write(`Local agent ${t} \u2192 ${i}${n.args.length>0?" "+n.args.join(" "):""}
401
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function ry(t){if(!t){process.stderr.write(`Usage: hydra-acp agent remove <id>
402
+ `),process.exit(2);return}await Ic(t,void 0),process.stdout.write(`Removed local agent ${t}.
403
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply to new sessions.\n")}async function Su(t){await $f(t),process.stdout.write(t?"Registry pinned to the on-disk cache. `hydra-acp agent refresh` still forces a fetch.\n":`Registry unpinned \u2014 the daemon will re-fetch per registry.ttlHours.
404
+ `),process.stdout.write("Restart with `hydra-acp daemon restart` to apply.\n")}function ts(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}Do();Ii();pr();je();ur();Sr();xt();Wt();Ma();Cu();import KC from"os";import{spawn as VC}from"child_process";async function YC({conn:t,agentId:e,authMethods:n,method:s,spawn:r}){try{return await t.request("session/new",{cwd:KC.homedir(),mcpServers:[],_meta:{"hydra-acp":{agentId:e}}}),process.stdout.write(`agent ${e} does not currently require authentication
405
+ `),{exitCode:0}}catch(i){if(i instanceof Error&&"code"in i&&i.code===W.AuthRequired){let o=i.data,a=o?._meta?.["hydra-acp"]?.authMethods??n,c=o?._meta?.["hydra-acp"]?.agentId??e,d=await QC(a,s),u=await xu(d,{authenticate:f=>t.request("authenticate",{methodId:f,_meta:{"hydra-acp":{agentId:c}}}),runTerminalAuth:f=>new Promise(p=>{let m=r(f.command,f.args,{stdio:"inherit",env:f.env,cwd:f.cwd});m.on("exit",h=>{p({exitCode:h})}),m.on("error",()=>{p({exitCode:-1})})})});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
406
+ `),{exitCode:0}):u.kind==="error"?(process.stderr.write(`${u.message}
407
+ `),{exitCode:1}):(process.stderr.write(`auth process exited with code ${u.exitCode}
408
+ `),{exitCode:1})}throw i}}async function QC(t,e){if(e!==void 0){let s=t.find(i=>i.id===e);if(s)return s;let r=t.map(i=>i.id).join(", ");process.stderr.write(`unknown auth method "${e}" \u2014 valid ids: ${r}
409
409
  `),process.exit(2)}if(t.length===1)return t[0];if(process.stdin.isTTY===!0){let s=t.map((c,d)=>`${d+1}) ${c.id} \u2014 ${c.name??c.description??""}`);process.stdout.write(`multiple auth methods available. choose one:
410
410
  ${s.join(`
411
411
  `)}
412
412
  `);let{createInterface:r}=await import("readline/promises"),i=r({input:process.stdin,output:process.stdout}),o=await i.question("method> ");i.close();let a=parseInt(o.trim(),10);return(Number.isNaN(a)||a<1||a>t.length)&&(process.stderr.write(`invalid selection "${o}" \u2014 enter a number between 1 and ${t.length}
413
413
  `),process.exit(2)),t[a-1]}let n=t.map(s=>s.id).join(", ");process.stderr.write(`multiple auth methods available; pass --method <id> (one of: ${n})
414
- `),process.exit(2)}async function ay(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
415
- `),process.exit(2));let n=await ye(),s=await Et(n);await vs(n);let r=["acp.v1",`hydra-acp-token.${s.token}`],i=await ur(s.wsUrl,r),o=Tn(i),a=new Pt(o);try{await a.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:fe}})}catch{}let c;try{c=await RC({conn:a,agentId:t,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:AC})}finally{i.close()}process.exit(c.exitCode)}yc();Ss();async function dy(t){let e=Br(t,"force");if(await id()&&!e){let r=await jr("Current password: ");await od(r)||(process.stderr.write(`Wrong password.
416
- `),process.exit(1))}let n=await jr("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
- `),process.exit(2));let s=await jr("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
- `),process.exit(1)),await fh(n),process.stdout.write(`Password set.
419
- `)}async function cy(){let e=(await Ee("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
420
- `);return}let n={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:$d(n.id,s.map(o=>o.id)),label:$d(n.label,s.map(o=>o.label)),createdAt:$d(n.createdAt,s.map(o=>o.createdAt)),expiresAt:$d(n.expiresAt,s.map(o=>o.expiresAt))},i=o=>[o.id.padEnd(r.id),o.label.padEnd(r.label),o.createdAt.padEnd(r.createdAt),o.expiresAt.padEnd(r.expiresAt),o.lastUsedAt].join(" ");process.stdout.write(i(n)+`
414
+ `),process.exit(2)}async function ky(t,e){(t===void 0||t.length===0)&&(process.stderr.write(`Usage: hydra agent auth <agent-id>
415
+ `),process.exit(2));let n=await we(),s=await Mt(n);await _s(n);let r=["acp.v1",`hydra-acp-token.${s.token}`],i=await kr(s.wsUrl,r),o=$n(i),a=new _t(o);try{await a.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:"hydra-cli",version:pe}})}catch{}let c;try{c=await YC({conn:a,agentId:t,authMethods:[],method:typeof e.method=="string"?e.method:void 0,spawn:VC})}finally{i.close()}process.exit(c.exitCode)}Tc();$s();async function Iy(t){let e=Vr(t,"force");if(await wd()&&!e){let r=await Zr("Current password: ");await bd(r)||(process.stderr.write(`Wrong password.
416
+ `),process.exit(1))}let n=await Zr("New password: ");n.length===0&&(process.stderr.write(`Password must not be empty.
417
+ `),process.exit(2));let s=await Zr("Confirm new password: ");n!==s&&(process.stderr.write(`Passwords did not match.
418
+ `),process.exit(1)),await Rh(n),process.stdout.write(`Password set.
419
+ `)}async function xy(){let e=(await Fe("/v1/auth/sessions",{expectStatus:200})).body;if(e.sessions.length===0){process.stdout.write(`No active session tokens.
420
+ `);return}let n={id:"ID",label:"LABEL",createdAt:"CREATED",expiresAt:"EXPIRES",lastUsedAt:"LAST USED"},s=e.sessions.map(o=>({id:o.id,label:o.label??"-",createdAt:o.createdAt,expiresAt:o.expiresAt,lastUsedAt:o.lastUsedAt})),r={id:Jd(n.id,s.map(o=>o.id)),label:Jd(n.label,s.map(o=>o.label)),createdAt:Jd(n.createdAt,s.map(o=>o.createdAt)),expiresAt:Jd(n.expiresAt,s.map(o=>o.expiresAt))},i=o=>[o.id.padEnd(r.id),o.label.padEnd(r.label),o.createdAt.padEnd(r.createdAt),o.expiresAt.padEnd(r.expiresAt),o.lastUsedAt].join(" ");process.stdout.write(i(n)+`
421
421
  `);for(let o of s)process.stdout.write(i(o)+`
422
- `)}async function ly(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
423
- `),process.exit(2));let e=await Ee(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
422
+ `)}async function Cy(t){t||(process.stderr.write(`Usage: hydra-acp auth revoke <id>
423
+ `),process.exit(2));let e=await Fe(`/v1/auth/sessions/${t}`,{method:"DELETE"});if(e.status===204){process.stdout.write(`Revoked ${t}
424
424
  `);return}e.status===404&&(process.stderr.write(`No session token with id ${t}
425
425
  `),process.exit(1)),process.stderr.write(`Daemon returned HTTP ${e.status}
426
- `),process.exit(1)}function $d(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as As from"fs";Ne();tr();lr();hu();It();var Od=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(yu(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(gu(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!gu(e)&&!yu(e)&&"method"in e){if(e.method==="session/update"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0,p=typeof f.update?.messageId=="string"?f.update.messageId:void 0;u&&p&&this.lastMessageIds.set(u,p)}return}if(gu(e)){if(e.method==="session/request_permission"){let f=e.params??{},u=typeof f.sessionId=="string"?f.sessionId:void 0;if(u){let p=f.toolCall,m=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:u,toolCallId:m,params:f};if(this.pendingPermissions.set(e.id,h),m){let w=this.pendingPermissionsByToolCall.get(m);w?w.push(e.id):this.pendingPermissionsByToolCall.set(m,[e.id])}}}return}if(!yu(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=Bt(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function gu(t){return"method"in t&&"id"in t&&t.id!==void 0}function yu(t){return!("method"in t)&&"id"in t}Ld();Nt();pe();to();import{writeFileSync as OC}from"fs";var FC=t=>{OC("/proc/self/comm",t)};function Li(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??FC;try{s(e.commName??vn())}catch{}}function Bi(t,e=vn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Nd(t){Li(Bi(process.argv.slice(2)),{commName:"hydra-shim"});let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await vs(e);let s=new Od,r=Ia(process.stdin,process.stdout),i=n.isLocal?async()=>(await Et(await ye())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new Fi({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await UC(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
427
- `);for(let l of d)await jC(a,l,s.lastMessageId(l.sessionId))}}});LC({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
428
- `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function LC({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(yy("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&JC(i)){e.send({jsonrpc:"2.0",id:i.id,result:br(i.params)});return}BC(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(yy("client\u2192daemon",i),s.observeFromClient(i),WC(i)){e.send(zC(i));return}if(qC(i)){if(t.sessionId){e.send(KC(i,t.sessionId));return}let o=i;t.agentId&&(o=Bd(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Bd(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Bd(o,{title:r.name}),r.used=!0),t.model&&(o=Bd(o,{model:t.model})),e.send(o);return}e.send(i)})}function BC(t,e,n){let s=NC(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=HC(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function NC(t){if(!DC(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function DC(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function HC(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function UC(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
429
- `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function jC(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
426
+ `),process.exit(1)}function Jd(t,e){let n=t.length;for(let s of e)s.length>n&&(n=s.length);return n}import*as Ns from"fs";je();ur();Sr();Au();xt();var Kd=class{contexts=new Map;pending=new Map;pendingPermissions=new Map;pendingPermissionsByToolCall=new Map;lastMessageIds=new Map;observeFromClient(e){if(Tu(e)){if(e.id===null)return;let n=this.pendingPermissions.get(e.id);n&&this.deletePendingPermission(n);return}if(Ru(e)){if(e.method==="session/new"){let n=e.params??{},s=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"new",data:{cwd:s}});return}if(e.method==="session/attach"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"";this.pending.set(e.id,{kind:"attach",data:{sessionId:s}});return}if(e.method==="session/load"||e.method==="session/resume"){let n=e.params??{},s=typeof n.sessionId=="string"?n.sessionId:"",r=typeof n.cwd=="string"?n.cwd:"";this.pending.set(e.id,{kind:"load",data:{sessionId:s,cwd:r}})}}}observeFromServer(e){if(!Ru(e)&&!Tu(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(Ru(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,m=p&&typeof p.toolCallId=="string"?p.toolCallId:void 0,h={requestId:e.id,sessionId:f,toolCallId:m,params:u};if(this.pendingPermissions.set(e.id,h),m){let y=this.pendingPermissionsByToolCall.get(m);y?y.push(e.id):this.pendingPermissionsByToolCall.set(m,[e.id])}}}return}if(!Tu(e)||e.id===null)return;if(e.error){this.pending.delete(e.id);return}let n=this.pending.get(e.id);if(!n)return;this.pending.delete(e.id);let s=e.result??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)return;let i=s._meta,o=qt(i),a=o.upstreamSessionId,c=o.agentId,d="";(n.kind==="new"||n.kind==="load")&&(d=n.data.cwd);let l=o.cwd??d;!a||!c||!l||this.contexts.set(r,{sessionId:r,upstreamSessionId:a,agentId:c,cwd:l,title:o.title,agentArgs:o.agentArgs})}list(){return[...this.contexts.values()]}forget(e){this.contexts.delete(e),this.lastMessageIds.delete(e)}lastMessageId(e){return this.lastMessageIds.get(e)}clearPending(){this.pending.clear()}takePendingPermissions(){let e=[...this.pendingPermissions.values()];return this.pendingPermissions.clear(),this.pendingPermissionsByToolCall.clear(),e}takePendingPermission(e){let n=this.pendingPermissions.get(e);return n&&this.deletePendingPermission(n),n}takePendingPermissionByToolCall(e){let n=this.pendingPermissionsByToolCall.get(e);if(!n||n.length===0)return;let s=n[0],r=this.pendingPermissions.get(s);return r&&this.deletePendingPermission(r),r}deletePendingPermission(e){if(this.pendingPermissions.delete(e.requestId),e.toolCallId){let n=this.pendingPermissionsByToolCall.get(e.toolCallId);if(n){let s=n.indexOf(e.requestId);s>=0&&n.splice(s,1),n.length===0&&this.pendingPermissionsByToolCall.delete(e.toolCallId)}}}};function Ru(t){return"method"in t&&"id"in t&&t.id!==void 0}function Tu(t){return!("method"in t)&&"id"in t}Yd();Wt();he();fo();import{writeFileSync as nA}from"fs";var sA=t=>{nA("/proc/self/comm",t)};function Ki(t,e={}){if(process.title=t,(e.platform??process.platform)!=="linux")return;let s=e.writeComm??sA;try{s(e.commName??Cn())}catch{}}function Vi(t,e=Cn()){return t.length===0?e:`${e} ${t.join(" ")}`}async function Gd(t){Ki(Vi(process.argv.slice(2)),{commName:"hydra-shim"});let e=await we(),n=t.target??await Mt(e);n.isLocal&&!t.target&&await _s(e);let s=new Kd,r=La(process.stdin,process.stdout),i=n.isLocal?async()=>(await Mt(await we())).wsUrl:n.wsUrl,o=["acp.v1",`hydra-acp-token.${n.token}`],a=new Ji({url:i,subprotocols:o,onConnect:async c=>{if(c)return;s.clearPending(),await cA(s,r);let d=s.list();if(d.length!==0){process.stderr.write(`hydra-acp: reconnected; resuming ${d.length} session(s)
427
+ `);for(let l of d)await lA(a,l,s.lastMessageId(l.sessionId))}}});rA({opts:t,upstream:a,downstream:r,tracker:s}),a.onClose(c=>{c&&process.stderr.write(`hydra-acp: ${c.message}
428
+ `),r.close(),process.exit(c?1:0)}),r.onClose(()=>{(async()=>(await Promise.race([a.close().catch(()=>{}),new Promise(d=>setTimeout(d,1e3))]),process.exit(0)))()}),await a.start()}function rA({opts:t,upstream:e,downstream:n,tracker:s}){e.onMessage(i=>{if(_y("daemon\u2192client",i),s.observeFromServer(i),t.dangerouslySkipPermissions===!0&&mA(i)){e.send({jsonrpc:"2.0",id:i.id,result:Pr(i.params)});return}iA(i,s,n),n.send(i)});let r={name:t.name,used:!1};n.onMessage(i=>{if(_y("client\u2192daemon",i),s.observeFromClient(i),fA(i)){e.send(pA(i));return}if(uA(i)){if(t.sessionId){e.send(hA(i,t.sessionId));return}let o=i;t.agentId&&(o=Qd(o,{agentId:t.agentId})),t.agentArgs&&t.agentArgs.length>0&&(o=Qd(o,{agentArgs:t.agentArgs})),r.name&&!r.used&&(o=Qd(o,{title:r.name}),r.used=!0),t.model&&(o=Qd(o,{model:t.model})),e.send(o);return}e.send(i)})}function iA(t,e,n){let s=oA(t);if(!s)return;let r=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(!r)return;let i=e.takePendingPermissionByToolCall(r);if(!i)return;let o=dA(s);n.send({jsonrpc:"2.0",id:i.requestId,result:o?{outcome:o}:null}).catch(()=>{})}function oA(t){if(!aA(t))return;let n=(t.params??{}).update;if(!(!n||typeof n!="object"||n.sessionUpdate!=="permission_resolved"))return n}function aA(t){return"method"in t&&t.method==="session/update"&&!("id"in t&&t.id!==void 0)}function dA(t){if(t.outcome&&typeof t.outcome=="object")return t.outcome;if(typeof t.chosenOptionId=="string")return{kind:"selected",optionId:t.chosenOptionId}}async function cA(t,e){let n=t.takePendingPermissions();if(n.length!==0){process.stderr.write(`hydra-acp: cancelling ${n.length} pending permission request(s)
429
+ `);for(let s of n){let r=typeof s.params.sessionId=="string"?s.params.sessionId:void 0;if(!r)continue;let i={sessionUpdate:"permission_resolved",outcome:{kind:"cancelled",reason:"daemon-disconnected"},resolvedBy:{clientId:"hydra-acp"}};s.toolCallId&&(i.toolCallId=s.toolCallId),await e.send({jsonrpc:"2.0",method:"session/update",params:{sessionId:r,update:i}}).catch(()=>{})}}}async function lA(t,e,n){let s={upstreamSessionId:e.upstreamSessionId,agentId:e.agentId,cwd:e.cwd};e.title!==void 0&&(s.title=e.title),e.agentArgs&&e.agentArgs.length>0&&(s.agentArgs=e.agentArgs);let r={sessionId:e.sessionId,_meta:{"hydra-acp":{resume:s}}};n?(r.historyPolicy="after_message",r.afterMessageId=n):r.historyPolicy="pending_only";let i={jsonrpc:"2.0",id:`resume-${e.sessionId}-${Date.now()}`,method:"session/attach",params:r};try{let o=await t.request(i);o.error&&process.stderr.write(`hydra-acp: replay attach for ${e.sessionId} failed: ${o.error.message}
430
430
  `)}catch(o){process.stderr.write(`hydra-acp: failed to replay attach for ${e.sessionId}: ${o.message}
431
- `)}}function qC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function WC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function zC(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:fe}}}}function JC(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function KC(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var YC=25*1024*1024,gy=!1,vr=null;function yy(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!gy){gy=!0;try{vr=_.shimWireLogFile(),As.mkdirSync(_.home(),{recursive:!0});let n=As.statSync(vr,{throwIfNoEntry:!1});n&&n.size>YC&&As.renameSync(vr,`${vr}.1`)}catch{vr=null}}if(vr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
432
- `;As.appendFile(vr,n,()=>{})}catch{}}}function Bd(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}sr();fi();Eo();Ne();tr();lr();ys();It();Nt();Ld();import{mkdtempSync as iA,rmSync as oA}from"fs";import{tmpdir as aA}from"os";import{join as dA}from"path";function wy(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}Ri();import VC from"chalk";import GC from"strip-ansi";var Dd=new VC.Instance({level:3});function by(t,e){if(t.length===0)return"";let n=xs(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(QC(i,e));let r=s.join(`
431
+ `)}}function uA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/new"}function fA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="initialize"}function pA(t){let e=t.params??{},n=e.clientInfo,s=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return(s&&typeof s.name=="string"?s.name.trim():"").length>0?t:{...t,params:{...e,clientInfo:{...s??{},name:"hydra-acp-shim",version:pe}}}}function mA(t){return"method"in t&&"id"in t&&t.id!==void 0&&t.method==="session/request_permission"}function hA(t,e){return{jsonrpc:"2.0",id:t.id,method:"session/attach",params:{sessionId:e,historyPolicy:"full"}}}var gA=25*1024*1024,My=!1,Mr=null;function _y(t,e){if(process.env.HYDRA_SHIM_WIRE_LOG){if(!My){My=!0;try{Mr=$.shimWireLogFile(),Ns.mkdirSync($.home(),{recursive:!0});let n=Ns.statSync(Mr,{throwIfNoEntry:!1});n&&n.size>gA&&Ns.renameSync(Mr,`${Mr}.1`)}catch{Mr=null}}if(Mr)try{let n=JSON.stringify({t:new Date().toISOString(),pid:process.pid,dir:t,msg:e})+`
432
+ `;Ns.appendFile(Mr,n,()=>{})}catch{}}}function Qd(t,e){let n=t.params??{},s=n._meta??{},r=s["hydra-acp"]??{};return{...t,params:{...n,_meta:{...s,"hydra-acp":{...r,...e}}}}}pr();Ii();Do();je();ur();Sr();Es();xt();Wt();Yd();import{mkdtempSync as RA,rmSync as TA}from"fs";import{tmpdir as EA}from"os";import{join as PA}from"path";function $y(t){let e="",n=!1,s=!1,r=!1,i=()=>{if(e.length===0)return;let a=e;e="",t.onChunk(a)},o=()=>{s||(s=!0,n=!1,t.scheduleFlushCheck(()=>{if(s=!1,n){o();return}i()}))};return{feed(a){r||a.length===0||(e+=a,s?n=!0:o())},eof(){r||(r=!0,i())}}}Ni();import yA from"chalk";import wA from"strip-ansi";var Xd=new yA.Instance({level:3});function Fy(t,e){if(t.length===0)return"";let n=Ls(t);if(n.length===0)return"";let s=[];for(let i of n)s.push(bA(i,e));let r=s.join(`
433
433
  `);return r.endsWith(`
434
434
  `)||(r+=`
435
- `),r}function QC(t,e){let n=sA(t.body,e);return e==="ansi"?n=rA(n,t.bodyStyle):n=GC(n),n}var XC="\x1B[1m",ZC="\x1B[96m",eA="\x1B[93m",tA="\x1B[0m",nA="\0";function sA(t,e){let n=t.replace(/\^\^/g,nA);return e==="ansi"&&(n=n.replace(/\^\+/g,XC).replace(/\^C/g,ZC).replace(/\^Y/g,eA).replace(/\^:/g,tA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function rA(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Dd.bold.yellowBright(t);case"heading-2":return Dd.bold.cyanBright(t);case"heading-3":return Dd.bold(t);case"dim":return Dd.dim(t);default:return t}}var cA=1*1024*1024,vy="mcp__hydra-acp-stdin__";function Sy(t,e){return{sessionId:t,prompt:e,_meta:{[mt]:{ancillary:!0}}}}function lA(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function uA(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(vy))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(vy))}async function ky(t){if(Li(Bi(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
436
- `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=iA(dA(aA(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{oA(c,{recursive:!0,force:!0})}catch{}})}let e=await ye(),n=t.target??await Et(e);n.isLocal&&!t.target&&await vs(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await ur(n.wsUrl,s),i=Tn(r),o=new Pt(i),a=await pA({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:fA(n.baseUrl,n.token)});process.exit(a.exitCode)}function fA(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function pA(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async V=>n.dangerouslySkipPermissions?br(V):uA(V)?br(V):py(V));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:rr,version:fe}})}catch{}let f=await gA(e,n,l),u=!1,p=!0,m="",h=0,w=V=>{V.length!==0&&(o(V),p=V.charCodeAt(V.length-1)===10,u=!0)},b=()=>{if(d||m.length===0)return;let V=by(m,c);if(m="",V.length===0)return;let ge=h>0?`
437
- `:"";w(ge+V),h+=1},v=()=>{b(),u&&!p&&w(`
438
- `),u=!1};e.onNotification("session/update",V=>{let ge=V?.update,Je=Rn(ge,{cwd:n.cwd});if(Je){if(Je.kind==="agent-text"){d?w(Je.text):m+=Je.text;return}if(Je.kind==="turn-complete"){v();return}switch(Je.kind){case"agent-thought":case"tool-call":case"tool-call-update":case"exit-plan-mode":case"plan":case"mode-changed":case"user-text":b();return;default:return}}});let S=!1,x=async V=>{let ge=[];if(n.prompt&&!S&&ge.push({type:"text",text:n.prompt}),V.length>0&&ge.push({type:"text",text:V}),ge.length!==0){try{await e.request("session/prompt",Sy(f,ge)),S=!0}catch(Je){a(`hydra-acp cat: prompt failed: ${Je.message}
439
- `);return}v()}},T=0,F,$=new Promise(V=>{F=V}),H=!1,J=async V=>{H||(H=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:f}))().catch(()=>{}),new Promise(Je=>setTimeout(Je,500))]),await e.close().catch(()=>{}),F({exitCode:V}))};e.onClose(V=>{V&&(a(`hydra-acp cat: ${V.message}
440
- `),T=1),H||(H=!0,v(),F({exitCode:T}))});let B=[],N=!1,j=!1,X=async()=>{if(!N){N=!0;try{for(;B.length>0;){let V=B.shift();if(V===void 0)break;await x(V)}}finally{N=!1,j&&B.length===0&&await J(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await J(0),$;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),mA({conn:e,streamClient:t.streamClient,sessionId:f,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{j=!0,!N&&B.length===0&&J(T)},onError:V=>{a(`hydra-acp cat: stdin error: ${V.message}
441
- `),T=1,j=!0,!N&&B.length===0&&J(T)},onPromptFailed:V=>{a(`hydra-acp cat: ${V.message}
442
- `),T=1,j=!0,!N&&B.length===0&&J(T)}}),$;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let V=wy({scheduleFlushCheck:ge=>{let Je=setImmediate(ge);return()=>clearImmediate(Je)},onChunk:ge=>{B.push(ge),X()}});return s.on("data",ge=>{V.feed(typeof ge=="string"?ge:ge.toString("utf8"))}),s.on("end",()=>{V.eof(),j=!0,!N&&B.length===0&&J(T)}),s.on("error",ge=>{a(`hydra-acp cat: stdin error: ${ge.message}
443
- `),T=1,j=!0,!N&&B.length===0&&J(T)}),$}let be="";return s.on("data",V=>{be+=typeof V=="string"?V:V.toString("utf8")}),s.on("end",()=>{j=!0,be.length>0&&B.push(be),X()}),s.on("error",V=>{a(`hydra-acp cat: stdin error: ${V.message}
444
- `),T=1,j=!0,!N&&B.length===0&&J(T)}),$}function mA(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??cA,d="undecided",l=!1,f=[],u=0,p=!1,m=Promise.resolve(),h=(v,S)=>{let x=v.toString("base64");m=m.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
445
- `)})},w=async()=>{d="inline";let v=Buffer.concat(f,u).toString("utf8");f=[],u=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}u>0&&(h(Buffer.concat(f,u),!1),f=[],u=0),d="file",l&&(l=!1,h(Buffer.alloc(0),!0)),await m.catch(()=>{});let S=hA(r.prompt,v.capacityBytes);e.request("session/prompt",Sy(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||h(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){f.push(S),u+=S.length,u>c&&b();return}if(d==="pivoting"){f.push(S),u+=S.length;return}if(d==="file"){h(S,!1);return}f.push(S),u+=S.length}),i.on("end",()=>{if(p=!0,d==="undecided"){w();return}if(d==="pivoting"){l=!0;return}d==="file"&&h(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function hA(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
435
+ `),r}function bA(t,e){let n=CA(t.body,e);return e==="ansi"?n=AA(n,t.bodyStyle):n=wA(n),n}var vA="\x1B[1m",SA="\x1B[96m",kA="\x1B[93m",IA="\x1B[0m",xA="\0";function CA(t,e){let n=t.replace(/\^\^/g,xA);return e==="ansi"&&(n=n.replace(/\^\+/g,vA).replace(/\^C/g,SA).replace(/\^Y/g,kA).replace(/\^:/g,IA)),n=n.replace(/\^[+\-:CcKY]/g,""),n=n.replace(/\x00/g,"^"),n}function AA(t,e){if(t.length===0||e===void 0)return t;switch(e){case"heading-1":return Xd.bold.yellowBright(t);case"heading-2":return Xd.bold.cyanBright(t);case"heading-3":return Xd.bold(t);case"dim":return Xd.dim(t);default:return t}}var MA=1*1024*1024,Oy="mcp__hydra-acp-stdin__";function Ly(t,e){return{sessionId:t,prompt:e,_meta:{[ht]:{ancillary:!0}}}}function _A(t){if(t)for(let e of t.split(/\r?\n/)){let n=e.trim();if(n)return n.length>80?`${n.slice(0,80)}\u2026`:n}}function $A(t){if(!t||typeof t!="object")return!1;let e=t.toolCall;if(!e||typeof e!="object")return!1;let n=e.title;if(typeof n=="string"&&n.startsWith(Oy))return!0;let s=e.toolName;return!!(typeof s=="string"&&s.startsWith(Oy))}async function By(t){if(Ki(Vi(process.argv.slice(2))),process.stdin.isTTY&&!t.prompt&&!t.sessionId){process.stderr.write(`hydra-acp cat: nothing to send. Pipe input on stdin, pass -p <text>, or attach to an existing session with --session.
436
+ `),process.exit(2);return}if(!t.sessionId&&t.cwd===void 0&&process.stdin.isTTY!==!0){let c=RA(PA(EA(),"hydra-cat-"));t.cwd=c,t.detach||process.once("exit",()=>{try{TA(c,{recursive:!0,force:!0})}catch{}})}let e=await we(),n=t.target??await Mt(e);n.isLocal&&!t.target&&await _s(e);let s=["acp.v1",`hydra-acp-token.${n.token}`],r=await kr(n.wsUrl,s),i=$n(r),o=new _t(i),a=await OA({conn:o,opts:t,stdin:process.stdin,stdinIsTty:process.stdin.isTTY===!0,stdoutIsTty:process.stdout.isTTY===!0,stdout:c=>process.stdout.write(c),stderr:c=>{process.stderr.write(c)},streamClient:FA(n.baseUrl,n.token)});process.exit(a.exitCode)}function FA(t,e){let n={"Content-Type":"application/json",Authorization:`Bearer ${e}`},s=(r,i)=>`${t}/v1/sessions/${encodeURIComponent(r)}/stdin${i}`;return{async open(r,i){let o=await fetch(s(r,"/open"),{method:"POST",headers:n,body:JSON.stringify(i)});if(!o.ok)throw new Error(`stdin/open HTTP ${o.status}`);return await o.json()},async write(r,i,o){let a=await fetch(s(r,""),{method:"POST",headers:n,body:JSON.stringify({chunk:i,eof:o})});if(!a.ok)throw new Error(`stdin write HTTP ${a.status}`)}}}async function OA(t){let{conn:e,opts:n,stdin:s,stdinIsTty:r,stdoutIsTty:i,stdout:o,stderr:a}=t,c=i?"ansi":"plain",d=n.raw===!0,l=!r&&n.sessionId===void 0&&n.follow!==!0;e.setDefaultHandler(async()=>({error:{code:-32601,message:"method not implemented"}})),e.onRequest("session/request_permission",async Y=>n.dangerouslySkipPermissions?Pr(Y):$A(Y)?Pr(Y):Ty(Y));try{await e.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:{name:hr,version:pe}})}catch{}let u=await NA(e,n,l),f=!1,p=!0,m="",h=0,y=Y=>{Y.length!==0&&(o(Y),p=Y.charCodeAt(Y.length-1)===10,f=!0)},b=()=>{if(d||m.length===0)return;let Y=Fy(m,c);if(m="",Y.length===0)return;let ye=h>0?`
437
+ `:"";y(ye+Y),h+=1},v=()=>{b(),f&&!p&&y(`
438
+ `),f=!1};e.onNotification("session/update",Y=>{let ye=Y?.update,Qe=_n(ye,{cwd:n.cwd});if(Qe){if(Qe.kind==="agent-text"){d?y(Qe.text):m+=Qe.text;return}if(Qe.kind==="turn-complete"){v();return}switch(Qe.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 Y=>{let ye=[];if(n.prompt&&!S&&ye.push({type:"text",text:n.prompt}),Y.length>0&&ye.push({type:"text",text:Y}),ye.length!==0){try{await e.request("session/prompt",Ly(u,ye)),S=!0}catch(Qe){a(`hydra-acp cat: prompt failed: ${Qe.message}
439
+ `);return}v()}},T=0,_,F=new Promise(Y=>{_=Y}),j=!1,J=async Y=>{j||(j=!0,v(),n.detach||await Promise.race([(async()=>e.request("session/detach",{sessionId:u}))().catch(()=>{}),new Promise(Qe=>setTimeout(Qe,500))]),await e.close().catch(()=>{}),_({exitCode:Y}))};e.onClose(Y=>{Y&&(a(`hydra-acp cat: ${Y.message}
440
+ `),T=1),j||(j=!0,v(),_({exitCode:T}))});let D=[],L=!1,U=!1,Q=async()=>{if(!L){L=!0;try{for(;D.length>0;){let Y=D.shift();if(Y===void 0)break;await x(Y)}}finally{L=!1,U&&D.length===0&&await J(T)}}};if(r&&!n.sessionId)return n.prompt&&await x(""),await J(0),F;if(l)return typeof s.setEncoding=="function"&&s.setEncoding("utf8"),LA({conn:e,streamClient:t.streamClient,sessionId:u,opts:n,stdin:s,stderr:a,sendInline:x,onEof:()=>{U=!0,!L&&D.length===0&&J(T)},onError:Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
441
+ `),T=1,U=!0,!L&&D.length===0&&J(T)},onPromptFailed:Y=>{a(`hydra-acp cat: ${Y.message}
442
+ `),T=1,U=!0,!L&&D.length===0&&J(T)}}),F;if(typeof s.setEncoding=="function"&&s.setEncoding("utf8"),n.follow===!0||r&&!!n.sessionId){let Y=$y({scheduleFlushCheck:ye=>{let Qe=setImmediate(ye);return()=>clearImmediate(Qe)},onChunk:ye=>{D.push(ye),Q()}});return s.on("data",ye=>{Y.feed(typeof ye=="string"?ye:ye.toString("utf8"))}),s.on("end",()=>{Y.eof(),U=!0,!L&&D.length===0&&J(T)}),s.on("error",ye=>{a(`hydra-acp cat: stdin error: ${ye.message}
443
+ `),T=1,U=!0,!L&&D.length===0&&J(T)}),F}let be="";return s.on("data",Y=>{be+=typeof Y=="string"?Y:Y.toString("utf8")}),s.on("end",()=>{U=!0,be.length>0&&D.push(be),Q()}),s.on("error",Y=>{a(`hydra-acp cat: stdin error: ${Y.message}
444
+ `),T=1,U=!0,!L&&D.length===0&&J(T)}),F}function LA(t){let{conn:e,streamClient:n,sessionId:s,opts:r,stdin:i,stderr:o,sendInline:a}=t,c=r.streamThreshold??MA,d="undecided",l=!1,u=[],f=0,p=!1,m=Promise.resolve(),h=(v,S)=>{let x=v.toString("base64");m=m.then(()=>n.write(s,x,S)).catch(T=>{o(`hydra-acp cat: stdin write failed: ${T.message}
445
+ `)})},y=async()=>{d="inline";let v=Buffer.concat(u,f).toString("utf8");u=[],f=0;try{await a(v)}catch(S){t.onPromptFailed(S);return}t.onEof()},b=async()=>{d="pivoting";let v;try{let T={mode:"memory"};r.streamBufferBytes!==void 0&&(T.capacityBytes=r.streamBufferBytes),v=await n.open(s,T)}catch(T){t.onPromptFailed(new Error(`stdin/open failed: ${T.message}`));return}f>0&&(h(Buffer.concat(u,f),!1),u=[],f=0),d="file",l&&(l=!1,h(Buffer.alloc(0),!0)),await m.catch(()=>{});let S=BA(r.prompt,v.capacityBytes);e.request("session/prompt",Ly(s,[{type:"text",text:S}])).catch(T=>{t.onPromptFailed(new Error(`prompt failed: ${T.message}`))}).then(()=>{p||h(Buffer.alloc(0),!0),t.onEof()})};i.on("data",v=>{let S=typeof v=="string"?Buffer.from(v,"utf8"):v;if(d==="undecided"){u.push(S),f+=S.length,f>c&&b();return}if(d==="pivoting"){u.push(S),f+=S.length;return}if(d==="file"){h(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"&&h(Buffer.alloc(0),!0)}),i.on("error",t.onError)}function BA(t,e){let s=`The user has piped data into this session. The bytes are NOT in your prompt; they live in the \`hydra-acp-stdin\` MCP server and you read them via its tools:
446
446
  - \`info()\` \u2014 current writeCursor / oldestAvailable / capacity / closed. Cheap; call first to see how much data is there.
447
447
  - \`grep({pattern, regex?, case_insensitive?, context_before?, context_after?, cursor?})\` \u2014 server-side line filter; returns matching lines as decoded strings (not base64). Prefer this for "find lines that mention X" questions on multi-MB inputs.
448
448
  - \`head({bytes})\` \u2014 first N bytes (good for headers / preamble / file signatures).
@@ -457,49 +457,49 @@ Use those tools NOW to answer the user's question \u2014 do not ask whether to c
457
457
  User's question:
458
458
  ${t}`:`${s}
459
459
 
460
- Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function gA(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:rr,version:fe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=lA(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[mt]:s});let o=await t.request("session/new",i);return Bt(o._meta),o.sessionId}Ne();pe();function Hd(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function Iy(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function yA(t){try{return JSON.parse(t)}catch{return t}}function xy(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function Cy(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
461
- `),process.exit(2));let e=Hd(t),n=await ye(),s=Iy(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
462
- `),process.exit(1)),process.stdout.write(`${xy(s)}
463
- `)}async function Ay(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
464
- `),process.exit(2));let n=Hd(t),s=yA(e);try{await Wn(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
465
- `),process.exit(1)}process.stdout.write(`set ${t} = ${xy(s)}
466
- `)}async function Ry(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
467
- `),process.exit(2));let e=Hd(t);try{await Wn(n=>{let s=n;for(let r=0;r<e.length-1;r++){let i=e[r],o=s[i];if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}delete s[e[e.length-1]]})}catch(n){process.stderr.write(`${n.message}
460
+ Use those tools to inspect the piped input and report what's there. Start with \`info()\` to see the size, then \`head\` and/or \`tail\` to look at the bytes.`}async function NA(t,e,n){if(e.sessionId)return(await t.request("session/attach",{sessionId:e.sessionId,historyPolicy:"pending_only",clientInfo:{name:hr,version:pe}})).sessionId;let s={};if(e.name)s.title=e.name;else{let a=_A(e.prompt);a&&(s.title=a)}e.model&&(s.model=e.model),n&&(s.mcpStdin=!0);let i={cwd:e.cwd??process.cwd()};e.agentId&&(s.agentId=e.agentId),Object.keys(s).length>0&&(i._meta={[ht]:s});let o=await t.request("session/new",i);return qt(o._meta),o.sessionId}je();he();function Zd(t){let e=t.split(".").filter(n=>n.length>0);if(e.length===0)throw new Error("config key must be a non-empty dotted path");return e}function Ny(t,e){let n=t;for(let s of e){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[s]}return n}function DA(t){try{return JSON.parse(t)}catch{return t}}function Dy(t){return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}async function Hy(t){t||(process.stderr.write(`usage: hydra-acp config get <dotted.key>
461
+ `),process.exit(2));let e=Zd(t),n=await we(),s=Ny(n,e);s===void 0&&(process.stderr.write(`config: key '${t}' is unset
462
+ `),process.exit(1)),process.stdout.write(`${Dy(s)}
463
+ `)}async function Uy(t,e){(!t||e===void 0)&&(process.stderr.write(`usage: hydra-acp config set <dotted.key> <value>
464
+ `),process.exit(2));let n=Zd(t),s=DA(e);try{await Xn(r=>{let i=r;for(let o=0;o<n.length-1;o++){let a=n[o],c=i[a];if(c==null){let d={};i[a]=d,i=d;continue}if(typeof c!="object"||Array.isArray(c))throw new Error(`config: cannot descend into '${n.slice(0,o+1).join(".")}' (not an object)`);i=c}i[n[n.length-1]]=s})}catch(r){process.stderr.write(`${r.message}
465
+ `),process.exit(1)}process.stdout.write(`set ${t} = ${Dy(s)}
466
+ `)}async function jy(t){t||(process.stderr.write(`usage: hydra-acp config unset <dotted.key>
467
+ `),process.exit(2));let e=Zd(t);try{await Xn(n=>{let s=n;for(let r=0;r<e.length-1;r++){let i=e[r],o=s[i];if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}delete s[e[e.length-1]]})}catch(n){process.stderr.write(`${n.message}
468
468
  `),process.exit(1)}process.stdout.write(`unset ${t}
469
- `)}async function Ty(t){let e=await ye(),n=t?Iy(e,Hd(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
469
+ `)}async function qy(t){let e=await we(),n=t?Ny(e,Zd(t)):e;n===void 0&&(process.stderr.write(`config: key '${t}' is unset
470
470
  `),process.exit(1)),process.stdout.write(`${JSON.stringify(n,null,2)}
471
- `)}function Ey(){process.stdout.write(`${_.config()}
472
- `)}Ne();qn();lr();Nt();Ss();async function _y(t={}){let{report:e,configLoaded:n}=await wA();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
471
+ `)}function Wy(){process.stdout.write(`${$.config()}
472
+ `)}je();Gn();Sr();Wt();$s();async function Ky(t={}){let{report:e,configLoaded:n}=await HA();if(t.json){process.stdout.write(JSON.stringify(e,null,2)+`
473
473
  `);return}process.stdout.write(`CLI: ${e.cli}
474
474
  `),n&&(process.stdout.write(`Daemon: ${e.daemon??(e.daemonReachable?"unknown":"not running")}
475
- `),e.daemonReachable&&(Py("Extensions",e.extensions),Py("Transformers",e.transformers)))}function Py(t,e){if(process.stdout.write(`
475
+ `),e.daemonReachable&&(zy("Extensions",e.extensions),zy("Transformers",e.transformers)))}function zy(t,e){if(process.stdout.write(`
476
476
  ${t}:
477
477
  `),e.length===0){process.stdout.write(` (none)
478
478
  `);return}let n=Math.max(...e.map(r=>r.name.length)),s=Math.max(...e.map(r=>(r.version??"-").length),7);for(let r of e){let i=r.version??"-";process.stdout.write(` ${r.name.padEnd(n)} ${i.padEnd(s)} ${r.status}
479
- `)}}async function wA(){let t={cli:fe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await ye()}catch{return{report:t,configLoaded:!1}}let n=await cr(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await Gs()}catch{return{report:t,configLoaded:!0}}let r=await wi(),i={Authorization:`Bearer ${s}`};return t.extensions=await My(`${r}/v1/extensions`,i,"extensions"),t.transformers=await My(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function My(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as bA}from"child_process";import{accessSync as vA,constants as SA,statSync as kA}from"fs";import{delimiter as IA,join as xA}from"path";var CA=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function AA(t){return CA.has(t)}function RA(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function TA(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function EA(t){try{if(!kA(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return vA(t,SA.X_OK),!0}catch{return!1}}function PA(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(IA).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=xA(o,r+a);if(EA(c))return c}}function MA(t,e){let n=bA(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
480
- `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function $y(t){let e=RA(t);if(e===void 0||AA(e))return!1;let n=PA(e);if(n===void 0)return!1;MA(n,TA(t))}wu();var Ps=!1,Jw=!1;function Kw(t){!t||Jw||(Jw=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
481
- `))}async function p0(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(ro(),Mf));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],x=v.slice(1),{flags:T}=dc(b);if(Vw(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
482
- `),process.exit(2);return}let F=S??it(T,"agent");if(!F){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
483
- `),process.exit(2);return}let $=await Gw(Cc(T),{allowPrompt:!1}),H=it(T,"name"),J=it(T,"model");Ps=!0;let B=T["dangerously-skip-permissions"]===!0;Kw(B);let N={agentId:F,agentArgs:x,name:H,model:J,dangerouslySkipPermissions:B};$?.sessionId!==void 0&&(N.sessionId=$.sessionId),$?.target!==void 0&&$.fromUrl&&(N.target=$.target),await Nd(N);return}Gu(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&$y(e);let{positional:s,flags:r}=dc(e);if(Vw(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${m0()}
484
- `);return}if(r.help===!0){Xu();return}let i=Gu(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=it(r,"name"),d=it(r,"agent"),l=it(r,"model"),f=r["dangerously-skip-permissions"]===!0;Kw(f);let u=Cc(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,m=await Gw(u,{allowPrompt:p});m!==void 0&&m.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
485
- `),process.exit(2));let h=m?.sessionId,w=m?.fromUrl?m.target:void 0;if(!a){if(process.stdout.isTTY){Ps=!0,await Yw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return}Ps=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await Nd(b);return}switch(a){case"shim":{Ps=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:f};h!==void 0&&(b.sessionId=h),w!==void 0&&(b.target=w),await Nd(b);return}case"cat":{let b=Gu(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=it(r,"cwd"),T={prompt:S,sessionId:h,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:f};x!==void 0&&(T.cwd=x),w!==void 0&&(T.target=w);let F=Qu(r,"stream-threshold");F!==void 0&&(T.streamThreshold=F);let $=Qu(r,"stream-bytes");$!==void 0&&(T.streamBufferBytes=$),d!==void 0&&await du(d),Ps=!0,await ky(T);return}case"version":{Ps=!0,await _y({json:r.json===!0});return}case"init":await Hf(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Fh();return}if(S==="start"){await Mh(r);return}if(S==="stop"){await _h();return}if(S==="restart"){await $h();return}if(S==="log"||S==="logs"){await Oh(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
486
- `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=it(r,"columns"),S;if(v!==void 0)try{S=Jh(v)}catch(x){process.stderr.write(`${x.message}
487
- `),process.exit(2);return}await Vh({all:r.all===!0,json:r.json===!0,host:typeof r.host=="string"?r.host:void 0,includeNonInteractive:r["include-non-interactive"]===!0,columns:S});return}if(b==="info"){await yg(s[2],{verbose:r.verbose===!0,json:r.json===!0,diff:r.diff===!0,fold:r.fold===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0});return}if(b==="diff"){await gg(s[2],{json:r.json===!0,noColor:r["no-color"]===!0,noPager:r["no-pager"]===!0,fold:r.fold===!0});return}if(b==="kill"){await Gh(s[2]);return}if(b==="remove"){await Qh(s[2]);return}if(b==="collect"){let v=it(r,"max-age-days"),S=it(r,"limit"),x={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
479
+ `)}}async function HA(){let t={cli:pe,daemon:null,daemonReachable:!1,extensions:[],transformers:[]},e;try{e=await we()}catch{return{report:t,configLoaded:!1}}let n=await vr(e);if(n!==void 0&&(t.daemonReachable=!0,t.daemon=n.version??null),!t.daemonReachable)return{report:t,configLoaded:!0};let s;try{s=await or()}catch{return{report:t,configLoaded:!0}}let r=await Ei(),i={Authorization:`Bearer ${s}`};return t.extensions=await Jy(`${r}/v1/extensions`,i,"extensions"),t.transformers=await Jy(`${r}/v1/transformers`,i,"transformers"),{report:t,configLoaded:!0}}async function Jy(t,e,n){try{let s=await fetch(t,{headers:e});if(!s.ok)return[];let i=(await s.json())[n];return Array.isArray(i)?i.map(o=>({name:o.name,version:o.version??null,status:o.status})):[]}catch{return[]}}import{spawnSync as UA}from"child_process";import{accessSync as jA,constants as qA,statSync as WA}from"fs";import{delimiter as zA,join as JA}from"path";var KA=new Set(["agent","agents","auth","cat","config","daemon","extension","extensions","init","launch","registry","session","sessions","shim","transformer","transformers","tui"]);function VA(t){return KA.has(t)}function YA(t){for(let e of t)if(e!==void 0&&!e.startsWith("-"))return e}function QA(t){let e=[],n=!1;for(let s of t){if(!n&&s!==void 0&&!s.startsWith("-")){n=!0;continue}s!==void 0&&e.push(s)}return e}function GA(t){try{if(!WA(t).isFile())return!1}catch{return!1}if(process.platform==="win32")return!0;try{return jA(t,qA.X_OK),!0}catch{return!1}}function XA(t,e=process.env){let n=e.PATH??e.Path??"";if(n.length===0)return;let s=n.split(zA).filter(o=>o.length>0),r=`hydra-acp-${t}`,i=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";"):[""];for(let o of s)for(let a of i){let c=JA(o,r+a);if(GA(c))return c}}function ZA(t,e){let n=UA(t,e,{stdio:"inherit",env:process.env});n.error&&(process.stderr.write(`hydra-acp: failed to exec ${t}: ${n.error.message}
480
+ `),process.exit(1)),typeof n.status=="number"&&process.exit(n.status),n.signal&&process.kill(process.pid,n.signal),process.exit(1)}function Vy(t){let e=YA(t);if(e===void 0||VA(e))return!1;let n=XA(e);if(n===void 0)return!1;ZA(n,QA(t))}Eu();var js=!1,lb=!1;function ub(t){!t||lb||(lb=!0,process.stderr.write(`hydra-acp: --dangerously-skip-permissions is set \u2014 all tool permission requests will be auto-approved.
481
+ `))}async function q0(){let{installGlobalTlsTrust:t}=await Promise.resolve().then(()=>(ho(),Wf));t();let e=process.argv.slice(2),n=e.indexOf("launch");if(n!==-1){let b=e.slice(0,n),v=e.slice(n+1),S=v[0],x=v.slice(1),{flags:T}=bc(b);if(pb(T),T.reattach===!0){process.stderr.write(`hydra-acp launch: --reattach is not valid here. Pass --session <id-or-url> to attach to a specific session.
482
+ `),process.exit(2);return}let _=S??rt(T,"agent");if(!_){process.stderr.write(`Usage: hydra-acp launch <agent> [agent-args...]
483
+ `),process.exit(2);return}let F=await mb(Lc(T),{allowPrompt:!1}),j=rt(T,"name"),J=rt(T,"model");js=!0;let D=T["dangerously-skip-permissions"]===!0;ub(D);let L={agentId:_,agentArgs:x,name:j,model:J,dangerouslySkipPermissions:D};F?.sessionId!==void 0&&(L.sessionId=F.sessionId),F?.target!==void 0&&F.fromUrl&&(L.target=F.target),await Gd(L);return}lf(e)===void 0&&!e.some(b=>b==="--prompt"||b.startsWith("--prompt="))&&Vy(e);let{positional:s,flags:r}=bc(e);if(pb(r),r.version===!0||s[0]==="--version"){process.stdout.write(`hydra-acp ${W0()}
484
+ `);return}if(r.help===!0){ff();return}let i=lf(e)!==void 0||typeof r.prompt=="string",o=s[0],a=o!==void 0&&!o.startsWith("-")?o:i?"cat":o,c=rt(r,"name"),d=rt(r,"agent"),l=rt(r,"model"),u=r["dangerously-skip-permissions"]===!0;ub(u);let f=Lc(r),p=a==="tui"||a===void 0&&process.stdout.isTTY,m=await mb(f,{allowPrompt:p});m!==void 0&&m.sessionId!==void 0&&r.reattach===!0&&(process.stderr.write(`hydra-acp: --session <id> and --reattach are mutually exclusive. Use one or the other.
485
+ `),process.exit(2));let h=m?.sessionId,y=m?.fromUrl?m.target:void 0;if(!a){if(process.stdout.isTTY){js=!0,await fb(r,{sessionId:h,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return}js=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};h!==void 0&&(b.sessionId=h),y!==void 0&&(b.target=y),await Gd(b);return}switch(a){case"shim":{js=!0;let b={name:c,model:l,agentId:d,dangerouslySkipPermissions:u};h!==void 0&&(b.sessionId=h),y!==void 0&&(b.target=y),await Gd(b);return}case"cat":{let b=lf(e),v=typeof r.prompt=="string"?r.prompt:void 0,S=b??v,x=rt(r,"cwd"),T={prompt:S,sessionId:h,name:c,model:l,agentId:d,detach:r.detach===!0,follow:r.follow===!0,raw:r.raw===!0,dangerouslySkipPermissions:u};x!==void 0&&(T.cwd=x),y!==void 0&&(T.target=y);let _=uf(r,"stream-threshold");_!==void 0&&(T.streamThreshold=_);let F=uf(r,"stream-bytes");F!==void 0&&(T.streamBufferBytes=F),d!==void 0&&await bu(d),js=!0,await By(T);return}case"version":{js=!0,await Ky({json:r.json===!0});return}case"init":await Zf(r);return;case"daemon":{let b=e.indexOf("daemon"),v=e.slice(b+1),S=v[0];if(S===void 0||S==="status"){await Qh();return}if(S==="start"){await Jh(r);return}if(S==="stop"){await Kh();return}if(S==="restart"){await Vh();return}if(S==="log"||S==="logs"){await Yh(v.slice(1));return}process.stderr.write(`Unknown daemon subcommand: ${S}
486
+ `),process.exit(2);return}case"session":case"sessions":{let b=s[1];if(b===void 0||b==="list"){let v=rt(r,"columns"),S;if(v!==void 0)try{S=ag(v)}catch(x){process.stderr.write(`${x.message}
487
+ `),process.exit(2);return}await lg({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 _g(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 Mg(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 ug(s[2]);return}if(b==="remove"){await fg(s[2]);return}if(b==="collect"){let v=rt(r,"max-age-days"),S=rt(r,"limit"),x={json:r.json===!0,keepUndecided:r["keep-undecided"]===!0};if(v!==void 0){let T=Number(v);if(!Number.isFinite(T)||T<0){process.stderr.write(`--max-age-days must be a non-negative number
488
488
  `),process.exit(2);return}x.maxAgeDays=T}if(S!==void 0){let T=Number(S);if(!Number.isFinite(T)||T<=0){process.stderr.write(`--limit must be a positive number
489
- `),process.exit(2);return}x.limit=T}await Xh(x);return}if(b==="export"){let v=it(r,"out"),S=it(r,"tools");await Zh(s[2],v,S);return}if(b==="transcript"){let v=it(r,"out");await eg(s[2],v);return}if(b==="import"){let v=it(r,"cwd");await tg(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=it(r,"host"),S=it(r,"cwd");await ng(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
490
- `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await bg();return}if(S==="add"){await vg(x,T);return}if(S==="remove"){await Sg(x);return}if(S==="start"){await kg(x);return}if(S==="stop"){await Ig(x);return}if(S==="restart"){await xg(x);return}if(S==="log"||S==="logs"){await Cg(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
491
- `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Ag();return}if(S==="add"){await Rg(x,T);return}if(S==="remove"){await Tg(x);return}if(S==="start"){await Eg(x);return}if(S==="stop"){await Pg(x);return}if(S==="restart"){await Mg(x);return}if(S==="log"||S==="logs"){await _g(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
492
- `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await Fg();return}if(b==="refresh"){await cu();return}if(b==="install"){await Lg(s[2]);return}if(b==="sync"){await Bg(s[2]);return}if(b==="set"){await Dg(s[2],s[3]);return}if(b==="pin"){await Ug(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await jg(S[1],S.slice(2));return}if(b==="remove"){await qg(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=md(S);await Ng(x,T);return}if(b==="auth"){await ay(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
493
- `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await cu();return}if(b==="pin"){await lu(!0);return}if(b==="unpin"){await lu(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
494
- `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await dy(r);return}process.stderr.write(`Unknown auth password action: ${v}
495
- `),process.exit(2);return}if(b===void 0||b==="list"){await cy();return}if(b==="revoke"){await ly(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
496
- `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await Ty(s[2]);return}if(b==="get"){await Cy(s[2]);return}if(b==="set"){await Ay(s[2],s[3]);return}if(b==="unset"){await Ry(s[2]);return}if(b==="path"){Ey();return}process.stderr.write(`Unknown config subcommand: ${b}
497
- `),process.exit(2);return}case"tui":Ps=!0,await Yw(r,{sessionId:h,agentId:d,name:c,model:l,target:w,dangerouslySkipPermissions:f});return;default:process.stderr.write(`Unknown command: ${a}
498
- `),Xu(),process.exit(2)}}async function Yw(t,e){let n=it(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await du(e.agentId),Li(Bi(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(zw(),Ww)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
499
- `),process.exit(2)),a.drip=!0;let c=Qu(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function Qu(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function Vw(t){let e=uf(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
489
+ `),process.exit(2);return}x.limit=T}await pg(x);return}if(b==="export"){let v=rt(r,"out"),S=rt(r,"tools");await mg(s[2],v,S);return}if(b==="transcript"){let v=rt(r,"out");await hg(s[2],v);return}if(b==="import"){let v=rt(r,"cwd");await gg(s[2],{replace:r.replace===!0,info:r.info===!0,...v!==void 0?{cwd:v}:{}});return}if(b==="share"){let v=rt(r,"host"),S=rt(r,"cwd");await yg(s[2],{...v!==void 0?{host:v}:{},...S!==void 0?{cwd:S}:{}});return}process.stderr.write(`Unknown session subcommand: ${b}
490
+ `),process.exit(2);return}case"extension":case"extensions":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Fg();return}if(S==="add"){await Og(x,T);return}if(S==="remove"){await Lg(x);return}if(S==="start"){await Bg(x);return}if(S==="stop"){await Ng(x);return}if(S==="restart"){await Dg(x);return}if(S==="log"||S==="logs"){await Hg(v.slice(1));return}process.stderr.write(`Unknown extension subcommand: ${S}
491
+ `),process.exit(2);return}case"transformer":case"transformers":{let b=e.indexOf(a),v=e.slice(b+1),S=v[0],x=v[1],T=v.slice(2);if(S===void 0||S==="list"){await Ug();return}if(S==="add"){await jg(x,T);return}if(S==="remove"){await qg(x);return}if(S==="start"){await Wg(x);return}if(S==="stop"){await zg(x);return}if(S==="restart"){await Jg(x);return}if(S==="log"||S==="logs"){await Kg(v.slice(1));return}process.stderr.write(`Unknown transformer subcommand: ${S}
492
+ `),process.exit(2);return}case"agent":case"agents":{let b=s[1];if(b===void 0||b==="list"){await Qg();return}if(b==="refresh"){await vu();return}if(b==="install"){await Gg(s[2]);return}if(b==="sync"){await Xg(s[2]);return}if(b==="set"){await ey(s[2],s[3]);return}if(b==="pin"){await ny(s[2],s[3]);return}if(b==="add"){let v=e.indexOf(a),S=e.slice(v+1);await sy(S[1],S.slice(2));return}if(b==="remove"){await ry(s[2]);return}if(b==="log"||b==="logs"){let v=e.indexOf(a),S=e.slice(v+2),{name:x,rest:T}=Rd(S);await Zg(x,T);return}if(b==="auth"){await ky(s[2],r);return}process.stderr.write(`Unknown agent subcommand: ${b}
493
+ `),process.exit(2);return}case"registry":{let b=s[1];if(b==="refresh"){await vu();return}if(b==="pin"){await Su(!0);return}if(b==="unpin"){await Su(!1);return}process.stderr.write(`Unknown registry subcommand: ${b}
494
+ `),process.exit(2);return}case"auth":{let b=s[1];if(b==="password"){let v=s[2];if(v===void 0||v==="set"){await Iy(r);return}process.stderr.write(`Unknown auth password action: ${v}
495
+ `),process.exit(2);return}if(b===void 0||b==="list"){await xy();return}if(b==="revoke"){await Cy(s[2]);return}process.stderr.write(`Unknown auth subcommand: ${b}
496
+ `),process.exit(2);return}case"config":{let b=s[1];if(b===void 0||b==="list"){await qy(s[2]);return}if(b==="get"){await Hy(s[2]);return}if(b==="set"){await Uy(s[2],s[3]);return}if(b==="unset"){await jy(s[2]);return}if(b==="path"){Wy();return}process.stderr.write(`Unknown config subcommand: ${b}
497
+ `),process.exit(2);return}case"tui":js=!0,await fb(r,{sessionId:h,agentId:d,name:c,model:l,target:y,dangerouslySkipPermissions:u});return;default:process.stderr.write(`Unknown command: ${a}
498
+ `),ff(),process.exit(2)}}async function fb(t,e){let n=rt(t,"cwd"),s=t.reattach===!0,r=t.new===!0,i=t.readonly===!0;i&&e.sessionId===void 0&&(process.stderr.write("hydra-acp: --readonly requires a session id. Pass --session <id-or-url> --readonly, or open the picker and press `v` on a session.\n"),process.exit(2)),e.agentId!==void 0&&await bu(e.agentId),Ki(Vi(process.argv.slice(2)));let{runTui:o}=await Promise.resolve().then(()=>(cb(),db)),a={resume:s,forceNew:r,readonly:i};if(e.sessionId!==void 0&&(a.sessionId=e.sessionId),e.agentId!==void 0&&(a.agentId=e.agentId),n!==void 0&&(a.cwd=n),e.name!==void 0&&(a.name=e.name),e.model!==void 0&&(a.model=e.model),e.target!==void 0&&(a.target=e.target),e.dangerouslySkipPermissions===!0&&(a.dangerouslySkipPermissions=!0),t.drip===!0){e.sessionId===void 0&&(process.stderr.write(`hydra-acp: --drip requires a session id. Pass --session <id-or-url> --drip.
499
+ `),process.exit(2)),a.drip=!0;let c=uf(t,"drip-speed");c!==void 0&&c>0&&(a.dripSpeed=c)}await o(a)}function uf(t,e){let n=t[e];if(n!==void 0){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let s=Number(n);if(Number.isFinite(s))return s}}}function pb(t){let e=xf(t);e!==void 0&&(process.stderr.write(`hydra-acp: unknown flag: --${e}
500
500
 
501
- `),Xu(),process.exit(2))}function Gu(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function Gw(t,e){try{return await Nf(t,e)}catch(n){process.stderr.write(`${n.message}
502
- `),process.exit(1)}}function m0(){try{let t=u0(l0(import.meta.url));return JSON.parse(c0(f0(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function Xu(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp agent auth <id> Run the auth flow for <id>"," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"," hydra-acp config path Print the config file path"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
503
- `))}async function Qw(){if(!Ps)try{let t=await No();t&&process.stderr.write(`\u2728 ${Do(t)}
504
- `)}catch{}}p0().then(Qw).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
505
- `),await Qw(),process.exit(1)});
501
+ `),ff(),process.exit(2))}function lf(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n!==void 0){if(n==="-p")return t[e+1];if(n.startsWith("-p")&&!n.startsWith("--"))return n.slice(2)}}}async function mb(t,e){try{return await Gf(t,e)}catch(n){process.stderr.write(`${n.message}
502
+ `),process.exit(1)}}function W0(){try{let t=U0(H0(import.meta.url));return JSON.parse(D0(j0(t,"../package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}function ff(){process.stdout.write(["hydra-acp \u2014 multi-client ACP session daemon","","Usage:"," hydra-acp [--session <id-or-url>] [--reattach] [opts]"," Auto: TUI when stdout is a TTY, shim otherwise (the editor-spawned case)."," With -p / --prompt and no subcommand, auto-dispatch to cat."," hydra-acp tui [same flags] Force TUI explicitly."," hydra-acp shim [same flags] Force shim explicitly (non-interactive; password prompts not allowed)."," hydra-acp cat [-p <prompt>] [--session <id-or-url>] [--detach] [--raw] [--agent <id>] [--model <id>] [--name <label>]"," Pipe-friendly headless mode. Reads stdin and sends it"," as a prompt to a fresh session, streams the agent's"," response to stdout, exits when stdin closes. A bounded",' input (e.g. `cat file.log | hydra cat -p "..."`) goes in'," as one turn; a streaming input (e.g. `tail -f`) is"," chunked by the natural pauses in the writer. -p is an"," optional standing instruction prepended to every chunk;"," if stdin already contains the question, -p is not needed."," By default, agent markdown is post-processed: ANSI-styled"," on a TTY, stripped to plain text on a pipe, tables laid"," out in both modes. Tool calls / thoughts split paragraphs"," but otherwise stay hidden. --raw bypasses the renderer"," and emits chunks immediately, the way cat used to behave."," With --session, attach to an existing session instead"," of creating a new one. With --detach, the session"," survives in the daemon for slack/browser/notifier"," extensions."," hydra-acp launch <agent> [agent-args...]"," Shim mode, force daemon to spawn <agent>"," from the registry. Args after <agent>"," are forwarded to the agent's command.","","Session selection (any entry point):"," --session <id> Attach to a local session by id."," --session hydra://host[:port]/id Attach to a session on another daemon (loopback uses the local service"," token; remote hosts use the cached credential from ~/.hydra-acp/remotes.json,"," falling back to a password prompt \u2014 but only on the TUI path)."," --session hydra://host/ URL with no id: picker (TUI) or fresh session (shim/cat)."," --reattach Pick the most-recent session for the current cwd."," --new Force a fresh session."," --readonly Open a session as a transcript viewer (requires --session)."," --dangerously-skip-permissions Auto-approve every tool permission request (tui / shim / launch / cat)."," HYDRA_ACP_SESSION Env var equivalent of --session (flag wins)."," hydra-acp init [--rotate-token] Initialize ~/.hydra-acp/config.json"," hydra-acp daemon [status] Show daemon pid/version (default when no subcommand)"," hydra-acp daemon start [--foreground] Start daemon (detached by default; --foreground to attach)"," hydra-acp daemon stop|restart"," hydra-acp daemon log [-f] [-n N] Tail or follow the daemon log"," hydra-acp version [--json] Print CLI, daemon, and extension/transformer versions"," hydra-acp session [list] [--all] [--json] [--host=<host>] [--include-non-interactive] [--columns=<list>]"," List sessions (live + 20 most-recent cold; --all lifts the cold cap AND surfaces non-interactive sessions; --json emits JSON for scripts)."," --host filters by origin machine: 'local' (default) shows only sessions created here, 'all' shows everything, or pass a hostname (e.g. machine-b) to show only imports from that peer."," --include-non-interactive surfaces ancillary (e.g. `hydra cat`) or never-prompted sessions while keeping the cold cap (a narrower --all)."," --columns picks which columns show and their order, e.g. --columns=session,state,title,cost (valid: session,upstream,host,state,agent,model,age,cwd,title,cost). UPSTREAM/HOST/MODEL hidden by default; COST is the trailing column; overrides config.tui.sessionColumns."," hydra-acp session info <id> [--verbose] [--json] [--diff] [--fold] [--no-color] [--no-pager]"," Aggregate one session: turn count, tool histogram, files touched, cost/duration, synopsis. --diff appends the session diff under the summary and pages the whole thing on a TTY (inherits --fold)."," hydra-acp session diff <id> [--json] [--no-color] [--no-pager] [--fold]"," Print a git-diff-shaped view of every file the session edited, reconstructed from history (no git). Pages through $HYDRA_ACP_PAGER / $PAGER / less on a TTY (LESS=FRX default); --no-pager bypasses. --fold collapses sequential hunks that rewrite the same region into one net-effect hunk."," hydra-acp session kill <id> Demote a live session to cold (keeps the on-disk record)"," hydra-acp session remove <id> Remove a session entirely (live or cold)"," hydra-acp session collect [--max-age-days <n>] [--limit <n>] [--keep-undecided] [--json]"," Delete cold sessions that were never promoted to a real conversation \u2014 `hydra cat` one-shots (interactive=false) AND editor-spawned panels that never had a turn (interactive=undefined). With no --max-age-days, collects every matching cold row regardless of age (you typed `collect`, so collect it all). Pass --max-age-days N to scope to anything older than N days; 0 is the same as omitting it. --keep-undecided narrows to only explicit interactive=false rows (matches what the background timer does). --limit caps deletions per call (default 1000); re-run to drain a larger backlog. The daemon also runs this on a timer using config.daemon.sessionGcMaxAgeDays (with the conservative explicit-only policy) \u2014 this is the manual trigger."," hydra-acp session export <id> [--out <file>|.]"," Write a session bundle to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session transcript <id>|<file> [--out <file>|.]"," Render a session as a markdown transcript. Accepts a session id (renders via the daemon) or a local .hydra bundle file (rendered in-process). Writes to <file>, to a default-named file when --out=., or to stdout"," hydra-acp session import <file>|- [--replace] [--cwd <path>] [--info]"," Import a bundle from <file> or stdin (-); --replace overwrites a lineage match (kills it if live); --cwd overrides the bundle's recorded working directory; --info prints the bundle's meta without importing"," hydra-acp session share [<id>] [--host <name>] [--cwd <path>]"," Print a hydra:// URL the recipient can paste into `--session`. With no id, picks the most-recent session for cwd. Host precedence: --host > config.daemon.publicHost > config.daemon.host > 127.0.0.1 (with a stderr warning that the URL is loopback-only)."," hydra-acp extension list List configured extensions and live state"," hydra-acp extension add <name> [opts] Add an extension to config"," hydra-acp extension remove <name> Remove an extension from config"," hydra-acp extension start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp extension log <name> [-f] [-n N] Tail or follow an extension's log"," hydra-acp transformer list List configured transformers and live state"," hydra-acp transformer add <name> [opts] Add a transformer to config (--command, --args, --env, --disabled)"," hydra-acp transformer remove <name> Remove a transformer from config"," hydra-acp transformer start|stop|restart <n>|all Lifecycle on one or all"," hydra-acp transformer log <name> [-f] [-n N] Tail or follow a transformer's log"," hydra-acp agent [list] List agents in the cached registry"," hydra-acp agent refresh Force a registry re-fetch"," hydra-acp agent install <id> Pre-install <id> from the registry (else lazy on first session)"," hydra-acp agent set [<id>] [model] With no args, report the daemon's current default agent and its default model. With <id>, set <id> as the default agent (config.defaultAgent). With <id> and [model], set the per-agent default model (config.defaultModels[<id>])."," hydra-acp agent pin <id> [packageSpec] Pin a registry agent to a specific npm version (e.g. opencode-ai@0.5.12). Omit packageSpec to clear. Sidesteps a broken upstream publish."," hydra-acp agent add <id> [--command CMD] [--args A,B,C] [--env K=V]... Define a local agent that bypasses the registry (e.g. your system `opencode`). --command defaults to <id> (resolved off PATH)."," hydra-acp agent remove <id> Remove a local agent."," hydra-acp registry pin | unpin Freeze the daemon on its cached registry (pin) so a bad push isn't picked up, or resume normal TTL fetching (unpin). `agent refresh` still forces a fetch."," hydra-acp agent sync <id> Spawn <id> just long enough to ACP session/list it, then persist any sessions it remembers (across every cwd) as cold rows in `session list`"," hydra-acp agent log <id> [-f] [-n N] Tail or follow an agent's spawn/stderr log"," hydra-acp agent auth <id> Run the auth flow for <id>"," hydra-acp config [list] [<dotted.key>] Print effective config (or one subtree) as JSON"," hydra-acp config get <dotted.key> Print a single effective value (e.g. `tui.openFileCommand`)"," hydra-acp config set <dotted.key> <value> Persist a value; <value> is parsed as JSON when possible, else stored as a string. Validated against the schema before write."," hydra-acp config unset <dotted.key> Remove a key from config.json (reverts to schema default)"," hydra-acp config path Print the config file path"," hydra-acp auth password [--force] Set the daemon's master password"," hydra-acp auth [list] List active session tokens"," hydra-acp auth revoke <id> Revoke a session token"," hydra-acp tui flags: [--session <id-or-url>] [--reattach] [--new] [--readonly] [--agent <id>] [--model <id>] [--cwd <path>] [--name <label>]"," Smart default (no flags): shows a picker when sessions exist, else new."," hydra-acp --version Print version"," hydra-acp --help Show this help","","External subcommands:"," Any `hydra-acp <name>` whose <name> is not built-in is exec'd as"," `hydra-acp-<name>` from PATH (git-style). Ecosystem packages like"," @hydra-acp/planner expose themselves through this mechanism.","","Config knob flags accept env-var equivalents (flag wins):"," --agent HYDRA_ACP_AGENT"," --model HYDRA_ACP_MODEL (one-shot at session/new; ignored on --session resume)"," --session HYDRA_ACP_SESSION (session id or hydra:// URL)"," --name HYDRA_ACP_NAME",""].join(`
503
+ `))}async function hb(){if(!js)try{let t=await Vo();t&&process.stderr.write(`\u2728 ${Yo(t)}
504
+ `)}catch{}}q0().then(hb).catch(async t=>{process.stderr.write(`hydra-acp: ${t.message}
505
+ `),await hb(),process.exit(1)});