@hydra-acp/cli 0.1.101 → 0.1.102

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/index.js CHANGED
@@ -1,36 +1,36 @@
1
- import*as Si from"fs";import*as st from"fs/promises";import*as ki from"net";import*as Ai from"tls";import Vu from"fastify";import Ku from"@fastify/websocket";var Rs="acp.v1";function Es(n,e){return n.has(Rs)?Rs:!1}import Ii from"pino";import Gu from"pino-roll";import*as be from"fs/promises";import{homedir as Sn}from"os";import{z as S}from"zod";import*as N from"path";import*as bn from"os";var Mi="HYDRA_ACP_HOME";function Me(n){let e=bn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Ri(){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 j(){let n=process.env[Mi];if(n&&n.length>0)return N.resolve(n);let e=Ri();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 N.join(bn.homedir(),".hydra-acp")}var I={home:j,config:()=>N.join(j(),"config.json"),authToken:()=>N.join(j(),"auth-token"),remotes:()=>N.join(j(),"remotes.json"),pidFile:()=>N.join(j(),"daemon.pid"),logFile:()=>N.join(j(),"daemon.log"),currentLogFile:()=>N.join(j(),"current.log"),registryCache:()=>N.join(j(),"registry.json"),agentsDir:()=>N.join(j(),"agents"),agentLogFile:n=>N.join(j(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>N.join(j(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>N.join(j(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>N.join(j(),"sessions"),sessionDir:n=>N.join(j(),"sessions",n),sessionFile:n=>N.join(j(),"sessions",n,"meta.json"),historyFile:n=>N.join(j(),"sessions",n,"history.jsonl"),toolsDir:n=>N.join(j(),"sessions",n,"tools"),toolBlobFile:(n,e)=>N.join(j(),"sessions",n,"tools",e),queueFile:n=>N.join(j(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>N.join(j(),"sessions",".tombstones"),tombstoneAgentDir:n=>N.join(j(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>N.join(j(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>N.join(j(),"extensions"),extensionLogFile:n=>N.join(j(),"extensions",`${n}.log`),extensionPidFile:n=>N.join(j(),"extensions",`${n}.pid`),transformersDir:()=>N.join(j(),"transformers"),transformerLogFile:n=>N.join(j(),"transformers",`${n}.log`),transformerPidFile:n=>N.join(j(),"transformers",`${n}.pid`),transformerState:(n,e)=>N.join(j(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>N.join(j(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>N.join(j(),"prompt-history"),tuiLogFile:()=>N.join(j(),"tui.log"),shimWireLogFile:()=>N.join(j(),"shim-wire.log")};import*as $e from"fs/promises";function Pt(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Ps(){try{let e=(await $e.readFile(I.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ei(){let n=await Ps();if(!n)throw new Error(`No service token found at ${I.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function In(n){await $e.mkdir(I.home(),{recursive:!0}),await $e.writeFile(I.authToken(),n+`
2
- `,{encoding:"utf8",mode:384})}async function Pi(){let n=await Ps();if(n)return n;let e=Pt();return await In(e),process.stderr.write(`hydra-acp: initialized ${I.authToken()} with a fresh service token.
3
- `),e}import*as Q from"fs/promises";import*as Ts from"fs";import*as ie from"path";import{randomBytes as Ti}from"crypto";async function ae(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
- `;await _i(n,r,t)}async function _i(n,e,t={}){let s=await $i(n),r=Fi(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${Oi()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Q.writeFile(o,e,i),await Q.rename(o,s)}catch(i){throw await Q.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{Ts.chmodSync(s,t.mode)}catch{}}async function $i(n){let e;try{e=await Q.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Q.readlink(n),s=ie.isAbsolute(t)?t:ie.resolve(ie.dirname(n),t);try{let r=await Q.realpath(ie.dirname(s));return ie.join(r,ie.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function ue(n){let e;try{e=await Q.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Fi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Oi(){return Ti(4).toString("hex")}var $s="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Hi=S.object({cert:S.string(),key:S.string()}),Fs=55514,Ni=S.object({host:S.string().default("127.0.0.1"),port:S.number().int().positive().default(Fs),logLevel:S.enum(["debug","info","warn","error"]).default("info"),tls:Hi.optional(),sessionIdleTimeoutSeconds:S.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:S.number().int().positive().default(1e4),agentStderrTailBytes:S.number().int().positive().default(4096),publicHost:S.string().optional(),agentSyncIntervalMinutes:S.number().nonnegative().default(60),sessionGcIntervalMinutes:S.number().nonnegative().default(60),sessionGcMaxAgeDays:S.number().positive().default(2)}),ji=S.object({url:S.string().url().default($s),ttlHours:S.number().positive().default(24),pinned:S.boolean().default(!1)}),Bi=S.object({name:S.string().optional(),description:S.string().optional(),command:S.string().optional(),args:S.array(S.string()).optional(),env:S.record(S.string()).optional()}),Ui=S.object({packageSpec:S.string().optional()}),Di=S.object({repaintThrottleMs:S.number().int().nonnegative().default(1e3),maxScrollbackLines:S.number().int().positive().default(1e4),mouse:S.boolean().default(!0),inAppSelection:S.boolean().optional(),selectionClipboard:S.enum(["primary","clipboard","both"]).default("both"),openFileCommand:S.union([S.string(),S.array(S.string())]).optional(),logMaxBytes:S.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:S.number().int().positive().default(32),progressIndicator:S.boolean().default(!0),defaultEnterAction:S.enum(["enqueue","amend"]).default("amend"),showThoughts:S.boolean().default(!0),ambiguousWidth:S.enum(["auto","narrow","wide"]).default("auto"),toolContent:S.enum(["inline","references"]).default("references"),diffContextLines:S.number().int().min(0).default(3),promptHistoryMaxEntries:S.number().int().positive().default(2e3),maxToolItems:S.number().int().nonnegative().default(5),maxPlanItems:S.number().int().nonnegative().default(5),showFileUpdates:S.enum(["none","edit","diff"]).default("edit"),sessionColumns:S.array(S.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),_s=S.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Li=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),qi=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),Os=S.object({daemon:Ni.default({}),registry:ji.default({url:$s,ttlHours:24,pinned:!1}),agents:S.record(S.string(),Bi).default({}),agentOverrides:S.record(S.string(),Ui).default({}),defaultAgent:S.string().default("opencode"),defaultModels:S.record(S.string(),S.string()).default({}),synopsisAgent:S.string().optional(),synopsisModel:S.string().optional(),compaction:S.object({agent:S.string().optional(),model:S.string().optional(),tailK:S.number().int().nonnegative().default(20),maxIterations:S.number().int().positive().default(3),contextFraction:S.number().min(0).max(1).default(.5),hardCeilingFraction:S.number().min(0).max(1).default(.85),absoluteFallback:S.number().int().positive().default(12e4),idleBeforePromptMs:S.number().int().nonnegative().default(3e5),modelContextWindows:S.record(S.string(),S.number().int().positive()).default({})}).default({}),defaultCwd:S.string().default("~"),compressToolContent:S.boolean().default(!0),sessionListColdLimit:S.number().int().nonnegative().default(20),extensions:S.record(_s,Li).default({}),transformers:S.record(_s,qi).default({}),defaultTransformers:S.array(S.string()).default([]),npmRegistry:S.string().url().optional(),tui:Di.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 Hs(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Ns(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function js(){return await zi(),await ue(I.config())??{}}async function zi(){let n;try{n=await be.lstat(I.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await be.stat(I.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await be.readlink(I.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${I.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Ji(){let n=await js(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await be.access(I.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${I.authToken()} and ${I.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await In(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ae(I.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${I.config()} to ${I.authToken()}.
5
- `)}async function Bs(){return await Ji(),Os.parse(await js())}async function Wi(n){await ae(I.config(),n,{mode:384})}function Qi(){return Os.parse({})}function Y(n){return n==="~"||n==="$HOME"?Sn():n.startsWith("~/")?Sn()+n.slice(1):n.startsWith("$HOME/")?Sn()+n.slice(5):n}import*as V from"fs/promises";import{createHash as Vi}from"crypto";import{gzip as Ki,gunzip as Gi}from"zlib";import{promisify as Us}from"util";var Ds=Us(Ki),Yi=Us(Gi),Ls=/^[A-Za-z0-9_-]+$/,Xi=/^[a-f0-9]{64}$/,kn=!0;function qs(n){kn=n}function Tt(n,e){return Ls.test(n)?e===void 0||Xi.test(e):!1}function _t(n,e){return`${I.toolBlobFile(n,e)}.gz`}async function An(n,e){if(!Tt(n))return null;let t=Vi("sha256").update(e,"utf8").digest("hex"),s=_t(n,t),r=I.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(I.toolsDir(n),{recursive:!0});let o=kn?s:r,i=kn?await Ds(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await V.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function $t(n,e){if(!Tt(n,e))return null;try{let t=await V.readFile(_t(n,e));return(await Yi(t)).toString("utf8")}catch{}try{return await V.readFile(I.toolBlobFile(n,e),"utf8")}catch{return null}}async function zs(n,e){if(!Tt(n,e))return null;try{return await V.readFile(_t(n,e))}catch{}try{let t=await V.readFile(I.toolBlobFile(n,e));return await Ds(t)}catch{return null}}async function Js(n,e,t){if(!Tt(n,e))return;let s=_t(n,e);try{await V.access(s);return}catch{}await V.mkdir(I.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ws(n){Ls.test(n)&&await V.rm(I.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as sr from"fs/promises";import*as Ft from"path";import{z as T}from"zod";import*as Vs from"fs";import*as X from"fs/promises";import*as Ie from"path";import{spawn as Ks}from"child_process";import{Readable as Zi}from"stream";function le(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function Mn(n,e=le()){if(e)return n[e]}var Fe=n=>{process.stderr.write(n+`
6
- `)};function Rn(n){Fe=n??(e=>process.stderr.write(e+`
7
- `))}async function Gs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${le()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=I.agentInstallDir(n.agentId,e,n.version),s=Ie.resolve(t,n.target.cmd);if(await xn(s))return s;if(await ea({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await xn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await X.chmod(s,493).catch(()=>{}),s}async function ea(n){await X.mkdir(Ie.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{Fe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ta({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Fe(`hydra-acp: extracting ${n.agentId}`),Oe(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await sa(t,e),await X.unlink(t).catch(()=>{});try{await X.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await xn(n.installDir)){await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Fe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Oe(n,e){if(n)try{n(e)}catch{}}async function ta(n){let e=na(n.url),t=Ie.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),o=Vs.createWriteStream(t),i=Zi.fromWeb(s.body);Oe(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,u=Date.now(),c=0,d=2e3,l=150;return i.on("data",p=>{a+=p.length;let f=Date.now();f-c>=l&&(c=f,Oe(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),f-u>=d&&(u=f,Fe(Qs(n.agentId,a,r)))}),await new Promise((p,f)=>{i.on("error",f),o.on("error",f),o.on("finish",()=>p()),i.pipe(o)}),Fe(Qs(n.agentId,a,r,!0)),Oe(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Qs(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function na(n){let e=new URL(n);return Ie.posix.basename(e.pathname)||"archive"}async function sa(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await Cn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ra("unzip")){await Cn("unzip",["-q",n,"-d",e]);return}await Cn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function Cn(n,e){return new Promise((t,s)=>{let r=Ks(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(o,i)=>{if(o===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function ra(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Ks(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function xn(n){try{return await X.access(n),!0}catch{return!1}}import*as ee from"fs/promises";import*as fe from"path";import{spawn as oa}from"child_process";var Pn=n=>{process.stderr.write(n+`
8
- `)};function Tn(n){Pn=n??(e=>process.stderr.write(e+`
9
- `))}async function Xs(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=I.agentNpmInstallDir(n.agentId,e,n.version),s=ua(n.packageSpec),r=la(s),o={installDir:t,packageName:s,hint:n.bin,basename:r},i=fe.join(t,"node_modules",".bin",n.bin);if(await Re(i))return i;if(await Re(t)){let l=await Ys(o);if(l)return l.binPath}await ia({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Ys(o);if(a)return a.binPath;let u=await er(t,s),c=typeof u=="object"&&u!==null?Object.keys(u):typeof u=="string"?[r]:[],d=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${d}`)}async function ia(n){await ee.mkdir(fe.dirname(n.installDir),{recursive:!0});let e=await ee.mkdtemp(`${n.installDir}.partial-`);try{Pn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),En(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ca({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await ee.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Re(n.installDir)){await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),En(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Pn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),En(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function En(n,e){if(n)try{n(e)}catch{}}var aa=5,da=25;function ca(n){return Zs(n,0)}async function Zs(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=oa("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.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)}),o.on("exit",(a,u)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${u??"unknown"}`,d=i.trim();s(new Error(d?`npm install ${n.packageSpec} failed (${c})
10
- stderr: ${d}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<aa)return await new Promise(r=>setTimeout(r,da*(e+1))),Zs(n,e+1);throw t}}function ua(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function la(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function er(n,e){let t=fe.join(n,"node_modules",e,"package.json");try{let s=await ee.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Ys(n){let e=fe.join(n.installDir,"node_modules",".bin"),t=fe.join(e,n.hint);if(await Re(t))return{binName:n.hint,binPath:t};let s=await er(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[n.hint,n.basename])if(r.includes(o)){let i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let r=fe.join(e,n.basename);if(await Re(r))return{binName:n.basename,binPath:r}}}async function Re(n){try{return await ee.access(n),!0}catch{return!1}}var fa=T.object({package:T.string(),bin:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),He=T.object({archive:T.string().url().optional(),cmd:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),pa=T.object({"darwin-aarch64":He.optional(),"darwin-x86_64":He.optional(),"linux-aarch64":He.optional(),"linux-x86_64":He.optional(),"windows-x86_64":He.optional(),"windows-aarch64":He.optional()}),ma=T.object({package:T.string(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),ga=T.object({command:T.string(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),ha=T.object({command:T.string().optional(),url:T.string().optional(),description:T.string().optional()}),ya=T.object({npx:fa.optional(),binary:pa.optional(),uvx:ma.optional(),exec:ga.optional()}),wa=T.object({id:T.string(),name:T.string(),version:T.string().optional(),description:T.string().optional(),authors:T.array(T.string()).optional(),license:T.string().optional(),icon:T.string().optional(),repository:T.string().optional(),website:T.string().optional(),distribution:ya,onboarding:ha.optional(),requiredEnv:T.array(T.string().min(1)).optional()}),tr=T.object({version:T.string(),agents:T.array(wa),extensions:T.array(T.unknown()).optional()}),ot=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(a=>_n(a)===e);if(o)return this.applyOverride(o);let i=e.toLowerCase();if(i.length>0){let a=s.agents.filter(u=>u.id.toLowerCase().startsWith(i));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:Y(t.command??e),args:t.args?.map(Y),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:va(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=tr.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(I.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=tr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ae(I.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function va(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function _n(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ne(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await $n(i),source:s.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function $n(n){let e=le();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Mn(n.distribution.binary,e);if(s?.cmd){let r=Ft.resolve(I.agentInstallDir(n.id,e,t),s.cmd);if(await nr(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??_n(n)??s.package,o=I.agentNpmInstallDir(n.id,e,t),i=Ft.join(o,"node_modules",".bin",r);if(await nr(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function nr(n){try{return await sr.access(n),!0}catch{return!1}}async function te(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??_n(n)??r.package,a=t.onInstallProgress;return{command:await Xs({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:o,env:r.env??{},version:s}}if(n.distribution.binary){let r=Mn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${le()??"this platform"}.`);let o=t.onInstallProgress,i=await Gs({agentId:n.id,version:s,target:r,onProgress:o?u=>o({source:"binary",...u}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Aa}from"child_process";import*as Nt from"fs";import*as yr from"path";var k={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 L}from"zod";var rr=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),ba=L.enum(["full","pending_only","none","after_message"]),or=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),ir=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),ar=L.object({sessionId:L.string(),historyPolicy:ba.default("full"),afterMessageId:L.string().optional(),clientId:L.string().optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional(),_meta:L.record(L.unknown()).optional()});import{z as F}from"zod";var dr=F.object({sessionId:F.string()}),cr=F.object({cwd:F.string().optional(),cursor:F.string().optional()}),Fn=F.object({used:F.number().optional(),size:F.number().optional(),costAmount:F.number().optional(),costCurrency:F.string().optional()}),Bl=F.object({sessionId:F.string(),upstreamSessionId:F.string().optional(),cwd:F.string(),title:F.string().optional(),agentId:F.string().optional(),currentModel:F.string().optional(),currentUsage:Fn.optional(),importedFromMachine:F.string().optional(),importedFromUpstreamSessionId:F.string().optional(),parentSessionId:F.string().optional(),forkedFromSessionId:F.string().optional(),forkedFromMessageId:F.string().optional(),originatingClient:F.object({name:F.string(),version:F.string().optional()}).optional(),interactive:F.boolean().optional(),priority:F.number().int().nonnegative().optional(),updatedAt:F.string(),attachedClients:F.number().int().nonnegative(),status:F.enum(["warm","cold"]).default("warm"),busy:F.boolean().default(!1),awaitingInput:F.boolean().default(!1),compactionState:F.any().optional(),forkSynthesisState:F.enum(["running","failed"]).optional(),_meta:F.record(F.unknown()).optional()}),Ia=F.object({sessionId:F.string(),cwd:F.string(),title:F.string().optional(),updatedAt:F.string().optional(),_meta:F.record(F.unknown()).optional()}),Ul=F.object({sessions:F.array(Ia),nextCursor:F.string().optional()});function Ot(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function ur(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:it(n._meta,Ot(n))};return n.title!==void 0&&(e.title=n.title),e}var at="hydra-acp";function Sa(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function dt(n){if(!n)return{};let e=n[at];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=ir.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=Fn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let u={clientId:a.clientId};typeof a.name=="string"&&(u.name=a.name),typeof a.version=="string"&&(u.version=a.version),r.push({messageId:i.messageId,originator:u,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Sa(t.env);r!==void 0&&(s.env=r)}return s}function it(n,e){return{...n??{},[at]:e}}import{z as M}from"zod";var lr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ht=M.object({sessionId:M.string()}),fr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Wl=M.object({sessionId:M.string(),messageId:M.string(),originator:fr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Ql=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Vl=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),pr=M.object({sessionId:M.string(),messageId:M.string()}),Kl=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),mr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Gl=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),gr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),Yl=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),Xl=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:fr,amendedAt:M.number()});import{z as Se}from"zod";var tf=Se.object({agentId:Se.string(),version:Se.string(),source:Se.enum(["binary","npm"]),phase:Se.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:Se.number().optional(),totalBytes:Se.number().optional(),packageSpec:Se.string().optional()}),hr="hydra-acp/agents/install_progress",je={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function On(n,e){let t="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let u of r)u(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let u=t.indexOf(`
1
+ import*as Si from"fs";import*as nt from"fs/promises";import*as ki from"net";import*as Ai from"tls";import Ku from"fastify";import Gu from"@fastify/websocket";var Es="acp.v1";function Ps(n,e){return n.has(Es)?Es:!1}import Ii from"pino";import Yu from"pino-roll";import*as Ie from"fs/promises";import{homedir as kn}from"os";import{z as S}from"zod";import*as N from"path";import*as In from"os";var Mi="HYDRA_ACP_HOME";function Me(n){let e=In.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Ri(){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 j(){let n=process.env[Mi];if(n&&n.length>0)return N.resolve(n);let e=Ri();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 N.join(In.homedir(),".hydra-acp")}var I={home:j,config:()=>N.join(j(),"config.json"),authToken:()=>N.join(j(),"auth-token"),remotes:()=>N.join(j(),"remotes.json"),pidFile:()=>N.join(j(),"daemon.pid"),logFile:()=>N.join(j(),"daemon.log"),currentLogFile:()=>N.join(j(),"current.log"),registryCache:()=>N.join(j(),"registry.json"),agentsDir:()=>N.join(j(),"agents"),agentLogFile:n=>N.join(j(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>N.join(j(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>N.join(j(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>N.join(j(),"sessions"),sessionDir:n=>N.join(j(),"sessions",n),sessionFile:n=>N.join(j(),"sessions",n,"meta.json"),historyFile:n=>N.join(j(),"sessions",n,"history.jsonl"),toolsDir:n=>N.join(j(),"sessions",n,"tools"),toolBlobFile:(n,e)=>N.join(j(),"sessions",n,"tools",e),queueFile:n=>N.join(j(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>N.join(j(),"sessions",".tombstones"),tombstoneAgentDir:n=>N.join(j(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>N.join(j(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>N.join(j(),"extensions"),extensionLogDir:n=>N.join(j(),"extensions",n),extensionLogFile:n=>N.join(j(),"extensions",n,"current.log"),extensionPidFile:n=>N.join(j(),"extensions",n,"extension.pid"),transformersDir:()=>N.join(j(),"transformers"),transformerLogDir:n=>N.join(j(),"transformers",n),transformerLogFile:n=>N.join(j(),"transformers",n,"current.log"),transformerPidFile:n=>N.join(j(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>N.join(j(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>N.join(j(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>N.join(j(),"prompt-history"),tuiLogFile:()=>N.join(j(),"tui.log"),shimWireLogFile:()=>N.join(j(),"shim-wire.log")};import*as $e from"fs/promises";function Et(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function Ts(){try{let e=(await $e.readFile(I.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ei(){let n=await Ts();if(!n)throw new Error(`No service token found at ${I.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Sn(n){await $e.mkdir(I.home(),{recursive:!0}),await $e.writeFile(I.authToken(),n+`
2
+ `,{encoding:"utf8",mode:384})}async function Pi(){let n=await Ts();if(n)return n;let e=Et();return await Sn(e),process.stderr.write(`hydra-acp: initialized ${I.authToken()} with a fresh service token.
3
+ `),e}import*as Q from"fs/promises";import*as _s from"fs";import*as ie from"path";import{randomBytes as Ti}from"crypto";async function ae(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
+ `;await _i(n,r,t)}async function _i(n,e,t={}){let s=await $i(n),r=Fi(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${Oi()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Q.writeFile(o,e,i),await Q.rename(o,s)}catch(i){throw await Q.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{_s.chmodSync(s,t.mode)}catch{}}async function $i(n){let e;try{e=await Q.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Q.readlink(n),s=ie.isAbsolute(t)?t:ie.resolve(ie.dirname(n),t);try{let r=await Q.realpath(ie.dirname(s));return ie.join(r,ie.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function ue(n){let e;try{e=await Q.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function Fi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Oi(){return Ti(4).toString("hex")}var Fs="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Hi=S.object({cert:S.string(),key:S.string()}),Os=55514,Ni=S.object({host:S.string().default("127.0.0.1"),port:S.number().int().positive().default(Os),logLevel:S.enum(["debug","info","warn","error"]).default("info"),tls:Hi.optional(),sessionIdleTimeoutSeconds:S.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:S.number().int().positive().default(1e4),agentStderrTailBytes:S.number().int().positive().default(4096),publicHost:S.string().optional(),agentSyncIntervalMinutes:S.number().nonnegative().default(60),sessionGcIntervalMinutes:S.number().nonnegative().default(60),sessionGcMaxAgeDays:S.number().positive().default(2)}),ji=S.object({url:S.string().url().default(Fs),ttlHours:S.number().positive().default(24),pinned:S.boolean().default(!1)}),Bi=S.object({name:S.string().optional(),description:S.string().optional(),command:S.string().optional(),args:S.array(S.string()).optional(),env:S.record(S.string()).optional()}),Ui=S.object({packageSpec:S.string().optional()}),Di=S.object({repaintThrottleMs:S.number().int().nonnegative().default(1e3),maxScrollbackLines:S.number().int().positive().default(1e4),mouse:S.boolean().default(!0),inAppSelection:S.boolean().optional(),selectionClipboard:S.enum(["primary","clipboard","both"]).default("both"),openFileCommand:S.union([S.string(),S.array(S.string())]).optional(),logMaxBytes:S.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:S.number().int().positive().default(32),progressIndicator:S.boolean().default(!0),defaultEnterAction:S.enum(["enqueue","amend"]).default("amend"),showThoughts:S.boolean().default(!0),ambiguousWidth:S.enum(["auto","narrow","wide"]).default("auto"),toolContent:S.enum(["inline","references"]).default("references"),diffContextLines:S.number().int().min(0).default(3),promptHistoryMaxEntries:S.number().int().positive().default(2e3),maxToolItems:S.number().int().nonnegative().default(5),maxPlanItems:S.number().int().nonnegative().default(5),showFileUpdates:S.enum(["none","edit","diff"]).default("edit"),sessionColumns:S.array(S.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),$s=S.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Li=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),qi=S.object({command:S.array(S.string()).default([]),args:S.array(S.string()).default([]),env:S.record(S.string()).default({}),enabled:S.boolean().default(!0)}),Hs=S.object({daemon:Ni.default({}),registry:ji.default({url:Fs,ttlHours:24,pinned:!1}),agents:S.record(S.string(),Bi).default({}),agentOverrides:S.record(S.string(),Ui).default({}),defaultAgent:S.string().default("opencode"),defaultModels:S.record(S.string(),S.string()).default({}),synopsisAgent:S.string().optional(),synopsisModel:S.string().optional(),compaction:S.object({agent:S.string().optional(),model:S.string().optional(),tailK:S.number().int().nonnegative().default(20),maxIterations:S.number().int().positive().default(3),contextFraction:S.number().min(0).max(1).default(.5),hardCeilingFraction:S.number().min(0).max(1).default(.85),absoluteFallback:S.number().int().positive().default(12e4),idleBeforePromptMs:S.number().int().nonnegative().default(3e5),modelContextWindows:S.record(S.string(),S.number().int().positive()).default({})}).default({}),defaultCwd:S.string().default("~"),compressToolContent:S.boolean().default(!0),sessionListColdLimit:S.number().int().nonnegative().default(20),extensions:S.record($s,Li).default({}),transformers:S.record($s,qi).default({}),defaultTransformers:S.array(S.string()).default([]),npmRegistry:S.string().url().optional(),tui:Di.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 Ns(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function js(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Bs(){return await zi(),await ue(I.config())??{}}async function zi(){let n;try{n=await Ie.lstat(I.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Ie.stat(I.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Ie.readlink(I.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${I.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Ji(){let n=await Bs(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Ie.access(I.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${I.authToken()} and ${I.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Sn(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ae(I.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${I.config()} to ${I.authToken()}.
5
+ `)}async function Us(){return await Ji(),Hs.parse(await Bs())}async function Wi(n){await ae(I.config(),n,{mode:384})}function Qi(){return Hs.parse({})}function Y(n){return n==="~"||n==="$HOME"?kn():n.startsWith("~/")?kn()+n.slice(1):n.startsWith("$HOME/")?kn()+n.slice(5):n}import*as V from"fs/promises";import{createHash as Vi}from"crypto";import{gzip as Ki,gunzip as Gi}from"zlib";import{promisify as Ds}from"util";var Ls=Ds(Ki),Yi=Ds(Gi),qs=/^[A-Za-z0-9_-]+$/,Xi=/^[a-f0-9]{64}$/,An=!0;function zs(n){An=n}function Pt(n,e){return qs.test(n)?e===void 0||Xi.test(e):!1}function Tt(n,e){return`${I.toolBlobFile(n,e)}.gz`}async function Cn(n,e){if(!Pt(n))return null;let t=Vi("sha256").update(e,"utf8").digest("hex"),s=Tt(n,t),r=I.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(I.toolsDir(n),{recursive:!0});let o=An?s:r,i=An?await Ls(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await V.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function _t(n,e){if(!Pt(n,e))return null;try{let t=await V.readFile(Tt(n,e));return(await Yi(t)).toString("utf8")}catch{}try{return await V.readFile(I.toolBlobFile(n,e),"utf8")}catch{return null}}async function Js(n,e){if(!Pt(n,e))return null;try{return await V.readFile(Tt(n,e))}catch{}try{let t=await V.readFile(I.toolBlobFile(n,e));return await Ls(t)}catch{return null}}async function Ws(n,e,t){if(!Pt(n,e))return;let s=Tt(n,e);try{await V.access(s);return}catch{}await V.mkdir(I.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Qs(n){qs.test(n)&&await V.rm(I.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as rr from"fs/promises";import*as $t from"path";import{z as T}from"zod";import*as Ks from"fs";import*as X from"fs/promises";import*as Se from"path";import{spawn as Gs}from"child_process";import{Readable as Zi}from"stream";function le(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function Rn(n,e=le()){if(e)return n[e]}var Fe=n=>{process.stderr.write(n+`
6
+ `)};function En(n){Fe=n??(e=>process.stderr.write(e+`
7
+ `))}async function Ys(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${le()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=I.agentInstallDir(n.agentId,e,n.version),s=Se.resolve(t,n.target.cmd);if(await Mn(s))return s;if(await ea({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await Mn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await X.chmod(s,493).catch(()=>{}),s}async function ea(n){await X.mkdir(Se.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{Fe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ta({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Fe(`hydra-acp: extracting ${n.agentId}`),Oe(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await sa(t,e),await X.unlink(t).catch(()=>{});try{await X.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Mn(n.installDir)){await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Fe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Oe(n,e){if(n)try{n(e)}catch{}}async function ta(n){let e=na(n.url),t=Se.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),o=Ks.createWriteStream(t),i=Zi.fromWeb(s.body);Oe(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,u=Date.now(),c=0,d=2e3,l=150;return i.on("data",f=>{a+=f.length;let p=Date.now();p-c>=l&&(c=p,Oe(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-u>=d&&(u=p,Fe(Vs(n.agentId,a,r)))}),await new Promise((f,p)=>{i.on("error",p),o.on("error",p),o.on("finish",()=>f()),i.pipe(o)}),Fe(Vs(n.agentId,a,r,!0)),Oe(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Vs(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function na(n){let e=new URL(n);return Se.posix.basename(e.pathname)||"archive"}async function sa(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await xn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ra("unzip")){await xn("unzip",["-q",n,"-d",e]);return}await xn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function xn(n,e){return new Promise((t,s)=>{let r=Gs(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(o,i)=>{if(o===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function ra(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Gs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Mn(n){try{return await X.access(n),!0}catch{return!1}}import*as ee from"fs/promises";import*as fe from"path";import{spawn as oa}from"child_process";var Tn=n=>{process.stderr.write(n+`
8
+ `)};function _n(n){Tn=n??(e=>process.stderr.write(e+`
9
+ `))}async function Zs(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=I.agentNpmInstallDir(n.agentId,e,n.version),s=ua(n.packageSpec),r=la(s),o={installDir:t,packageName:s,hint:n.bin,basename:r},i=fe.join(t,"node_modules",".bin",n.bin);if(await Re(i))return i;if(await Re(t)){let l=await Xs(o);if(l)return l.binPath}await ia({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Xs(o);if(a)return a.binPath;let u=await tr(t,s),c=typeof u=="object"&&u!==null?Object.keys(u):typeof u=="string"?[r]:[],d=c.length>0?` (package declares bins: ${c.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${d}`)}async function ia(n){await ee.mkdir(fe.dirname(n.installDir),{recursive:!0});let e=await ee.mkdtemp(`${n.installDir}.partial-`);try{Tn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),Pn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ca({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await ee.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Re(n.installDir)){await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Pn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Tn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Pn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Pn(n,e){if(n)try{n(e)}catch{}}var aa=5,da=25;function ca(n){return er(n,0)}async function er(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=oa("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.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)}),o.on("exit",(a,u)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${u??"unknown"}`,d=i.trim();s(new Error(d?`npm install ${n.packageSpec} failed (${c})
10
+ stderr: ${d}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<aa)return await new Promise(r=>setTimeout(r,da*(e+1))),er(n,e+1);throw t}}function ua(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function la(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function tr(n,e){let t=fe.join(n,"node_modules",e,"package.json");try{let s=await ee.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function Xs(n){let e=fe.join(n.installDir,"node_modules",".bin"),t=fe.join(e,n.hint);if(await Re(t))return{binName:n.hint,binPath:t};let s=await tr(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[n.hint,n.basename])if(r.includes(o)){let i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let r=fe.join(e,n.basename);if(await Re(r))return{binName:n.basename,binPath:r}}}async function Re(n){try{return await ee.access(n),!0}catch{return!1}}var fa=T.object({package:T.string(),bin:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),He=T.object({archive:T.string().url().optional(),cmd:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),pa=T.object({"darwin-aarch64":He.optional(),"darwin-x86_64":He.optional(),"linux-aarch64":He.optional(),"linux-x86_64":He.optional(),"windows-x86_64":He.optional(),"windows-aarch64":He.optional()}),ma=T.object({package:T.string(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),ga=T.object({command:T.string(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional()}),ha=T.object({command:T.string().optional(),url:T.string().optional(),description:T.string().optional()}),ya=T.object({npx:fa.optional(),binary:pa.optional(),uvx:ma.optional(),exec:ga.optional()}),wa=T.object({id:T.string(),name:T.string(),version:T.string().optional(),description:T.string().optional(),authors:T.array(T.string()).optional(),license:T.string().optional(),icon:T.string().optional(),repository:T.string().optional(),website:T.string().optional(),distribution:ya,onboarding:ha.optional(),requiredEnv:T.array(T.string().min(1)).optional()}),nr=T.object({version:T.string(),agents:T.array(wa),extensions:T.array(T.unknown()).optional()}),rt=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(a=>$n(a)===e);if(o)return this.applyOverride(o);let i=e.toLowerCase();if(i.length>0){let a=s.agents.filter(u=>u.id.toLowerCase().startsWith(i));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:Y(t.command??e),args:t.args?.map(Y),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:va(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=nr.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(I.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=nr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ae(I.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function va(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function $n(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ne(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await Fn(i),source:s.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function Fn(n){let e=le();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Rn(n.distribution.binary,e);if(s?.cmd){let r=$t.resolve(I.agentInstallDir(n.id,e,t),s.cmd);if(await sr(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??$n(n)??s.package,o=I.agentNpmInstallDir(n.id,e,t),i=$t.join(o,"node_modules",".bin",r);if(await sr(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function sr(n){try{return await rr.access(n),!0}catch{return!1}}async function te(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??$n(n)??r.package,a=t.onInstallProgress;return{command:await Zs({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:o,env:r.env??{},version:s}}if(n.distribution.binary){let r=Rn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${le()??"this platform"}.`);let o=t.onInstallProgress,i=await Ys({agentId:n.id,version:s,target:r,onProgress:o?u=>o({source:"binary",...u}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Aa}from"child_process";import*as Ht from"fs";import*as wr from"path";var k={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 L}from"zod";var or=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),ba=L.enum(["full","pending_only","none","after_message"]),ir=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),ar=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),dr=L.object({sessionId:L.string(),historyPolicy:ba.default("full"),afterMessageId:L.string().optional(),clientId:L.string().optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional(),_meta:L.record(L.unknown()).optional()});import{z as F}from"zod";var cr=F.object({sessionId:F.string()}),ur=F.object({cwd:F.string().optional(),cursor:F.string().optional()}),On=F.object({used:F.number().optional(),size:F.number().optional(),costAmount:F.number().optional(),costCurrency:F.string().optional()}),Ul=F.object({sessionId:F.string(),upstreamSessionId:F.string().optional(),cwd:F.string(),title:F.string().optional(),agentId:F.string().optional(),currentModel:F.string().optional(),currentUsage:On.optional(),importedFromMachine:F.string().optional(),importedFromUpstreamSessionId:F.string().optional(),parentSessionId:F.string().optional(),forkedFromSessionId:F.string().optional(),forkedFromMessageId:F.string().optional(),originatingClient:F.object({name:F.string(),version:F.string().optional()}).optional(),interactive:F.boolean().optional(),priority:F.number().int().nonnegative().optional(),updatedAt:F.string(),attachedClients:F.number().int().nonnegative(),status:F.enum(["warm","cold"]).default("warm"),busy:F.boolean().default(!1),awaitingInput:F.boolean().default(!1),compactionState:F.any().optional(),forkSynthesisState:F.enum(["running","failed"]).optional(),_meta:F.record(F.unknown()).optional()}),Ia=F.object({sessionId:F.string(),cwd:F.string(),title:F.string().optional(),updatedAt:F.string().optional(),_meta:F.record(F.unknown()).optional()}),Dl=F.object({sessions:F.array(Ia),nextCursor:F.string().optional()});function Ft(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function lr(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ot(n._meta,Ft(n))};return n.title!==void 0&&(e.title=n.title),e}var it="hydra-acp";function Sa(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function at(n){if(!n)return{};let e=n[it];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=ar.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=On.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let u={clientId:a.clientId};typeof a.name=="string"&&(u.name=a.name),typeof a.version=="string"&&(u.version=a.version),r.push({messageId:i.messageId,originator:u,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Sa(t.env);r!==void 0&&(s.env=r)}return s}function ot(n,e){return{...n??{},[it]:e}}import{z as M}from"zod";var fr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ot=M.object({sessionId:M.string()}),pr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Ql=M.object({sessionId:M.string(),messageId:M.string(),originator:pr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Vl=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Kl=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),mr=M.object({sessionId:M.string(),messageId:M.string()}),Gl=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),gr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Yl=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),hr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),Xl=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),Zl=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:pr,amendedAt:M.number()});import{z as ke}from"zod";var nf=ke.object({agentId:ke.string(),version:ke.string(),source:ke.enum(["binary","npm"]),phase:ke.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ke.number().optional(),totalBytes:ke.number().optional(),packageSpec:ke.string().optional()}),yr="hydra-acp/agents/install_progress",je={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function Hn(n,e){let t="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let u of r)u(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let u=t.indexOf(`
11
11
  `);for(;u!==-1;){let c=t.slice(0,u).trim();if(t=t.slice(u+1),c.length>0)try{let d=JSON.parse(c);for(let l of s)l(d)}catch(d){for(let l of s)l({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse ndjson line: ${d.message}`}})}u=t.indexOf(`
12
12
  `)}}),n.on("end",()=>i()),n.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let u=JSON.stringify(a)+`
13
- `;await new Promise((c,d)=>{e.write(u,l=>{if(l){d(l);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as ka}from"nanoid";var Hn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Ee=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new Hn;let s=ka(),r={jsonrpc:"2.0",id:s,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(s,{resolve:u=>i(u),reject:a}),this.stream.send(r).catch(u=>{this.pending.delete(s),a(u)})});return{id:s,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:k.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??k.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}};var Ca=4096,he=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??Ca,this.killEscalationMs=e.killEscalationMs??xa,this.logger=e.logger,this.fileLog=Ma(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
14
- `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=On(t.stdout,t.stdin);this.connection=new Ee(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
13
+ `;await new Promise((c,d)=>{e.write(u,l=>{if(l){d(l);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as ka}from"nanoid";var Nn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Ee=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new Nn;let s=ka(),r={jsonrpc:"2.0",id:s,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(s,{resolve:u=>i(u),reject:a}),this.stream.send(r).catch(u=>{this.pending.delete(s),a(u)})});return{id:s,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:k.MethodNotFound,message:`Method not found: ${e.method}`}).catch(()=>{});return}try{let s=await t(e.params,e.method),r={jsonrpc:"2.0",id:e.id,result:s};await this.stream.send(r).catch(()=>{})}catch(s){let r=s;await this.sendError(e.id,{code:r.code??k.InternalError,message:r.message,data:r.data}).catch(()=>{})}}handleNotification(e){let t=this.notificationHandlers.get(e.method);if(t){t(e.params,e.method);return}let s=this.bufferedNotifications.get(e.method);if(!s){if(this.bufferedNotifications.size>=n.MAX_BUFFERED_METHODS){let r=this.bufferedNotifications.keys().next().value;r!==void 0&&this.bufferedNotifications.delete(r)}s=[],this.bufferedNotifications.set(e.method,s)}s.push(e),s.length>n.MAX_BUFFERED_PER_METHOD&&s.shift()}handleResponse(e){let t=e.id===null?void 0:this.pending.get(e.id);if(!t){if(e.error)for(let s of this.orphanErrorHandlers)try{s({code:e.error.code,message:e.error.message,data:e.error.data})}catch{}return}if(this.pending.delete(e.id),e.error){let s=new Error(e.error.message);s.code=e.error.code,s.data=e.error.data,t.reject(s)}else t.resolve(e.result)}async sendError(e,t){let s={jsonrpc:"2.0",id:e,error:t};await this.stream.send(s)}handleClose(e){if(!this.closed){this.closed=!0;for(let t of this.pending.values())t.reject(e??new Error("connection closed"));this.pending.clear();for(let t of this.closeHandlers)t(e)}}};var Ca=4096,he=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??Ca,this.killEscalationMs=e.killEscalationMs??xa,this.logger=e.logger,this.fileLog=Ma(e.agentId),this.writeLog(`--- spawn pid=${t.pid} version=${e.plan.version} cwd=${e.cwd} cmd=${e.plan.command} args=${JSON.stringify(e.plan.args)} time=${new Date().toISOString()} ---
14
+ `),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Hn(t.stdout,t.stdin);this.connection=new Ee(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
15
15
  `),this.connection.fail(new Error(o))}),t.on("exit",(r,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
16
16
  `),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${r} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${o}`)}for(let i of this.exitHandlers)i(r,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
17
17
  stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Aa(e.plan.command,e.plan.args,{cwd:e.cwd,env:t,stdio:["pipe","pipe","pipe"],detached:!0});return s.unref(),new n(e,s)}onExit(e){this.exitHandlers.push(e)}isAlive(){return!this.exited}async kill(e="SIGTERM"){this.exited||(this.killed=!0,this.writeLog(`--- kill requested signal=${e} time=${new Date().toISOString()} ---
18
18
  `),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()} ---
19
- `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},xa=2e3;function Ma(n){try{let e=I.agentLogFile(n);Nt.mkdirSync(yr.dirname(e),{recursive:!0});let t=Nt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Te from"fs/promises";import*as Vt from"os";import*as vt from"path";import{customAlphabet as jd}from"nanoid";async function Be(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=n;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(u=>u.id).join(", ");return i?.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 i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Ue(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:o}=n;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as Tr}from"nanoid";import*as vr from"fs/promises";var Ra=64*1024*1024,Ea=1*1024*1024,De=64*1024,Pa=6e4,Ta=100,_a=1e3,$a=64*1024,Fa=256*1024,wr=20;function Oa(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jt=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??Ra,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ea,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,De));if(s===0){let l={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(l.eof=!0),l}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let l={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(l.gap=o),this.closed&&(l.eof=!0),l}let u=Math.min(a,s),d={bytes:this.sliceFromRing(r,u),nextCursor:r+u};return o>0&&(d.gap=o),this.closed&&r+u>=this.writeCursor&&(d.eof=!0),d}tail(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Pa));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,o=0;s!==void 0&&s<t&&(o=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,u=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,u):new RegExp(Oa(e.pattern),u),d=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??Ta,_a)),p=Math.max(1,Math.min(e.maxBytes??$a,Fa)),f=Math.max(0,Math.min(e.contextBefore??0,wr)),m=Math.max(0,Math.min(e.contextAfter??0,wr)),g=[],h=[],y=[],v=0,w=!1,b=0,A=0,C=(H,D)=>{for(let z of y)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:H,line:D}),z.remaining--,v+=D.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(D)!==d&&g.length<l){let z={cursor:H,line:D};if(f>0&&h.length>0){z.before=h.slice();for(let de of z.before)v+=de.line.length}v+=D.length,g.push(z),m>0&&y.push({match:z,remaining:m})}if(f>0)for(h.push({cursor:H,line:D});h.length>f;)h.shift();let E=g.length>=l&&y.length===0,B=v>=p;return E||B};for(let H=0;H<i.length;H++){if(i[H]!==10)continue;let D=i.subarray(b,H).toString("utf8"),R=r+b;if(b=H+1,A=b,C(R,D)){w=!0;break}}if(!w&&b<i.length&&this.closed){let H=i.subarray(b).toString("utf8"),D=r+b;C(D,H)&&(w=!0),A=i.length}let x=Math.min(r+A,this.writeCursor),_={matches:g,truncated:w,nextCursor:x,scannedBytes:A};return o>0&&(_.gap=o),this.closed&&x>=this.writeCursor&&(_.eof=!0),_}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<t&&this.storage.copy(s,o,0,t-o),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>vr.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var Le=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],kf=new Map(Le.map(n=>[n.verb,n]));function br(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function qe(n,e){return Nn(n,e.map(t=>t.modelId))}function Nn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=br(n),s=e.filter(o=>br(o)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}function Ir(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let c=jn(u);if(c?.sessionUpdate!=="tool_call_update")continue;let d=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(d!==void 0&&(e.set(d,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(d,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let l=t.get(d);l?l.push(...c.content):t.set(d,[...c.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let c=jn(u);if(!c||typeof c.sessionUpdate!="string"){r.push(u),o=null;continue}let d=c.sessionUpdate;if(d==="agent_message_chunk"||d==="agent_thought_chunk"||d==="user_message_chunk"){o&&o.kind===d?Na(r,o.outIndex,Ha(c.content)):(r.push(u),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&e.get(l)!==a)continue;let p=l!==void 0&&t.has(l)?ja(u,t.get(l)??[]):u;l!==void 0&&s.has(l)&&!Ba(p)&&(p=Ua(p,s.get(l))),r.push(p);continue}if(d==="plan"){i!==null?r[i]=u:(r.push(u),i=r.length-1);continue}(d==="prompt_received"||d==="turn_complete")&&(i=null),r.push(u)}return r}function jn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ha(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Na(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...s,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function ja(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Ba(n){let t=jn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Ua(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Sr=`[older history truncated]
20
- `,Da=["file_path","filePath","path","command","pattern","query"];function ze(n,e={}){let t=e.maxChars??4e5,s=[],r="",o=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let i of n){if(i.method!=="session/update")continue;let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let c=u.sessionUpdate;if(c==="prompt_received"){o();let d=Un(u.prompt).trim();d.length>0&&s.push(`User: ${d}`)}else if(c==="agent_message_chunk"){let d=Dn(u.content);d.length>0&&(r+=d)}else c==="tool_call"?(o(),s.push(Bn(u))):c==="turn_complete"&&o()}return o(),Ja(s.join(`
21
- `),t)}function Bn(n){let e=La(n),t=qa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function La(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function qa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Da){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${za(r,200)}`)}return t}function Un(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function Dn(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function za(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Ja(n,e){if(n.length<=e)return n;let t=n.split(`
22
- `);for(;t.length>0;){let s=Sr+t.join(`
23
- `);if(s.length<=e)return s;t.shift()}return Sr}var kr="(untitled)";function Ln(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??kr}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let i=ct("Open threads",t.open_threads);i.length>0&&e.push(i);let a=ct("Decisions",t.decisions);a.length>0&&e.push(a);let u=ct("File edit intentions",t.file_edit_intentions);u.length>0&&e.push(u);let c=ct("Unresolved errors",t.unresolved_errors);c.length>0&&e.push(c);let d=ct("Tool state",t.tool_state);d.length>0&&e.push(d);let l=Ar(t.files_touched);l.length>0&&e.push(`[Files previously touched] ${l}`);let p=Ar(t.tools_used);p.length>0&&e.push(`[Tools previously used] ${p}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??kr}`);let{closedText:s,openText:r,keptCount:o}=Wa(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+o+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
24
- `)}function ct(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
25
- `)}`}function Ar(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Wa(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Qa(n),i=0,a=[];if(e>0&&r.length>0){let d=r.filter(f=>f.startEntryIndex>=t).length,l=Math.max(d,s),p=Math.min(l,e,r.length);i=p,a=p>0?r.slice(-p):[]}let u=a.length>0?Cr(a):"",c=o?Cr([o]):"";return{closedText:u,openText:c,keptCount:i}}function Cr(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
26
- `)}function Qa(n){let e=[],t=null;for(let r=0;r<n.length;r++){let o=n[r];if(o.method!=="session/update")continue;let a=o.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let u=a.sessionUpdate;if(u==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Un(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(u==="agent_message_chunk"&&t!==null){let c=Dn(a.content);c.length>0&&(t.agent+=c)}else u==="tool_call"&&t!==null?t.tools.push(Bn(a)):u==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}import*as pe from"fs/promises";async function ut(n,e){let t=I.queueFile(n);if(e.length===0){await pe.unlink(t).catch(()=>{});return}await pe.mkdir(I.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
19
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},xa=2e3;function Ma(n){try{let e=I.agentLogFile(n);Ht.mkdirSync(wr.dirname(e),{recursive:!0});let t=Ht.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Te from"fs/promises";import*as Qt from"os";import*as wt from"path";import{customAlphabet as jd}from"nanoid";async function Be(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=n;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(u=>u.id).join(", ");return i?.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 i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Ue(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:o}=n;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as _r}from"nanoid";import*as br from"fs/promises";var Ra=64*1024*1024,Ea=1*1024*1024,De=64*1024,Pa=6e4,Ta=100,_a=1e3,$a=64*1024,Fa=256*1024,vr=20;function Oa(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Nt=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??Ra,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ea,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,De));if(s===0){let l={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(l.eof=!0),l}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let l={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(l.gap=o),this.closed&&(l.eof=!0),l}let u=Math.min(a,s),d={bytes:this.sliceFromRing(r,u),nextCursor:r+u};return o>0&&(d.gap=o),this.closed&&r+u>=this.writeCursor&&(d.eof=!0),d}tail(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Pa));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,o=0;s!==void 0&&s<t&&(o=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,u=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,u):new RegExp(Oa(e.pattern),u),d=e.invert??!1,l=Math.max(1,Math.min(e.maxMatches??Ta,_a)),f=Math.max(1,Math.min(e.maxBytes??$a,Fa)),p=Math.max(0,Math.min(e.contextBefore??0,vr)),m=Math.max(0,Math.min(e.contextAfter??0,vr)),g=[],h=[],y=[],v=0,w=!1,b=0,A=0,C=(H,D)=>{for(let z of y)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:H,line:D}),z.remaining--,v+=D.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(D)!==d&&g.length<l){let z={cursor:H,line:D};if(p>0&&h.length>0){z.before=h.slice();for(let de of z.before)v+=de.line.length}v+=D.length,g.push(z),m>0&&y.push({match:z,remaining:m})}if(p>0)for(h.push({cursor:H,line:D});h.length>p;)h.shift();let E=g.length>=l&&y.length===0,B=v>=f;return E||B};for(let H=0;H<i.length;H++){if(i[H]!==10)continue;let D=i.subarray(b,H).toString("utf8"),R=r+b;if(b=H+1,A=b,C(R,D)){w=!0;break}}if(!w&&b<i.length&&this.closed){let H=i.subarray(b).toString("utf8"),D=r+b;C(D,H)&&(w=!0),A=i.length}let x=Math.min(r+A,this.writeCursor),_={matches:g,truncated:w,nextCursor:x,scannedBytes:A};return o>0&&(_.gap=o),this.closed&&x>=this.writeCursor&&(_.eof=!0),_}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<t&&this.storage.copy(s,o,0,t-o),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>br.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var Le=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],Af=new Map(Le.map(n=>[n.verb,n]));function Ir(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function qe(n,e){return jn(n,e.map(t=>t.modelId))}function jn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=Ir(n),s=e.filter(o=>Ir(o)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}function Sr(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let c=Bn(u);if(c?.sessionUpdate!=="tool_call_update")continue;let d=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(d!==void 0&&(e.set(d,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(d,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let l=t.get(d);l?l.push(...c.content):t.set(d,[...c.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let c=Bn(u);if(!c||typeof c.sessionUpdate!="string"){r.push(u),o=null;continue}let d=c.sessionUpdate;if(d==="agent_message_chunk"||d==="agent_thought_chunk"||d==="user_message_chunk"){o&&o.kind===d?Na(r,o.outIndex,Ha(c.content)):(r.push(u),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&e.get(l)!==a)continue;let f=l!==void 0&&t.has(l)?ja(u,t.get(l)??[]):u;l!==void 0&&s.has(l)&&!Ba(f)&&(f=Ua(f,s.get(l))),r.push(f);continue}if(d==="plan"){i!==null?r[i]=u:(r.push(u),i=r.length-1);continue}(d==="prompt_received"||d==="turn_complete")&&(i=null),r.push(u)}return r}function Bn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ha(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Na(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...s,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function ja(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Ba(n){let t=Bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Ua(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var kr=`[older history truncated]
20
+ `,Da=["file_path","filePath","path","command","pattern","query"];function ze(n,e={}){let t=e.maxChars??4e5,s=[],r="",o=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let i of n){if(i.method!=="session/update")continue;let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let c=u.sessionUpdate;if(c==="prompt_received"){o();let d=Dn(u.prompt).trim();d.length>0&&s.push(`User: ${d}`)}else if(c==="agent_message_chunk"){let d=Ln(u.content);d.length>0&&(r+=d)}else c==="tool_call"?(o(),s.push(Un(u))):c==="turn_complete"&&o()}return o(),Ja(s.join(`
21
+ `),t)}function Un(n){let e=La(n),t=qa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function La(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function qa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Da){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${za(r,200)}`)}return t}function Dn(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function Ln(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function za(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Ja(n,e){if(n.length<=e)return n;let t=n.split(`
22
+ `);for(;t.length>0;){let s=kr+t.join(`
23
+ `);if(s.length<=e)return s;t.shift()}return kr}var Ar="(untitled)";function qn(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??Ar}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let i=dt("Open threads",t.open_threads);i.length>0&&e.push(i);let a=dt("Decisions",t.decisions);a.length>0&&e.push(a);let u=dt("File edit intentions",t.file_edit_intentions);u.length>0&&e.push(u);let c=dt("Unresolved errors",t.unresolved_errors);c.length>0&&e.push(c);let d=dt("Tool state",t.tool_state);d.length>0&&e.push(d);let l=Cr(t.files_touched);l.length>0&&e.push(`[Files previously touched] ${l}`);let f=Cr(t.tools_used);f.length>0&&e.push(`[Tools previously used] ${f}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??Ar}`);let{closedText:s,openText:r,keptCount:o}=Wa(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+o+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
24
+ `)}function dt(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
25
+ `)}`}function Cr(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Wa(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Qa(n),i=0,a=[];if(e>0&&r.length>0){let d=r.filter(p=>p.startEntryIndex>=t).length,l=Math.max(d,s),f=Math.min(l,e,r.length);i=f,a=f>0?r.slice(-f):[]}let u=a.length>0?xr(a):"",c=o?xr([o]):"";return{closedText:u,openText:c,keptCount:i}}function xr(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
26
+ `)}function Qa(n){let e=[],t=null;for(let r=0;r<n.length;r++){let o=n[r];if(o.method!=="session/update")continue;let a=o.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let u=a.sessionUpdate;if(u==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Dn(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(u==="agent_message_chunk"&&t!==null){let c=Ln(a.content);c.length>0&&(t.agent+=c)}else u==="tool_call"&&t!==null?t.tools.push(Un(a)):u==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}import*as pe from"fs/promises";async function ct(n,e){let t=I.queueFile(n);if(e.length===0){await pe.unlink(t).catch(()=>{});return}await pe.mkdir(I.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
27
27
  `)+`
28
- `;await pe.writeFile(t,s,"utf8")}async function xr(n){let e=I.queueFile(n),t;try{t=await pe.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
29
- `))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Mr(n){let e=I.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as Or from"fs/promises";var _r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",$r=Tr(_r,16),qn=Tr(_r,16),Va=20,Ka=20,Ga=5,ye="hydra_session_";function ke(){return`m_${$r()}`}function Fr(n){return n.startsWith(ye)?n.slice(ye.length):n}var Ya=1e3,Bt=300*1e3,Xa=64,Pe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${ye}${$r()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Ya,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){rd(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=Er(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let o=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let d=s;d<this.transformChain.length;d++){let l=this.transformChain[d];if(t.has(l.name)||!l.intercepts.has(a))continue;let p=`t_${qn()}`,f;try{f=await l.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(g){this.logger?.warn(`transformer ${l.name} error on ${a}: ${g.message}`);continue}let m=f?.action??"continue";if(m==="stop")return;if(m==="processing"){let g=d,h=i,y=new Set(t),v=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:l.name}),this.runResponseChain(h,new Set([...y,l.name]),g+1,v).then(()=>w()).catch(()=>w()))},Bt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:l.name,method:v,envelope:h,chainIdx:g,originatedBy:y,side:"response"})});return}f?.payload&&typeof f.payload=="object"&&(i=f.payload),t.add(l.name)}if(r!=="session/update")return;let u=od(i);if(u!==null){this.setAgentAdvertisedCommands(u);return}let c=sd(i);if(c!==null){this.setAgentAdvertisedModes(c);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(o)){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 t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,o=r!==this.agentId,i=this.cwd,a=this.agentArgs,u=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=this.spawnReplacementAgent;if(!l)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],f=await l({agentId:r,cwd:i,agentArgs:a,...u?{forwardedEnv:u}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(f.agent),o||(await Ue({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedModel:c,agentReportedModel:f.initialModel,logger:this.logger}),await Be({agent:f.agent,upstreamSessionId:f.upstreamSessionId,persistedMode:d,agentReportedMode:f.initialMode,logger:this.logger})),f.agent.connection.drainBuffered("session/update");let m=[];if(this.historyStore)try{m=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let g=Ln({synopsis:e.artifact,title:e.title,tail:m,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await f.agent.connection.request("session/prompt",{sessionId:f.upstreamSessionId,prompt:[{type:"text",text:g}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${g.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let h=this.upstreamSessionId,y=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=f.agent,this.upstreamSessionId=f.upstreamSessionId,this.agentMeta=f.agentMeta,this.agentCapabilities=f.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=f.initialModel,this.currentMode=f.initialMode,this.setAgentAdvertisedModels(f.initialModels??[]),this.setAgentAdvertisedModes(f.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(C){this.logger?.warn(`swapUpstream: agentChange handler failed: ${C.message}`)}if(!o&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...y!==void 0?{previousSummarizedThroughEntry:y}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),o||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),o&&this.broadcastAgentSwitch(s,r);let w=o?`
28
+ `;await pe.writeFile(t,s,"utf8")}async function Mr(n){let e=I.queueFile(n),t;try{t=await pe.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
29
+ `))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Rr(n){let e=I.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as Hr from"fs/promises";var $r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Fr=_r($r,16),zn=_r($r,16),Va=20,Ka=20,Ga=5,ye="hydra_session_";function Ae(){return`m_${Fr()}`}function Or(n){return n.startsWith(ye)?n.slice(ye.length):n}var Ya=1e3,jt=300*1e3,Xa=64,Pe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${ye}${Fr()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Ya,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){rd(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=Pr(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let o=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let d=s;d<this.transformChain.length;d++){let l=this.transformChain[d];if(t.has(l.name)||!l.intercepts.has(a))continue;let f=`t_${zn()}`,p;try{p=await l.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(g){this.logger?.warn(`transformer ${l.name} error on ${a}: ${g.message}`);continue}let m=p?.action??"continue";if(m==="stop")return;if(m==="processing"){let g=d,h=i,y=new Set(t),v=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:l.name}),this.runResponseChain(h,new Set([...y,l.name]),g+1,v).then(()=>w()).catch(()=>w()))},jt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(f,{resolve:()=>w(),timer:b,transformerName:l.name,method:v,envelope:h,chainIdx:g,originatedBy:y,side:"response"})});return}p?.payload&&typeof p.payload=="object"&&(i=p.payload),t.add(l.name)}if(r!=="session/update")return;let u=od(i);if(u!==null){this.setAgentAdvertisedCommands(u);return}let c=sd(i);if(c!==null){this.setAgentAdvertisedModes(c);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(o)){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 t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,o=r!==this.agentId,i=this.cwd,a=this.agentArgs,u=this.forwardedEnv,c=this.currentModel,d=this.currentMode,l=this.spawnReplacementAgent;if(!l)throw new Error("agent spawning not configured for this session");let f=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],p=await l({agentId:r,cwd:i,agentArgs:a,...u?{forwardedEnv:u}:{},mcpServers:f});this.accumulateAndResetCost(),this.wireAgent(p.agent),o||(await Ue({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedModel:c,agentReportedModel:p.initialModel,logger:this.logger}),await Be({agent:p.agent,upstreamSessionId:p.upstreamSessionId,persistedMode:d,agentReportedMode:p.initialMode,logger:this.logger})),p.agent.connection.drainBuffered("session/update");let m=[];if(this.historyStore)try{m=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let g=qn({synopsis:e.artifact,title:e.title,tail:m,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await p.agent.connection.request("session/prompt",{sessionId:p.upstreamSessionId,prompt:[{type:"text",text:g}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${g.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let h=this.upstreamSessionId,y=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let v=this.agent;this.agent=p.agent,this.upstreamSessionId=p.upstreamSessionId,this.agentMeta=p.agentMeta,this.agentCapabilities=p.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=p.initialModel,this.currentMode=p.initialMode,this.setAgentAdvertisedModels(p.initialModels??[]),this.setAgentAdvertisedModes(p.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(C){this.logger?.warn(`swapUpstream: agentChange handler failed: ${C.message}`)}if(!o&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...y!==void 0?{previousSummarizedThroughEntry:y}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await v.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),o||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),o&&this.broadcastAgentSwitch(s,r);let w=o?`
30
30
  Switched to ${r}.
31
31
  `:`
32
32
  Compaction completed.
33
- `,b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:w},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.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,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,u=this.currentModel,c=this.currentMode,d=await s(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(d.agent),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:u,agentReportedModel:d.initialModel,logger:this.logger}),await Be({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:c,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let l=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await l.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let p of this.agentChangeHandlers)try{p({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(f){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${f.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Va){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of s){let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let c=u.sessionUpdate,d=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(d){if(c==="tool_call")r.add(d);else if(c==="tool_call_update"){let l=u.status;(l==="completed"||l==="failed")&&o.add(d)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw ne(new Error("session is closed"),k.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),k.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Ir(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Rr(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Jn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...s(o)],appliedPolicy:"full"}:{entries:[...i,...s(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),k.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),k.SessionClosing);let r=ke();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(dt((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let i of this.interactiveHandlers)try{i(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Je(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:ke()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Xa;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),k.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let u=this.promptQueue.find(d=>d.messageId===r&&d.kind==="user");if(u&&u.kind==="user"&&!u.cancelled)return u.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let o=ke(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let u=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}u.push(c)}this.promptQueue=u}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let s=ke(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw ne(new Error("client not attached"),k.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name))continue;let c=`request:${e}`;if(!u.intercepts.has(c))continue;let d=`t_${qn()}`,l;try{l=await u.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(f){this.logger?.warn(`transformer ${u.name} error on ${c}: ${f.message}`);continue}let p=l?.action??"continue";if(p==="stop")return o==="notification"?void 0:l?.payload??zn(e);if(p==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(u.name);continue}if(p==="processing"){let f=a,m=i,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:u.name}),this.forwardRequest(e,m,new Set([...g,u.name]),f+1,o).then(h).catch(()=>h(o==="notification"?void 0:zn(e))))},Bt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(d,{resolve:h,timer:y,transformerName:u.name,method:e,envelope:m,chainIdx:f,originatedBy:g,side:"request",tailKind:o})})}s.add(u.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async runAgentRequestChain(e,t,s=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name)||!u.intercepts.has(i))continue;let c=`t_${qn()}`,d;try{d=await u.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${u.name} error on ${i}: ${p.message}`);continue}let l=d?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:d?.payload??ud(e)};if(l==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(u.name);continue}if(l==="processing"){let p=a,f=o,m=new Set(s),g=e;return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:u.name}),this.runAgentRequestChain(g,f,new Set([...m,u.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:f})))},Bt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:v=>h({shortCircuit:!0,payload:v}),timer:y,transformerName:u.name,method:g,envelope:f,chainIdx:p,originatedBy:m,side:"agent-request"})})}s.add(u.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):Bt,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let i=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,i).then(s.resolve).catch(()=>s.resolve(i==="notification"?void 0:zn(s.method)))}},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(t,s,i,o)}async emitToQueue(e,t){let s=this.transformChain.findIndex(c=>c.name===e),r=s>=0?s+1:0,o=(t??{}).prompt??[],i=ke(),a=`transformer:${e}`,u={clientId:a,name:e};return new Promise((c,d)=>{let l={kind:"user",messageId:i,originator:u,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:c,reject:d},p=this.insertEntryAt(l,"tail");this.persistRewrite(),this.broadcastQueueAdded(l,{position:p}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Je((e??{}).prompt),r=Wn(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=We(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}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 o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=We(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let u=i.currentValue;if(typeof u=="string"){let c=u.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(i.id==="mode"){let a=lt(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let u=i.currentValue;if(typeof u=="string"){let c=u.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),u=We(i.options);if(u.length>0){let c=lt(i.options),d=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):u.map(h=>({value:h.modelId,name:h.name??h.modelId})),l=i.name,p=typeof l=="string"&&l.trim()?l.trim():a,f=i.currentValue,m=typeof f=="string"&&f.trim()?f.trim():d[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=d,typeof f=="string"&&f.trim()&&(h.currentValue=f.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:m,options:d})}}}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 o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let o={};typeof s.costAmount=="number"&&(o.amount=s.costAmount),typeof s.costCurrency=="string"&&(o.currency=s.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(ed(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(td(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),nd(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of Le){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let u=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&u.length>0){let c=r.verb?`hydra ${u} ${r.verb}`:`hydra ${u}`,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}if(u.length>0&&t.get(u)===s){let c=r.verb?`${u} ${r.verb}`:u,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name);a&&e.add(a)}let s=new Map;for(let i of Le)e.has(i.verb)||s.set(i.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||s.has(a))continue;let u=r.get(a);u===void 0?r.set(a,i):u!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&s.set(i,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(Le.some(l=>l.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return a?this.runAgentCommandInline(i):this.runAgentCommand(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let l=new Error(`no dispatcher for /hydra verb ${o}`);throw l.code=k.InternalError,l}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let u=`hydra-acp-${o}`;if(this.extensionCommands?.has(u))return a?this.runExtensionCommandInline(u,i,t):this.runExtensionCommand(u,i);let c=Le.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:p}of this.extensionCommands.list())l.has(p)||(c.push(p),l.add(p))}let d=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw d.code=k.InvalidParams,d}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(m=>m.verb===i)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let u={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(u.messageId=s);let c=()=>{},d=new Promise(m=>{c=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>c({stopReason:"cancelled",reason:m})});let l,p=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",u),g=await Promise.race([m,d]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let f=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return f.length>0?this.emitExtensionReply(f):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
33
+ `,b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:w},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.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,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,u=this.currentModel,c=this.currentMode,d=await s(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(d.agent),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:u,agentReportedModel:d.initialModel,logger:this.logger}),await Be({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:c,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let l=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await l.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=Va){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of s){let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let c=u.sessionUpdate,d=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(d){if(c==="tool_call")r.add(d);else if(c==="tool_call_update"){let l=u.status;(l==="completed"||l==="failed")&&o.add(d)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw ne(new Error("session is closed"),k.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),k.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Sr(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Er(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Wn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...s(o)],appliedPolicy:"full"}:{entries:[...i,...s(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),k.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),k.SessionClosing);let r=Ae();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(at((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let i of this.interactiveHandlers)try{i(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Je(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Ae()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Xa;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),k.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let u=this.promptQueue.find(d=>d.messageId===r&&d.kind==="user");if(u&&u.kind==="user"&&!u.cancelled)return u.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let c=this.recentlyTerminal.get(r);return c?c.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let o=Ae(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let u=[];for(let c of this.promptQueue){if(c.kind==="user"&&!c.cancelled){c.cancelled=!0,this.broadcastQueueRemoved(c.messageId,"cancelled"),c.resolve({stopReason:"cancelled"});continue}u.push(c)}this.promptQueue=u}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let s=Ae(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw ne(new Error("client not attached"),k.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name))continue;let c=`request:${e}`;if(!u.intercepts.has(c))continue;let d=`t_${zn()}`,l;try{l=await u.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${u.name} error on ${c}: ${p.message}`);continue}let f=l?.action??"continue";if(f==="stop")return o==="notification"?void 0:l?.payload??Jn(e);if(f==="continue"){l?.payload&&typeof l.payload=="object"&&(i=l.payload),s.add(u.name);continue}if(f==="processing"){let p=a,m=i,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:u.name}),this.forwardRequest(e,m,new Set([...g,u.name]),p+1,o).then(h).catch(()=>h(o==="notification"?void 0:Jn(e))))},jt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(d,{resolve:h,timer:y,transformerName:u.name,method:e,envelope:m,chainIdx:p,originatedBy:g,side:"request",tailKind:o})})}s.add(u.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async runAgentRequestChain(e,t,s=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name)||!u.intercepts.has(i))continue;let c=`t_${zn()}`,d;try{d=await u.connection.request("hydra-acp/transformer/message",{token:c,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(f){this.logger?.warn(`transformer ${u.name} error on ${i}: ${f.message}`);continue}let l=d?.action??"continue";if(l==="stop")return{shortCircuit:!0,payload:d?.payload??ud(e)};if(l==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(u.name);continue}if(l==="processing"){let f=a,p=o,m=new Set(s),g=e;return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:u.name}),this.runAgentRequestChain(g,p,new Set([...m,u.name]),f+1).then(h).catch(()=>h({shortCircuit:!1,envelope:p})))},jt);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(c,{resolve:v=>h({shortCircuit:!0,payload:v}),timer:y,transformerName:u.name,method:g,envelope:p,chainIdx:f,originatedBy:m,side:"agent-request"})})}s.add(u.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):jt,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let i=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,i).then(s.resolve).catch(()=>s.resolve(i==="notification"?void 0:Jn(s.method)))}},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(t,s,i,o)}async emitToQueue(e,t){let s=this.transformChain.findIndex(c=>c.name===e),r=s>=0?s+1:0,o=(t??{}).prompt??[],i=Ae(),a=`transformer:${e}`,u={clientId:a,name:e};return new Promise((c,d)=>{let l={kind:"user",messageId:i,originator:u,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:c,reject:d},f=this.insertEntryAt(l,"tail");this.persistRewrite(),this.broadcastQueueAdded(l,{position:f}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Je((e??{}).prompt),r=Qn(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=We(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}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 o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=We(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let u=i.currentValue;if(typeof u=="string"){let c=u.trim();c&&c!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(c)}`),this.applyModelChange(c))}}else if(i.id==="mode"){let a=ut(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let u=i.currentValue;if(typeof u=="string"){let c=u.trim();c&&c!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(c)}`),this.applyModeChange(c))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),u=We(i.options);if(u.length>0){let c=ut(i.options),d=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):u.map(h=>({value:h.modelId,name:h.name??h.modelId})),l=i.name,f=typeof l=="string"&&l.trim()?l.trim():a,p=i.currentValue,m=typeof p=="string"&&p.trim()?p.trim():d[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=d,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:m,options:d})}}}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 o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let o={};typeof s.costAmount=="number"&&(o.amount=s.costAmount),typeof s.costCurrency=="string"&&(o.currency=s.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(ed(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(td(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),nd(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of Le){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let u=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&u.length>0){let c=r.verb?`hydra ${u} ${r.verb}`:`hydra ${u}`,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}if(u.length>0&&t.get(u)===s){let c=r.verb?`${u} ${r.verb}`:u,l={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(l.description=r.description),e.push(l)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name);a&&e.add(a)}let s=new Map;for(let i of Le)e.has(i.verb)||s.set(i.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||s.has(a))continue;let u=r.get(a);u===void 0?r.set(a,i):u!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&s.set(i,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(Le.some(l=>l.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return a?this.runAgentCommandInline(i):this.runAgentCommand(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let l=new Error(`no dispatcher for /hydra verb ${o}`);throw l.code=k.InternalError,l}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let u=`hydra-acp-${o}`;if(this.extensionCommands?.has(u))return a?this.runExtensionCommandInline(u,i,t):this.runExtensionCommand(u,i);let c=Le.map(l=>l.verb);if(this.extensionCommands){let l=new Set;for(let{name:f}of this.extensionCommands.list())l.has(f)||(c.push(f),l.add(f))}let d=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw d.code=k.InvalidParams,d}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(m=>m.verb===i)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let u={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(u.messageId=s);let c=()=>{},d=new Promise(m=>{c=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>c({stopReason:"cancelled",reason:m})});let l,f=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",u),g=await Promise.race([m,d]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return f=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};l=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=l&&typeof l=="object"&&typeof l.text=="string"?l.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
34
34
  ${e}
35
35
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",u=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${u}`});e=`Sessions (${t.length}):
36
36
  ${s.join(`
@@ -40,7 +40,7 @@ ${e}
40
40
  ${t.join(`
41
41
  `)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
42
42
  ${s}
43
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let u=i?o.some(d=>d.modelId===i):!0,c=o.map(d=>{let l=d.modelId===i?"\u25B6 ":" ",p=d.name&&d.name!==d.modelId?` ${d.name}`:"";return`${l}${d.modelId}${p}`});!u&&i&&c.unshift(`\u25B6 ${i}`),a=c.join(`
43
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let u=i?o.some(d=>d.modelId===i):!0,c=o.map(d=>{let l=d.modelId===i?"\u25B6 ":" ",f=d.name&&d.name!==d.modelId?` ${d.name}`:"";return`${l}${d.modelId}${f}`});!u&&i&&c.unshift(`\u25B6 ${i}`),a=c.join(`
44
44
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
45
45
  ${a}
46
46
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=qe(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let o=this.agentAdvertisedModels.map(l=>l.modelId),i=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:o.filter(l=>l.toLowerCase().includes(i)),u=a.length>0?a:o,c=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,d=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:`
@@ -53,7 +53,7 @@ ${d}:
53
53
  ${i}
54
54
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(o=>o.id).join(", ");throw ne(new Error(`unknown mode: ${t} (known: ${r})`),k.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[2]??"";if(!s){let d=this.buildConfigOptions();if(d.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
55
55
  _(no config options advertised yet)_
56
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let l=d.map(p=>Pr(p));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
56
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let l=d.map(f=>Tr(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
57
  ${l.join(`
58
58
 
59
59
  `)}
@@ -63,18 +63,18 @@ ${l.join(`
63
63
  Available options:
64
64
  ${d}
65
65
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
66
- ${Pr(i)}
67
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(d=>d.value),u=Nn(r,a),c=r;if(u.kind==="resolved")c=u.modelId;else if(u.kind==="ambiguous"||u.kind==="unknown"){let d=r.toLowerCase(),l=u.kind==="ambiguous"?u.candidates:a.filter(g=>g.toLowerCase().includes(d)),p=l.length>0?l:a,f=u.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${u.candidates.join(", ")}`:l.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=u.kind==="ambiguous"||l.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
68
- ${f}.
66
+ ${Tr(i)}
67
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(d=>d.value),u=jn(r,a),c=r;if(u.kind==="resolved")c=u.modelId;else if(u.kind==="ambiguous"||u.kind==="unknown"){let d=r.toLowerCase(),l=u.kind==="ambiguous"?u.candidates:a.filter(g=>g.toLowerCase().includes(d)),f=l.length>0?l:a,p=u.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${u.candidates.join(", ")}`:l.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=u.kind==="ambiguous"||l.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
68
+ ${p}.
69
69
  ${m}:
70
- ${p.join(`
70
+ ${f.join(`
71
71
  `)}
72
72
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(c!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:c}),this.applyModelChange(c),{stopReason:"end_turn"}):s==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):s==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:c}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw ne(new Error("/hydra agent requires an agent id"),k.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw ne(new Error(`already on agent ${r}`),k.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw ne(new Error("agent restart not configured for this session"),k.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),t=this._summarizedThroughEntry;if(e==null&&t==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
73
- `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ne(new Error("session is closing"),k.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=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 o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let i={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let l=(c.params??{}).update;if(!l||l._meta?.["hydra-acp"]?.synthetic)continue;let f=l.sessionUpdate;if(f==="prompt_received"){let m=Je(l.prompt);m&&s.push({speaker:"user",text:m})}else if(f==="agent_message_chunk"){let g=l.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(f==="tool_call"||f==="tool_call_update"){let m=l.status,g=l.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let o=[],i;for(let c of s)i&&i.speaker===c.speaker?i.text+=c.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:c.speaker,text:c.text});i&&o.push(`<${i.speaker}>: ${i.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,u=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,u,"","--- begin transcript ---",...o,"--- end transcript ---"].join(`
74
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=Ln({synopsis:e,title:t,tail:s,tailK:Ka,tailFloor:Ga,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new jt(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??De,De)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let u=await r.waitForData(i.nextCursor,s);(u==="data"||u==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=k.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let o of s){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Mr(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>Or.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(s))return;this.attentionFlags.set(o,{...i,payload:s,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!o)return;let i=typeof s.kind=="string"?s.kind:void 0;i&&!this.toolCallKind.has(o)&&this.toolCallKind.set(o,i);let a=i??this.toolCallKind.get(o);if(a==="edit"&&Array.isArray(s.locations))for(let d of s.locations){if(!d||typeof d!="object")continue;let l=d.path;if(typeof l!="string"||l.length===0||this.filesEditedSeen.has(l))continue;this.filesEditedSeen.add(l);let p=d.line,f={path:l,toolCallId:o};typeof p=="number"&&(f.line=p),this.notifyChain("file.edited",f)}if(r!=="tool_call_update")return;let u=typeof s.status=="string"?s.status:void 0;if(u!=="completed"&&u!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,u);let c={toolCallId:o,status:u};a&&(c.kind=a),s.content!==void 0&&(c.content=s.content),Array.isArray(s.locations)&&(c.locations=s.locations),this.notifyChain("tool.completed",c)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),o=!Rr(e,r),i=o?id(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ne(new Error("no clients attached to handle permission request"),k.PermissionDenied);let s=this.rewriteForClient(e),r=Er(s),o=ke(),{toolCall:i,options:a}=s??{};return new Promise((u,c)=>{let d=!1,l=[],p=0,f,m=this.sessionId,g=v=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),v())},h=v=>v?.code===k.MethodNotFound;function y(v){if(d)return;let w=v.connection.request("session/request_permission",s);l.push({client:v}),p++,w.then(b=>{p--,g(()=>{let A=ad({toolCallId:r,result:b,resolver:v});for(let C of l)C.client.clientId!==v.clientId&&C.client.connection.notify("session/update",{sessionId:m,update:A}).catch(()=>{});u(b)})}).catch(b=>{if(p--,h(b)||(f=b),p===0&&!d){let A=f??ne(new Error("no client handled permission request"),k.PermissionDenied);g(()=>c(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,y);for(let v of t)y(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:ke(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],o={clientId:e.clientId};e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version);let i=this.parseQueuePosition(t);return new Promise((a,u)=>{let c={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:u},d=this.insertEntryAt(c,i);this.persistRewrite(),this.broadcastQueueAdded(c,{position:d}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),s+o+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ut(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Je(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
- `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||o){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(o){let u=t.slice(s.length).trim(),c=u?`/hydra ${r} ${u}`:`/hydra ${r}`;a=await this.handleSlashCommand(c,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i;try{i=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function ne(n,e){return n.code=e,n}var Za=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]);function Rr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Za.has(s)}function ed(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function td(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function nd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function We(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function lt(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function sd(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function rd(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.chunks.push(o.text),n.messageChars+=o.text.length);return}if(r==="agent_thought_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.thinkingChars+=o.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function od(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function id(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:ke()}}}function Jn(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function Er(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function ad(n){let e=dd(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=cd(n.resolver),t}function dd(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function cd(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Je(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function zn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function ud(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Pr(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let o=r.value===n.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
73
+ `)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ne(new Error("session is closing"),k.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=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 o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let i={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let l=(c.params??{}).update;if(!l||l._meta?.["hydra-acp"]?.synthetic)continue;let p=l.sessionUpdate;if(p==="prompt_received"){let m=Je(l.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let g=l.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(p==="tool_call"||p==="tool_call_update"){let m=l.status,g=l.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let o=[],i;for(let c of s)i&&i.speaker===c.speaker?i.text+=c.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:c.speaker,text:c.text});i&&o.push(`<${i.speaker}>: ${i.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,u=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,u,"","--- begin transcript ---",...o,"--- end transcript ---"].join(`
74
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=qn({synopsis:e,title:t,tail:s,tailK:Ka,tailFloor:Ga,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Nt(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??De,De)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let u=await r.waitForData(i.nextCursor,s);(u==="data"||u==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=k.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let o of s){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Rr(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>Hr.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(s))return;this.attentionFlags.set(o,{...i,payload:s,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!o)return;let i=typeof s.kind=="string"?s.kind:void 0;i&&!this.toolCallKind.has(o)&&this.toolCallKind.set(o,i);let a=i??this.toolCallKind.get(o);if(a==="edit"&&Array.isArray(s.locations))for(let d of s.locations){if(!d||typeof d!="object")continue;let l=d.path;if(typeof l!="string"||l.length===0||this.filesEditedSeen.has(l))continue;this.filesEditedSeen.add(l);let f=d.line,p={path:l,toolCallId:o};typeof f=="number"&&(p.line=f),this.notifyChain("file.edited",p)}if(r!=="tool_call_update")return;let u=typeof s.status=="string"?s.status:void 0;if(u!=="completed"&&u!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,u);let c={toolCallId:o,status:u};a&&(c.kind=a),s.content!==void 0&&(c.content=s.content),Array.isArray(s.locations)&&(c.locations=s.locations),this.notifyChain("tool.completed",c)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),o=!Er(e,r),i=o?id(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ne(new Error("no clients attached to handle permission request"),k.PermissionDenied);let s=this.rewriteForClient(e),r=Pr(s),o=Ae(),{toolCall:i,options:a}=s??{};return new Promise((u,c)=>{let d=!1,l=[],f=0,p,m=this.sessionId,g=v=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),v())},h=v=>v?.code===k.MethodNotFound;function y(v){if(d)return;let w=v.connection.request("session/request_permission",s);l.push({client:v}),f++,w.then(b=>{f--,g(()=>{let A=ad({toolCallId:r,result:b,resolver:v});for(let C of l)C.client.clientId!==v.clientId&&C.client.connection.notify("session/update",{sessionId:m,update:A}).catch(()=>{});u(b)})}).catch(b=>{if(f--,h(b)||(p=b),f===0&&!d){let A=p??ne(new Error("no client handled permission request"),k.PermissionDenied);g(()=>c(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,y);for(let v of t)y(v)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ae(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],o={clientId:e.clientId};e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version);let i=this.parseQueuePosition(t);return new Promise((a,u)=>{let c={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:u},d=this.insertEntryAt(c,i);this.persistRewrite(),this.broadcastQueueAdded(c,{position:d}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),s+o+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ct(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Je(e.prompt).replace(/\s+$/,""),s=!t.includes(`
75
+ `)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||o){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(o){let u=t.slice(s.length).trim(),c=u?`/hydra ${r} ${u}`:`/hydra ${r}`;a=await this.handleSlashCommand(c,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i;try{i=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function ne(n,e){return n.code=e,n}var Za=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]);function Er(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Za.has(s)}function ed(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function td(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.id!==e[t]?.id||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function nd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function We(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function ut(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function sd(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function rd(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.chunks.push(o.text),n.messageChars+=o.text.length);return}if(r==="agent_thought_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.thinkingChars+=o.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function od(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function id(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:Ae()}}}function Wn(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function Pr(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function ad(n){let e=dd(n.result),t={sessionUpdate:"permission_resolved"};return n.toolCallId!==void 0&&(t.toolCallId=n.toolCallId),e&&(t.outcome=e,e.kind==="selected"&&typeof e.optionId=="string"&&(t.chosenOptionId=e.optionId)),t.resolvedBy=cd(n.resolver),t}function dd(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function cd(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Je(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Jn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function ud(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function Tr(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let o=r.value===n.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
76
76
  ${s.join(`
77
- `)}`}function Wn(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as Ke from"fs/promises";import*as Wf from"path";import{customAlphabet as pd}from"nanoid";import{z as P}from"zod";import{z as Qe}from"zod";var ld=Qe.object({source:Qe.string(),reason:Qe.string(),raisedAt:Qe.number(),payload:Qe.unknown()}),Hr=Qe.array(ld);import{z as q}from"zod";var Nr=q.object({status:q.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:q.number(),iter:q.number().int().nonnegative().optional(),attempts:q.number().int().nonnegative().optional(),lastError:q.string().optional(),worker:q.object({upstreamSessionId:q.string(),pid:q.number().int().nonnegative()}).optional()}),ft=q.object({goal:q.string().optional(),outcome:q.string().optional(),files_touched:q.array(q.string()).optional(),tools_used:q.array(q.string()).optional(),rejected_approaches:q.array(q.string()).optional(),open_threads:q.array(q.string()).optional(),decisions:q.array(q.string()).optional(),file_edit_intentions:q.array(q.string()).optional(),unresolved_errors:q.array(q.string()).optional(),tool_state:q.array(q.string()).optional()}),jr=200,Qn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
77
+ `)}`}function Qn(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as Ke from"fs/promises";import*as Qf from"path";import{customAlphabet as pd}from"nanoid";import{z as P}from"zod";import{z as Qe}from"zod";var ld=Qe.object({source:Qe.string(),reason:Qe.string(),raisedAt:Qe.number(),payload:Qe.unknown()}),Nr=Qe.array(ld);import{z as q}from"zod";var jr=q.object({status:q.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:q.number(),iter:q.number().int().nonnegative().optional(),attempts:q.number().int().nonnegative().optional(),lastError:q.string().optional(),worker:q.object({upstreamSessionId:q.string(),pid:q.number().int().nonnegative()}).optional()}),lt=q.object({goal:q.string().optional(),outcome:q.string().optional(),files_touched:q.array(q.string()).optional(),tools_used:q.array(q.string()).optional(),rejected_approaches:q.array(q.string()).optional(),open_threads:q.array(q.string()).optional(),decisions:q.array(q.string()).optional(),file_edit_intentions:q.array(q.string()).optional(),unresolved_errors:q.array(q.string()).optional(),tool_state:q.array(q.string()).optional()}),Br=200,Vn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
78
78
  {
79
79
  "title": "short summary, max 80 chars",
80
80
  "synopsis": {
@@ -84,7 +84,7 @@ ${s.join(`
84
84
  "open_threads": ["work started but not finished"]
85
85
  }
86
86
  }
87
- Use empty arrays/strings where a field doesn't apply.`;function Br(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Ve(e.slice(o,i+1)))}if(t===void 0){let o=Dr(e);o!==void 0&&(t=Ve(o))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let o=s.title.trim();o.length>0&&(r.title=o.slice(0,jr))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=ft.safeParse(s.synopsis);o.success&&fd(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var Vn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
87
+ Use empty arrays/strings where a field doesn't apply.`;function Ur(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Ve(e.slice(o,i+1)))}if(t===void 0){let o=Lr(e);o!==void 0&&(t=Ve(o))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let o=s.title.trim();o.length>0&&(r.title=o.slice(0,Br))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=lt.safeParse(s.synopsis);o.success&&fd(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var Kn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
88
88
  {
89
89
  "title": "short summary, max 80 chars",
90
90
  "goal": "the user's original ask",
@@ -96,50 +96,50 @@ Use empty arrays/strings where a field doesn't apply.`;function Br(n){let e=n.tr
96
96
  "unresolved_errors": ["errors left open at session end"],
97
97
  "tool_state": ["runtime state relevant for recall"]
98
98
  }
99
- Use empty arrays/strings where a field doesn't apply.`;function Ur(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let c=e.indexOf("{"),d=e.lastIndexOf("}");c>=0&&d>c&&(t=Ve(e.slice(c,d+1)))}if(t===void 0){let c=Dr(e);c!==void 0&&(t=Ve(c))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let c=s.title.trim();c.length>0&&(r.title=c.slice(0,jr))}let o={},i=!1,a=["goal","outcome"];for(let c of a)if(typeof s[c]=="string"){let d=s[c].trim();d.length>0&&(o[c]=d,i=!0)}let u=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let c of u)if(Array.isArray(s[c])){let d=s[c],l=q.array(q.string()).safeParse(d);l.success&&d.length>0&&(o[c]=l.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ve(n){try{return JSON.parse(n)}catch{return}}function Dr(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let o=e;o<n.length;o++){let i=n[o];if(s){r?r=!1:i==="\\"?r=!0:i==='"'&&(s=!1);continue}if(i==='"'){s=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function fd(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var md="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gd=pd(md,16),hd="hydra_lineage_";function pt(){return`${hd}${gd()}`}var Gn=P.object({name:P.string(),description:P.string().optional()}),Yn=P.object({id:P.string(),name:P.string().optional(),description:P.string().optional()}),yd=P.object({modelId:P.string(),name:P.string().optional(),description:P.string().optional()}),Xn=P.object({used:P.number().optional(),size:P.number().optional(),costAmount:P.number().optional(),costCurrency:P.string().optional(),cumulativeCost:P.number().optional()}),Zn=P.object({name:P.string(),version:P.string().optional()}),wd=P.object({previousUpstreamSessionId:P.string(),previousSummarizedThroughEntry:P.number().int().nonnegative().optional()}),vd=P.object({version:P.literal(1),sessionId:P.string(),lineageId:P.string().optional(),upstreamSessionId:P.string(),importedFromSessionId:P.string().optional(),importedFromUpstreamSessionId:P.string().optional(),importedFromMachine:P.string().optional(),agentId:P.string(),cwd:P.string(),title:P.string().optional(),synopsis:ft.optional(),compactionState:Nr.optional(),rollbackBreadcrumb:wd.optional(),summarizedThroughEntry:P.number().int().nonnegative().optional(),agentArgs:P.array(P.string()).optional(),currentModel:P.string().optional(),currentMode:P.string().optional(),currentUsage:Xn.optional(),agentCommands:P.array(Gn).optional(),agentModes:P.array(Yn).optional(),agentModels:P.array(yd).optional(),pendingHistorySync:P.boolean().optional(),pendingAgentSwap:P.string().optional(),parentSessionId:P.string().optional(),forkedFromSessionId:P.string().optional(),forkedFromMessageId:P.string().optional(),forkSynthesisState:P.enum(["running","failed"]).optional(),originatingClient:Zn.optional(),interactive:P.boolean().optional(),priority:P.number().int().nonnegative().optional(),forwardedEnv:P.record(P.string(),P.string()).optional(),attentionFlags:Hr.default([]).optional(),createdAt:P.string(),updatedAt:P.string()}),Kn=/^[A-Za-z0-9_-]+$/;function bd(n){if(!Kn.test(n))throw new Error(`unsafe session id: ${n}`)}var Ut=class{async write(e){bd(e.sessionId);let t={version:1,...e};await ae(I.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Kn.test(e))return;let t=await ue(I.sessionFile(e));if(t!==void 0)try{return vd.parse(t)}catch{return}}async delete(e){if(Kn.test(e)){try{await Ke.unlink(I.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ke.rmdir(I.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Ke.readdir(I.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}};function es(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var Id=me.object({version:me.literal(1),agentId:me.string(),upstreamSessionId:me.string(),deletedAt:me.string(),upstreamUpdatedAt:me.string().optional(),cwd:me.string().optional(),title:me.string().optional(),reason:me.enum(["user","expired"]).optional(),interactive:me.boolean().optional()}),Dt=class{async add(e){let t={version:1,...e};await ae(I.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(I.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=I.tombstoneFile(e,t),r=await ue(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return Id.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(I.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(I.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await we.readdir(I.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let t;try{t=await we.readdir(I.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function Lr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as eo from"fs/promises";import{fileURLToPath as Sd}from"url";import*as mt from"path";import*as Lt from"fs";function kd(){try{let n=mt.dirname(Sd(import.meta.url));for(let e=0;e<8;e+=1){let t=mt.join(n,"package.json");if(Lt.existsSync(t)){let r=JSON.parse(Lt.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=mt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var K=kd(),qt="hydra-acp-cat";var Ad=12e4;async function zr(n,e,t){let s=n.timeoutMs??Ad,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let u=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),c=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=c.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(d,r.pid),n.modelId){let m=xd(c);if(m.size===0||m.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(g){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${g.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let l=[];r.connection.onNotification("session/update",m=>{let g=Cd(m);g.length>0&&l.push(g)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let p=l.join(""),f=t(p);if(!f){let m=JSON.stringify(p.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${p.length} preview=${m})`);let g=p.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${p.length} chars): ${g}${p.length>120?"\u2026":""}`)}return f})();return await new Promise((u,c)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),u(void 0)},s),o.unref?.(),a.then(d=>{o&&clearTimeout(o),i||u(d)},d=>{o&&clearTimeout(o),i||c(d)})})}catch(a){let u=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${u}`),n.onFailure?.(`agent ${n.agentId} failed: ${u}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function zt(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
99
+ Use empty arrays/strings where a field doesn't apply.`;function Dr(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let c=e.indexOf("{"),d=e.lastIndexOf("}");c>=0&&d>c&&(t=Ve(e.slice(c,d+1)))}if(t===void 0){let c=Lr(e);c!==void 0&&(t=Ve(c))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let c=s.title.trim();c.length>0&&(r.title=c.slice(0,Br))}let o={},i=!1,a=["goal","outcome"];for(let c of a)if(typeof s[c]=="string"){let d=s[c].trim();d.length>0&&(o[c]=d,i=!0)}let u=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let c of u)if(Array.isArray(s[c])){let d=s[c],l=q.array(q.string()).safeParse(d);l.success&&d.length>0&&(o[c]=l.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ve(n){try{return JSON.parse(n)}catch{return}}function Lr(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let o=e;o<n.length;o++){let i=n[o];if(s){r?r=!1:i==="\\"?r=!0:i==='"'&&(s=!1);continue}if(i==='"'){s=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function fd(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var md="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gd=pd(md,16),hd="hydra_lineage_";function ft(){return`${hd}${gd()}`}var Yn=P.object({name:P.string(),description:P.string().optional()}),Xn=P.object({id:P.string(),name:P.string().optional(),description:P.string().optional()}),yd=P.object({modelId:P.string(),name:P.string().optional(),description:P.string().optional()}),Zn=P.object({used:P.number().optional(),size:P.number().optional(),costAmount:P.number().optional(),costCurrency:P.string().optional(),cumulativeCost:P.number().optional()}),es=P.object({name:P.string(),version:P.string().optional()}),wd=P.object({previousUpstreamSessionId:P.string(),previousSummarizedThroughEntry:P.number().int().nonnegative().optional()}),vd=P.object({version:P.literal(1),sessionId:P.string(),lineageId:P.string().optional(),upstreamSessionId:P.string(),importedFromSessionId:P.string().optional(),importedFromUpstreamSessionId:P.string().optional(),importedFromMachine:P.string().optional(),agentId:P.string(),cwd:P.string(),title:P.string().optional(),synopsis:lt.optional(),compactionState:jr.optional(),rollbackBreadcrumb:wd.optional(),summarizedThroughEntry:P.number().int().nonnegative().optional(),agentArgs:P.array(P.string()).optional(),currentModel:P.string().optional(),currentMode:P.string().optional(),currentUsage:Zn.optional(),agentCommands:P.array(Yn).optional(),agentModes:P.array(Xn).optional(),agentModels:P.array(yd).optional(),pendingHistorySync:P.boolean().optional(),pendingAgentSwap:P.string().optional(),parentSessionId:P.string().optional(),forkedFromSessionId:P.string().optional(),forkedFromMessageId:P.string().optional(),forkSynthesisState:P.enum(["running","failed"]).optional(),originatingClient:es.optional(),interactive:P.boolean().optional(),priority:P.number().int().nonnegative().optional(),forwardedEnv:P.record(P.string(),P.string()).optional(),attentionFlags:Nr.default([]).optional(),createdAt:P.string(),updatedAt:P.string()}),Gn=/^[A-Za-z0-9_-]+$/;function bd(n){if(!Gn.test(n))throw new Error(`unsafe session id: ${n}`)}var Bt=class{async write(e){bd(e.sessionId);let t={version:1,...e};await ae(I.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Gn.test(e))return;let t=await ue(I.sessionFile(e));if(t!==void 0)try{return vd.parse(t)}catch{return}}async delete(e){if(Gn.test(e)){try{await Ke.unlink(I.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ke.rmdir(I.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Ke.readdir(I.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}};function ts(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var Id=me.object({version:me.literal(1),agentId:me.string(),upstreamSessionId:me.string(),deletedAt:me.string(),upstreamUpdatedAt:me.string().optional(),cwd:me.string().optional(),title:me.string().optional(),reason:me.enum(["user","expired"]).optional(),interactive:me.boolean().optional()}),Ut=class{async add(e){let t={version:1,...e};await ae(I.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(I.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=I.tombstoneFile(e,t),r=await ue(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return Id.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(I.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(I.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await we.readdir(I.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let t;try{t=await we.readdir(I.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function qr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as to from"fs/promises";import{fileURLToPath as Sd}from"url";import*as pt from"path";import*as Dt from"fs";function kd(){try{let n=pt.dirname(Sd(import.meta.url));for(let e=0;e<8;e+=1){let t=pt.join(n,"package.json");if(Dt.existsSync(t)){let r=JSON.parse(Dt.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=pt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var K=kd(),Lt="hydra-acp-cat";var Ad=12e4;async function Jr(n,e,t){let s=n.timeoutMs??Ad,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let u=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),c=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=c.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(d,r.pid),n.modelId){let m=xd(c);if(m.size===0||m.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(g){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${g.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let l=[];r.connection.onNotification("session/update",m=>{let g=Cd(m);g.length>0&&l.push(g)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let f=l.join(""),p=t(f);if(!p){let m=JSON.stringify(f.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${f.length} preview=${m})`);let g=f.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${f.length} chars): ${g}${f.length>120?"\u2026":""}`)}return p})();return await new Promise((u,c)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),u(void 0)},s),o.unref?.(),a.then(d=>{o&&clearTimeout(o),i||u(d)},d=>{o&&clearTimeout(o),i||c(d)})})}catch(a){let u=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${u}`),n.onFailure?.(`agent ${n.agentId} failed: ${u}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function qt(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
100
100
 
101
101
  ${e}
102
102
 
103
- ${Qn}`:`${t}
103
+ ${Vn}`:`${t}
104
104
 
105
- ${Qn}`;return zr(n,s,Br)}async function Jr(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
105
+ ${Vn}`;return Jr(n,s,Ur)}async function Wr(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
106
106
 
107
107
  ${e}
108
108
 
109
- ${Vn}`:`${t}
109
+ ${Kn}`:`${t}
110
110
 
111
- ${Vn}`;return zr(n,s,Ur)}function Cd(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function xd(n){let e=new Set;qr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&qr(e,t.availableModels),e}function qr(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function Md(n){let e=new Map;for(let t of Gr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Vr(n){return Md(n).map(e=>e.name)}function Rd(n){let e=new Map;for(let t of Gr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Kr(n){return Rd(n).map(e=>e.path)}function Gr(n){let e=new Map,t=0;for(let s of n){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let u=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,c=e.get(u);c===void 0?(c={toolName:Wr(o),paths:new Set},e.set(u,c)):c.toolName=Wr(o);for(let d of Qr(o.rawInput,o.locations))c.paths.add(d);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let u of Qr(o.rawInput,o.locations))a.paths.add(u)}return e}function Wr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Qr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Ed=2,Jt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ed}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let u=s==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(u);if(!c){this.opts.logger?.warn(`synopsis: agent ${u} not in registry for session ${e}; skipping`);return}let d=await te(c,[],{npmRegistry:this.opts.npmRegistry}),l=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(l?o.currentModel:void 0):this.opts.synopsisModel,f=I.sessionDir(e);if(await eo.mkdir(f,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${u} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${f}`),s==="compaction"){let m=this.opts.compactionMaxIterations??3,g=0,h=a??0,y,v=0,w,b=Date.now(),A={targetAgentId:r},C=_=>this.opts.onCompactionStateChange?.(e,_,A)??Promise.resolve(),x=_=>{this.opts.broadcastHydraCompaction?.(e,_,A)};await C({status:"requested",requestedAt:b}),x({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{g++,this.opts.logger?.info(`synopsis: compaction iteration ${g} sessionId=${e} historyLen=${i.length} watermark=${h}`);let _=await this.opts.histories.load(e,{maxEntries:1/0});if(_.length===h)break;let H=await Jr({agentId:u,cwd:f,plan:d,history:_,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(R,E)=>{C({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:R,pid:E??0}})},onFailure:R=>{w=R}});if(H){let R=Yr(H.synopsis,_);R&&Xr(R)&&(await this.opts.persistSynopsis(e,R,_.length),y=R,v=_.length,w=void 0,await C({status:"running",requestedAt:b,iter:g}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:_.length}),await this.opts.onSynthesisArtifact?.(e,R,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${Zr(R)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(h=_.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(g<m);if(y)g>=m&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let _=w??(g===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${g} iteration(s)`);await C({status:"failed",requestedAt:b,iter:g,lastError:_}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:_})}}catch(_){let H=_ instanceof Error?_.message:String(_);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${H}`),await C({status:"failed",requestedAt:b,iter:g,lastError:H}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:H},{targetAgentId:r})}}else{let m=await zt({agentId:u,cwd:f,plan:d,history:i,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let g=Yr(m.synopsis,i);g&&Xr(g)?(await this.opts.persistSynopsis(e,g,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${Zr(g)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function Yr(n,e){let t=Kr(e),s=Vr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Xr(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function Zr(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Z from"fs/promises";function to(n){return n==="summary"?"summary":"inline"}var ts=256;function no(n,e){return e!=="summary"?n:n.map(Pd)}function Pd(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(so));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,u={};a.error!==void 0&&(u.error=ns(a.error)),a.metadata!==void 0&&(u.metadata=a.metadata),o.rawOutput=u}return{...n,params:{...t,update:o}}}function Td(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function so(n){if(Td(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=ns(e.text)),typeof e.content=="string"?t.content=ns(e.content):e.content&&typeof e.content=="object"&&(t.content=so(e.content)),t}function ns(n){if(typeof n=="string"&&n.length>ts){let e=n.length-ts;return`${n.slice(0,ts)}\u2026[+${e} chars omitted from summary export]`}return n}var _d=2048;function ro(n){let e=new Set,t=s=>{if(oo(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function oo(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function $d(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function os(n,e){if(!$d(n))return n;let t=n.params,s=t.update,r=await ss(s,e);return{...n,params:{...t,update:r}}}async function ss(n,e){if(typeof n=="string"){if(n.length<=_d)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await ss(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await ss(r,e);return t}return n}async function io(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await rs(t,e);return s===t?n:{...n,params:s}}async function rs(n,e){if(oo(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let o=await rs(r,e);o!==r&&(t=!0),s.push(o)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,o]of Object.entries(n)){let i=await rs(o,e);i!==o&&(t=!0),s[r]=i}return t?s:n}return n}var gt=/^[A-Za-z0-9_-]+$/,Fd=1e3,Wt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Fd}async append(e,t){if(gt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(I.sessionDir(e),{recursive:!0});let s=await os(t,o=>An(e,o)),r=JSON.stringify(s)+`
112
- `;await Z.appendFile(I.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(gt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(I.sessionDir(e),{recursive:!0});let s=[];for(let o of t)s.push(await os(o,i=>An(e,i)));let r=s.length===0?"":s.map(o=>JSON.stringify(o)).join(`
111
+ ${Kn}`;return Jr(n,s,Dr)}function Cd(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function xd(n){let e=new Set;zr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&zr(e,t.availableModels),e}function zr(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function Md(n){let e=new Map;for(let t of Yr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Kr(n){return Md(n).map(e=>e.name)}function Rd(n){let e=new Map;for(let t of Yr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Gr(n){return Rd(n).map(e=>e.path)}function Yr(n){let e=new Map,t=0;for(let s of n){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let u=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,c=e.get(u);c===void 0?(c={toolName:Qr(o),paths:new Set},e.set(u,c)):c.toolName=Qr(o);for(let d of Vr(o.rawInput,o.locations))c.paths.add(d);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let u of Vr(o.rawInput,o.locations))a.paths.add(u)}return e}function Qr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Vr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Ed=2,zt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ed}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let u=s==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,c=await this.opts.registry.getAgent(u);if(!c){this.opts.logger?.warn(`synopsis: agent ${u} not in registry for session ${e}; skipping`);return}let d=await te(c,[],{npmRegistry:this.opts.npmRegistry}),l=this.opts.compactionAgent===void 0&&r===void 0,f=s==="compaction"?this.opts.compactionModel??(l?o.currentModel:void 0):this.opts.synopsisModel,p=I.sessionDir(e);if(await to.mkdir(p,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${u} historyLen=${i.length} model=${JSON.stringify(f??"(default)")} cwd=${p}`),s==="compaction"){let m=this.opts.compactionMaxIterations??3,g=0,h=a??0,y,v=0,w,b=Date.now(),A={targetAgentId:r},C=_=>this.opts.onCompactionStateChange?.(e,_,A)??Promise.resolve(),x=_=>{this.opts.broadcastHydraCompaction?.(e,_,A)};await C({status:"requested",requestedAt:b}),x({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{g++,this.opts.logger?.info(`synopsis: compaction iteration ${g} sessionId=${e} historyLen=${i.length} watermark=${h}`);let _=await this.opts.histories.load(e,{maxEntries:1/0});if(_.length===h)break;let H=await Wr({agentId:u,cwd:p,plan:d,history:_,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:(R,E)=>{C({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:R,pid:E??0}})},onFailure:R=>{w=R}});if(H){let R=Xr(H.synopsis,_);R&&Zr(R)&&(await this.opts.persistSynopsis(e,R,_.length),y=R,v=_.length,w=void 0,await C({status:"running",requestedAt:b,iter:g}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:_.length}),await this.opts.onSynthesisArtifact?.(e,R,v,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${eo(R)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(h=_.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(g<m);if(y)g>=m&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${v} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let _=w??(g===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${g} iteration(s)`);await C({status:"failed",requestedAt:b,iter:g,lastError:_}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:_})}}catch(_){let H=_ instanceof Error?_.message:String(_);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${H}`),await C({status:"failed",requestedAt:b,iter:g,lastError:H}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:H},{targetAgentId:r})}}else{let m=await qt({agentId:u,cwd:p,plan:d,history:i,modelId:f,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let g=Xr(m.synopsis,i);g&&Zr(g)?(await this.opts.persistSynopsis(e,g,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${eo(g)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function Xr(n,e){let t=Gr(e),s=Kr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function Zr(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function eo(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Z from"fs/promises";function no(n){return n==="summary"?"summary":"inline"}var ns=256;function so(n,e){return e!=="summary"?n:n.map(Pd)}function Pd(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(ro));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,u={};a.error!==void 0&&(u.error=ss(a.error)),a.metadata!==void 0&&(u.metadata=a.metadata),o.rawOutput=u}return{...n,params:{...t,update:o}}}function Td(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function ro(n){if(Td(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=ss(e.text)),typeof e.content=="string"?t.content=ss(e.content):e.content&&typeof e.content=="object"&&(t.content=ro(e.content)),t}function ss(n){if(typeof n=="string"&&n.length>ns){let e=n.length-ns;return`${n.slice(0,ns)}\u2026[+${e} chars omitted from summary export]`}return n}var _d=2048;function oo(n){let e=new Set,t=s=>{if(io(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function io(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function $d(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function is(n,e){if(!$d(n))return n;let t=n.params,s=t.update,r=await rs(s,e);return{...n,params:{...t,update:r}}}async function rs(n,e){if(typeof n=="string"){if(n.length<=_d)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await rs(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await rs(r,e);return t}return n}async function ao(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await os(t,e);return s===t?n:{...n,params:s}}async function os(n,e){if(io(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let o=await os(r,e);o!==r&&(t=!0),s.push(o)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,o]of Object.entries(n)){let i=await os(o,e);i!==o&&(t=!0),s[r]=i}return t?s:n}return n}var mt=/^[A-Za-z0-9_-]+$/,Fd=1e3,Jt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Fd}async append(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(I.sessionDir(e),{recursive:!0});let s=await is(t,o=>Cn(e,o)),r=JSON.stringify(s)+`
112
+ `;await Z.appendFile(I.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(I.sessionDir(e),{recursive:!0});let s=[];for(let o of t)s.push(await is(o,i=>Cn(e,i)));let r=s.length===0?"":s.map(o=>JSON.stringify(o)).join(`
113
113
  `)+`
114
- `;await Z.writeFile(I.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(gt.test(e))return this.enqueue(e,async()=>{let s;try{s=await Z.readFile(I.historyFile(e),"utf8")}catch(i){if(i.code==="ENOENT")return;throw i}let r=s.split(`
114
+ `;await Z.writeFile(I.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(mt.test(e))return this.enqueue(e,async()=>{let s;try{s=await Z.readFile(I.historyFile(e),"utf8")}catch(i){if(i.code==="ENOENT")return;throw i}let r=s.split(`
115
115
  `).filter(i=>i.length>0);if(r.length<=t)return;let o=r.slice(-t);await Z.writeFile(I.historyFile(e),o.join(`
116
116
  `)+`
117
- `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!gt.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await Z.readFile(I.historyFile(e),"utf8")}catch(p){if(p.code==="ENOENT")return[];throw p}let i=[];for(let p of o.split(`
118
- `)){if(p.length===0)continue;let f;try{f=JSON.parse(p)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let m=f;typeof m.method=="string"&&typeof m.recordedAt=="number"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=t.maxEntries??this.maxEntries,u=i.length>a?i.slice(-a):i;if(!s)return u;let c=new Map,d=async p=>{let f=c.get(p);if(f!==void 0)return f;let m=await $t(e,p);return c.set(p,m),m},l=[];for(let p of u)l.push(await io(p,d));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(gt.test(e))return this.enqueue(e,async()=>{try{await Z.unlink(I.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Ws(e);try{await Z.rmdir(I.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};import{promises as ao}from"fs";import*as co from"path";async function uo(n,e){await ao.mkdir(co.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await ao.writeFile(n,t.length>0?t.join(`
117
+ `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!mt.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await Z.readFile(I.historyFile(e),"utf8")}catch(f){if(f.code==="ENOENT")return[];throw f}let i=[];for(let f of o.split(`
118
+ `)){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"&&i.push({method:m.method,params:m.params,recordedAt:m.recordedAt})}let a=t.maxEntries??this.maxEntries,u=i.length>a?i.slice(-a):i;if(!s)return u;let c=new Map,d=async f=>{let p=c.get(f);if(p!==void 0)return p;let m=await _t(e,f);return c.set(f,m),m},l=[];for(let f of u)l.push(await ao(f,d));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(mt.test(e))return this.enqueue(e,async()=>{try{await Z.unlink(I.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Qs(e);try{await Z.rmdir(I.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};import{promises as co}from"fs";import*as uo from"path";async function lo(n,e){await co.mkdir(uo.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await co.writeFile(n,t.length>0?t.join(`
119
119
  `)+`
120
- `:"")}import{z as U}from"zod";var Od=U.object({method:U.string(),params:U.unknown(),recordedAt:U.number()}),Hd=U.object({sessionId:U.string(),lineageId:U.string(),upstreamSessionId:U.string().optional(),agentId:U.string(),cwd:U.string(),title:U.string().optional(),synopsis:ft.optional(),summarizedThroughEntry:U.number().int().nonnegative().optional(),currentModel:U.string().optional(),currentMode:U.string().optional(),currentUsage:Xn.optional(),agentCommands:U.array(Gn).optional(),agentModes:U.array(Yn).optional(),interactive:U.boolean().optional(),originatingClient:Zn.optional(),priority:U.number().int().nonnegative().optional(),createdAt:U.string(),updatedAt:U.string()}),Nd=U.object({version:U.literal(1),exportedAt:U.string(),exportedFrom:U.object({hydraVersion:U.string(),machine:U.string(),hydraHost:U.string().optional()}),session:Hd,history:U.array(Od),promptHistory:U.array(U.string()).optional(),toolBlobs:U.record(U.string()).optional()});function ht(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function lo(n){return Nd.parse(n)}var fo=900*1e3,Bd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qt=jd(Bd,16),bt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>he.spawn(a)),this.store=s??new Ut,this.tombstones=r.tombstones??new Dt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Wt({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 o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new Jt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,u)=>{let c=this.get(a);if(c){await c.retitle(u);return}await this.persistTitle(a,u)},persistSynopsis:(a,u,c)=>this.persistSynopsis(a,u,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,u,c)=>{if(c.targetAgentId)return;let d=this.get(a);d&&(d.compactionState=u),await this.mutateRecord(a,{compactionState:u})},broadcastHydraCompaction:(a,u,c)=>{this.emitSwapPhase(a,c.targetAgentId,u)},onSynthesisArtifact:async(a,u,c,d)=>{await this.dispatchSynthesisSwap(a,u,c,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let o=this.get(e);if(!o){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let i=this.compactionTailK;try{if(await o.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(o,t,i,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let u=o.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,u)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let u=await this.store.read(e).catch(()=>{});u?.synopsis&&u.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,u.synopsis,u.summarizedThroughEntry,u.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,s,o.summarizedThroughEntry,i)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,o){try{let i=o?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:i,summarizedThroughEntry:r,...o?{newAgentId:o}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ne(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let o={...s.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let a=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Qt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:o});a.action==="stop"&&a.payload&&(o=a.payload)}catch{}s.agentCapabilities=o}let r=new Pe({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:o=>this.bootstrapAgent({...o,mcpServers:o.mcpServers??[]}),loadExistingAgentSession:(o,i)=>this.bootstrapAgentLoad(o,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:o=>this.scheduleCompaction(r.sessionId,o),resolveAgentId:async o=>(await this.registry.getAgent(o))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:o=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:o}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=k.AlreadyAttached,o}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let g=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw g.code=k.AgentNotInstalled,g}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await te(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),i;try{let g=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});i=g.agentCapabilities,o.authMethods=yt(g.authMethods)}catch(g){throw await o.kill().catch(()=>{}),Ae(g,o)}let a;try{let g=po(e.agentId,e.currentModel);a=await o.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...g&&{_meta:g}})}catch(g){if(g&&typeof g=="object"&&g.code===k.AuthRequired)throw await o.kill().catch(()=>{}),Ae(g,o);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
121
- `),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let u=us(a??{}),c=e.agentModes??as(cs(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(u)} advertisedModes=${JSON.stringify(c?.map(g=>g.id))}`);let d=await Be({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:u,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(d)} for sessionId=${e.hydraSessionId}`);let l=is(a??{}),p=as(ds(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(l)} advertisedModels=${JSON.stringify(p?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let f=await Ue({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:l,logger:this.logger});if(e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new Pe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:g.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(g,h)=>this.bootstrapAgentLoad(g,{...h,mcpServers:h.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:f,currentMode:d,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:p,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:g=>this.scheduleCompaction(m.sessionId,g),resolveAgentId:async g=>(await this.registry.getAgent(g))?.id,getCompactionState:()=>this.getCompactionState(m.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:g=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:g}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await Be({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let u=new Pe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:c.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(c,d)=>this.bootstrapAgentLoad(c,{...d,mcpServers:d.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,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(u.sessionId),scheduleCompaction:c=>this.scheduleCompaction(u.sessionId,c),resolveAgentId:async c=>(await this.registry.getAgent(c))?.id,getCompactionState:()=>this.getCompactionState(u.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(u.sessionId),uncompactHook:()=>this.performUncompact(u.sessionId),onCompactionSwapHook:c=>{this.mutateRecord(u.sessionId,{rollbackBreadcrumb:c}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(u.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(u),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${u.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?u.seedFromFork(e.synopsis).catch(()=>{}):u.seedFromImport().catch(()=>{}),u}async dirExists(e){try{return(await Te.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Y(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let f=new Error(`agent ${e} not found in registry`);throw f.code=k.AgentNotInstalled,f}let s=await te(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Vt.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}})}catch(f){throw await r.kill().catch(()=>{}),Ae(f,r)}if(r.authMethods=yt(o.authMethods),(o.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(f){throw await r.kill().catch(()=>{}),f}await r.kill().catch(()=>{});let u=new Set;for(let f of this.sessions.values())u.add(`${f.agentId}::${f.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let f of c)u.add(`${f.agentId}::${f.upstreamSessionId}`);let d=I.sessionsDir(),l=[],p=0;for(let f of a){let m=`${e}::${f.sessionId}`;if(u.has(m)){p+=1;continue}if(Ud(f.cwd,d)){p+=1;continue}let g=await this.tombstones.read(e,f.sessionId).catch(()=>{});if(g){if(!Lr(g,f.updatedAt)){p+=1;continue}await this.tombstones.remove(e,f.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${f.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}u.add(m);let h=`${ye}${Qt()}`,y=new Date().toISOString(),v=f.updatedAt??y,w={sessionId:h,lineageId:pt(),upstreamSessionId:f.sessionId,agentId:e,cwd:f.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};f.title!==void 0&&(w.title=f.title);let b=es(w);await this.store.write(b),l.push({version:1,...b})}return{synced:l,skipped:p}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let o=0;o<100;o+=1){let i={};s!==void 0&&(i.cursor=s);let a=await e.connection.request("session/list",i),u=Array.isArray(a.sessions)?a.sessions:[];for(let c of u){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let d={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(d.title=c.title),typeof c.updatedAt=="string"&&(d.updatedAt=c.updatedAt),t.push(d)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=k.AgentNotInstalled,o}let s=await te(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),i=o.agentCapabilities;r.authMethods=yt(o.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),u=a.sessionId;if(typeof u!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=is(a),d=ds(a),l=e.model??this.defaultModels[e.agentId];if(l&&l!==c){let m=qe(l,d),g=e.model!==void 0?`model=${JSON.stringify(l)}`:`defaultModels[${e.agentId}]=${JSON.stringify(l)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,u,l,g)&&(c=l);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(r,u,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(c=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${g} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=d.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let p=cs(a),f=us(a);return{agent:r,upstreamSessionId:u,agentMeta:a._meta,agentCapabilities:i,initialModel:c,initialModels:d.length>0?d:void 0,initialModes:p.length>0?p:void 0,initialMode:f}}catch(o){throw await r.kill().catch(()=>{}),Ae(go(o,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let i=new Error(`agent ${t.agentId} not found in registry`);throw i.code=k.AgentNotInstalled,i}let r=await te(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=yt(i.authMethods);let u=po(t.agentId,void 0),c=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...u&&{_meta:u}}),d=is(c),l=as(ds(c)),p=cs(c),f=us(c);return{agent:o,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:a,initialModel:d,initialModels:l,initialModes:p.length>0?p:void 0,initialMode:f}}catch(i){throw await o.kill().catch(()=>{}),Ae(go(i,o,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),o)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=s.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let u=new Error(`agent ${e} not found in registry`);throw u.code=k.AgentNotInstalled,u}let o=await te(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let u=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});a.authMethods=yt(u.authMethods)}catch(u){throw await a.kill().catch(()=>{}),Ae(u,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=k.AgentNotInstalled,s}return te(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Ge({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:yo(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Dd(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return $t(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Ld(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=Je(r.update.prompt),i=Wn(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ye))return;let t=ye+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=k.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await wt(t.sessionId),u=Ge({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:u,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await wt(s.sessionId),o=Ge(s,r.hasContent),i=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:o,priority:s.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=d=>e.includeNonInteractive?!0:d===!0,o=[...this.sessions.values()].filter(d=>!e.cwd||d.cwd===e.cwd),i=await Promise.all(o.map(d=>wt(d.sessionId)));for(let d=0;d<o.length;d+=1){let l=o[d],p=i[d];s.add(l.sessionId);let f=Ge({interactive:l.interactive,...l.originatingClient?{originatingClient:l.originatingClient}:{}},p.hasContent);if(!r(f))continue;let m=p.mtime??new Date(l.updatedAt).toISOString();t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:m,attachedClients:l.attachedCount,status:"warm",busy:l.turnStartedAt!==void 0,awaitingInput:l.awaitingInput,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}let u=(await this.store.list().catch(d=>{throw this.logger?.warn(`session list: store.list() failed: ${d?.message??String(d)}`),d})).filter(d=>!s.has(d.sessionId)&&(!e.cwd||d.cwd===e.cwd)),c=await Promise.all(u.map(d=>wt(d.sessionId)));for(let d=0;d<u.length;d+=1){let l=u[d],p=c[d],f=Ge(l,p.hasContent);if(!r(f))continue;let m=p.mtime??l.updatedAt;t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage?{...l.currentUsage,costAmount:(l.currentUsage.cumulativeCost??0)+(l.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:l.importedFromMachine,importedFromUpstreamSessionId:l.importedFromUpstreamSessionId,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:f,priority:l.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}return t.sort((d,l)=>d.updatedAt<l.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=pt(),d={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let l=await this.store.read(e);l&&(l.lineageId||await this.store.write({...l,lineageId:c}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await ho(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let u={};for(let c of ro(i)){let d=await zs(e,c);d&&(u[c]=d.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:u}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=k.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ye}${Qt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=k.SessionNotFound,w}let r=t.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,u,c=t.mode??"synthesis",d,l,p,f=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let w=Jn(i,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=k.InvalidParams,b}u=t.forkAt,a=i.slice(0,w+1)}else{let w=zd(i);w?(u=w.messageId,a=i.slice(0,w.index+1)):(u="",a=i.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),u="",a=i;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}p=w,l=s.currentModel,d="running"}let m=await ho(e),g=c==="synthesis",h={...s,lineageId:pt(),agentId:r,interactive:!1,...d!==void 0?{forkSynthesisState:d}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=ht({record:h,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:K,machine:Vt.hostname()}),v=`${ye}${Qt()}`;return await this.writeImportedRecord({sessionId:v,bundle:y,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:u,...d!==void 0?{forkSynthesisState:d}:{}}),g&&(async()=>{try{let w=await te(p,[],{npmRegistry:this.npmRegistry}),b=await zt({agentId:r,cwd:t.cwd??I.sessionDir(e),plan:w,history:i,modelId:l,sessionId:e,logger:this.logger,timeoutMs:f});b&&b.synopsis?await this.mutateRecord(v,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:u}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await Js(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(I.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await uo(I.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await wt(e),o=Ge(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...o!==void 0?{interactive:o}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,...t,updatedAt:new Date().toISOString()};for(let i of s)delete o[i];await this.store.write(o)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let o=s.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(s.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await xr(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(u=>r-u.enqueuedAt<fo),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${fo/1e3}s)`),await ut(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await ut(t.sessionId,[]).catch(()=>{});continue}try{let u=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),u.replayPersistedQueue(o)}catch(u){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${u.message}`)}}}};function Ud(n,e){if(typeof n!="string"||n.length===0)return!1;let t=vt.resolve(n),s=vt.resolve(e);return t===s||t.startsWith(s+vt.sep)}function Dd(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(d=>d.description!==void 0?{name:d.name,description:d.description}:{name:d.name}):void 0)??e?.agentCommands,r=n.availableModes(),i=(r.length>0?r.map(d=>{let l={id:d.id};return d.name!==void 0&&(l.name=d.name),d.description!==void 0&&(l.description=d.description),l}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(d=>{let l={modelId:d.modelId};return d.name!==void 0&&(l.name=d.name),d.description!==void 0&&(l.description=d.description),l}):void 0)??e?.agentModels;return es({sessionId:n.sessionId,lineageId:e?.lineageId??pt(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:yo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function yo(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ld(n){return n?{...n}:void 0}function po(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Kt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let i=e.fromObject(s);if(i!==void 0)return i}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let u=e.fromObject(a);if(u!==void 0)return u}}let o=qd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function is(n){return Kt(n,{nestedKey:"models",configId:"model",fromObject:e=>ge(e.currentModelId)??ge(e.currentModel)??ge(e.modelId)??ge(e.model),fromConfig:e=>ge(e.currentValue)})}function Ae(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==k.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},o=s(r._meta)?r._meta:{},i=s(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",u=new Error(a);return u.code=k.AuthRequired,u.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},u}function mo(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function go(n,e,t,s){if(n&&typeof n=="object"&&n.code===k.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=s?`to reproduce: (cd ${mo(s.cwd)} && ${[s.command,...s.args].map(mo).join(" ")})`:"";if(!i&&!a)return n;let u=[o?r:`agent ${t} failed to start: ${r}`];i&&u.push(`stderr: ${i}`),a&&u.push(a);let c=new Error(u.join(`
122
- `));if(n&&typeof n=="object"){let d=n;typeof d.code=="number"&&(c.code=d.code),d.data!==void 0&&(c.data=d.data)}return c}function yt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",o=s.type==="agent"||s.type==="terminal"?s.type:void 0,i=typeof s.name=="string"?s.name:void 0,a=s._meta,u=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...u&&{_meta:u}})}return e.length>0?e:void 0}function ge(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function qd(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function as(n){return n.length>0?n:void 0}function ds(n){return Kt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=We(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=We(e.options);return t.length>0?t:void 0}})??[]}function cs(n){return Kt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=lt(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=lt(e.options);return t.length>0?t:void 0}})??[]}function us(n){return Kt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ge(e.currentModeId)??ge(e.currentMode)??ge(e.modeId)??ge(e.mode),fromConfig:e=>ge(e.currentValue)})}function zd(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function ho(n){try{let e=await Te.readFile(I.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
123
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function wt(n){try{let e=await Te.stat(I.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ge(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===qt?!1:e?!0:void 0}import{spawn as Jd}from"child_process";import*as Xe from"fs";import*as Ce from"fs/promises";import*as wo from"path";var Gt=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Wd=1e3,Qd=6e4,ls=3e3,Ye=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Wd,this.restartCapMs=r.restartCapMs??Qd;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await Ce.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 t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},ls);s.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw It(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw It(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw It(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw It(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw It(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},ls);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Gt(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await Ce.readdir(this.adapter.paths.dir())}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.endsWith(".pid"))continue;let s=wo.join(this.adapter.paths.dir(),t),r;try{let o=await Ce.readFile(s,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&fs(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+ls;for(;Date.now()<o&&fs(r);)await new Promise(i=>setTimeout(i,50));if(fs(r))try{process.kill(r,"SIGKILL")}catch{}}await Ce.unlink(s).catch(()=>{})}}spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Xe.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});i.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
124
- `);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let u={...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},[c,...d]=o;if(c===void 0){i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
125
- `),i.end();return}let l=Y(c),p=[...d,...r.args].map(Y),f;try{f=Jd(l,p,{env:u,stdio:["ignore","pipe","pipe"],detached:!1})}catch(m){i.write(`[hydra-acp] failed to spawn ${r.name}: ${m.message}
126
- `),i.end(),this.scheduleRestart(e,t);return}if(f.stdout&&f.stdout.pipe(i,{end:!1}),f.stderr&&f.stderr.pipe(i,{end:!1}),typeof f.pid=="number")try{Xe.writeFileSync(this.adapter.paths.pidFile(r.name),`${f.pid}
127
- `,{encoding:"utf8",mode:384})}catch(m){i.write(`[hydra-acp] failed to write pid file for ${r.name}: ${m.message}
128
- `)}e.child=f,e.logStream=i,e.pid=typeof f.pid=="number"?f.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,f.on("error",m=>{i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${m.message}
129
- `)}),f.on("exit",(m,g)=>{try{Xe.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${m??"null"} signal=${g??"null"}
130
- `),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 h=e.exitWaiters.splice(0);for(let v of h)v();if(this.stopping||e.manuallyStopped){try{i.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let y=e.breaker.recordExit(m,r.name,this.adapter.kind);if(typeof y=="object"){e.failureReason=y.tripped,i.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${y.tripped}
131
- `);try{i.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function fs(n){try{return process.kill(n,0),!0}catch{return!1}}function It(n,e){return n.code=e,n}var Vd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:I.extensionsDir,logFile:I.extensionLogFile,pidFile:I.extensionPidFile}},Yt=class extends Ye{constructor(e,t,s={}){super(e,Vd,t,s)}};var Kd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:I.transformersDir,logFile:I.transformerLogFile,pidFile:I.transformerPidFile}},Xt=class extends Ye{connected=new Map;constructor(e,t,s={}){super(e,Kd,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var Zt=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};import*as ps from"fs/promises";async function vo(n){await ps.writeFile(I.pidFile(),JSON.stringify(n)+`
132
- `,{encoding:"utf8",mode:384})}import*as kt from"fs/promises";import*as en from"path";var St=n=>{process.stderr.write(n+`
133
- `)};function ms(n){St=n??(e=>process.stderr.write(e+`
134
- `))}async function bo(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let u of s.agents)r.set(u.id,u.version??"current");let o=e.activeAgentVersions(),i=en.join(I.agentsDir(),t),a;try{a=await kt.readdir(i,{withFileTypes:!0})}catch(u){let c=u;if(c.code==="ENOENT")return;St(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let u of a){if(!u.isDirectory())continue;let c=u.name,d=r.get(c);if(d===void 0)continue;let l=o.get(c)??new Set,p=en.join(i,c),f;try{f=await kt.readdir(p,{withFileTypes:!0})}catch(m){St(`hydra-acp: prune: failed to read ${p}: ${m.message}`);continue}for(let m of f){if(!m.isDirectory())continue;let g=m.name;if(g===d||l.has(g)||g.includes(".partial-"))continue;let h=en.join(p,g);try{await kt.rm(h,{recursive:!0,force:!0}),St(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(y){St(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function Io(n){let e,t=!1,s=0,r=(a,u)=>{n.logger&&n.logger[a](`agent-sync: ${u}`)},o=async()=>{let a=[];try{let d=await n.registry.load();for(let l of d.agents)await $n(l)==="yes"&&a.push(l.id)}catch(d){return r("warn",`registry load failed: ${d.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let u=s%a.length;s=(s+1)%a.length;let c=a[u];try{let{synced:d,skipped:l}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${d.length}, skipped ${l}`)}catch(d){r("warn",`${c}: ${d.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(u=>{i(u)}).catch(u=>{r("warn",`tick crashed: ${u.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function gs(n){let e=n.maxDeletions??200,t=(f,m)=>{n.logger&&n.logger[f](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(f=>(t("warn",`manager.list failed: ${f.message}`),[])),i=[];for(let f of o){if(f.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(f.interactive!==!1)continue}else if(f.interactive===!0)continue;let g=Date.parse(f.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:f.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((f,m)=>f.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),u=a[0]?.lastUsedMs,c=0,d=0;for(let{sessionId:f}of a)try{await n.manager.deleteRecord(f,"expired")&&(c+=1)}catch(m){d+=1,t("warn",`delete ${f} failed: ${m.message}`)}let l=i.length-a.length;if(n.verbose||c>0||d>0){let f=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${f} session(s) older than ${Gd(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(l>0?`; ${l} deferred to next sweep`:""))}let p={considered:i.length,deleted:c,failed:d,deferred:l};return u!==void 0&&(p.oldestLastUsedMs=u),p}function So(n){let e,t=!1,s=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await gs({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},o),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Gd(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as Yd}from"crypto";function hs(n){if(Array.isArray(n))return n.map(hs);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=hs(n[t]);return e}return n}function ko(n){let{tui:e,...t}=n,s=JSON.stringify(hs(t));return Yd("sha256").update(s).digest("hex").slice(0,16)}import*as xo from"path";import{createHash as Xd,randomBytes as Zd,timingSafeEqual as ec}from"crypto";var Mo="hydra_session_",tc=3600*24*30,Ao=12,nc=32,sc=50;function rc(){return xo.join(I.home(),"session-tokens.json")}function Co(n){return Xd("sha256").update(n).digest("hex")}function Ro(n){return Zd(n).toString("hex")}function oc(){return Ro(Ao).slice(0,Ao*2)}function ic(){return`${Mo}${Ro(nc)}`}var tn=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=rc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(ac));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=ic(),s=Co(t),r=oc(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:tc,a=new Date(o.getTime()+i*1e3),u={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,u),this.scheduleWrite(),{id:r,token:t,expiresAt:u.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Mo))return;let t=Co(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!ec(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},sc))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ae(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 ac(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var Eo="Bearer ",nn=class{constructor(e){this.token=e}token;async validate(e){return dc(e,this.token)?"service":void 0}},sn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},rn=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Po(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Eo)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Eo.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function To(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var on=class{tokens=new Map;mint(e,t){let s=Pt();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function dc(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var an=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Is from"fs";import*as xt from"os";import*as Zo from"path";import*as Ss from"readline";function ys(n){return Math.floor(n/4)}function _o(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=ys(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}import{posix as cc}from"path";import uc from"strip-ansi";function At(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var lc=/[\x00-\x08\x0b-\x1f\x7f]/g;function oe(n){return uc(n).replace(lc,"")}function W(n){return oe(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Oo(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return wc(t);case"agent_thought_chunk":case"agent_thought":return vc(t);case"user_message_chunk":return bc(t);case"prompt_received":return Ic(t);case"tool_call":return Sc(t,e);case"tool_call_update":return Mc(t,e);case"plan":return Pc(t);case"current_mode_update":return Tc(t);case"current_model_update":return _c(t);case"turn_complete":return $c(t);case"usage_update":return yc(t);case"available_commands_update":return gc(t);case"available_modes_update":return hc(t);case"session_info_update":return pc(t);case"config_option_update":return fc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function fc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function pc(n){let e=J(n,"title"),t=e!==void 0?W(e):void 0,s=n._meta,r,o;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let u=a.agentId;if(typeof u=="string"&&(r=u),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function mc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:W(r)};typeof s.description=="string"&&(o.description=W(s.description)),e.push(o)}return e}function gc(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:mc(e)}:null}function hc(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:W(r.id)};typeof r.name=="string"&&(o.name=W(r.name)),typeof r.description=="string"&&(o.description=W(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function yc(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function wc(n){let e=Ct(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:At(n)}}function vc(n){let e=typeof n.text=="string"?oe(n.text):Ct(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:At(n)}}function bc(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=Ct(n.content);return t===null?null:{kind:"user-text",text:t}}function Ic(n){let e=Fc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Ho(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function $o(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function dn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=$o(r.oldText),i=$o(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function No(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:oe(t)}function Sc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title")??J(n,"name")??J(n,"label")??"tool call",r=J(n,"name")??J(n,"title");if(Ho(r)){let m=No(n);if(m!==null){let g=J(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:m};return g!==void 0&&(h.status=g),h}}let o=Uo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),u={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(u.status=i),a!==void 0&&(u.rawKind=a);let c=dn(n);c!==null&&(u.editDiff=c);let d=Bo(n);d!==void 0&&(u.detail=d);let l=ws(n);l!==void 0&&(u.detailFull=l);let p=jo(n);p!==void 0&&(u.locations=p);let f=At(n);return f!==void 0&&(u.workerTaskId=f),u}function jo(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Fo=64;function Bo(n){let e=ws(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?Cc(t,Fo):xc(t,Fo)}function ws(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return oe(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Me(W(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return Me(W(s))}}}var kc=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Ac(n){for(let e of kc)if(n.startsWith(e))return!0;return!1}function Uo(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return Me(i)}return Ac(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(cc.resolve(t.cwd,n)):n}function Cc(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function xc(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Mc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Uo(W(s),n,e):void 0,o=J(n,"status"),i=dn(n),a=Bo(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let c=J(n,"name")??s;if(Ho(c)){let m={kind:"exit-plan-mode",toolCallId:t},g=No(n);return g!==null&&(m.plan=g),o!==void 0&&(m.status=o),m}let d={kind:"tool-call-update",toolCallId:t};r!==void 0&&(d.title=r),a!==void 0&&(d.detail=a);let l=ws(n);l!==void 0&&(d.detailFull=l);let p=jo(n);if(p!==void 0&&(d.locations=p),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let m=Rc(n);m!==null&&(d.errorText=m),Ec(n,m)&&(d.upstreamInterrupted=!0)}let f=At(n);return f!==void 0&&(d.workerTaskId=f),d}function Rc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=Ct(s.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return oe(s)}return null}function Ec(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Pc(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?W(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function Tc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function _c(n){let e=J(n,"currentModel")??J(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:W(e),...s&&s.length>0?{availableModels:s}:{}}}function $c(n){let e=J(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function Ct(n){if(typeof n=="string")return oe(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?oe(e.text):null}function Fc(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=Ct(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function J(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Do(n){let e=new Map,t=new Map;for(let r of n){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let u=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=Hc(i);if(c.length===0)continue;let d=c;if(u!==void 0){let l=e.get(u)??[],p=[];for(let f of c)l.some(m=>m.path===f.path&&m.oldText===f.oldText&&m.newText===f.newText)||p.push(f);if(p.length===0)continue;e.set(u,[...l,...p]),d=p}for(let l of d)Oc(t,l)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function Lo(n){let e=[];for(let t of n){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){s=o;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Oc(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Hc(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let u of a){if(!u||typeof u!="object")continue;let c=u,d=typeof c.old_string=="string"?c.old_string:void 0,l=typeof c.new_string=="string"?c.new_string:void 0;d===void 0||l===void 0||e.push({path:i,oldText:d,newText:l})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let u=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:u,newText:c})}if(e.length>0)return e}let r=dn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function qo(n){let e=Nc(n),t=jc(e),s=[];Bc(s,n),Uc(s,e,t);let r=s.join(`
120
+ `:"")}import{z as U}from"zod";var Od=U.object({method:U.string(),params:U.unknown(),recordedAt:U.number()}),Hd=U.object({sessionId:U.string(),lineageId:U.string(),upstreamSessionId:U.string().optional(),agentId:U.string(),cwd:U.string(),title:U.string().optional(),synopsis:lt.optional(),summarizedThroughEntry:U.number().int().nonnegative().optional(),currentModel:U.string().optional(),currentMode:U.string().optional(),currentUsage:Zn.optional(),agentCommands:U.array(Yn).optional(),agentModes:U.array(Xn).optional(),interactive:U.boolean().optional(),originatingClient:es.optional(),priority:U.number().int().nonnegative().optional(),createdAt:U.string(),updatedAt:U.string()}),Nd=U.object({version:U.literal(1),exportedAt:U.string(),exportedFrom:U.object({hydraVersion:U.string(),machine:U.string(),hydraHost:U.string().optional()}),session:Hd,history:U.array(Od),promptHistory:U.array(U.string()).optional(),toolBlobs:U.record(U.string()).optional()});function gt(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function fo(n){return Nd.parse(n)}var po=900*1e3,Bd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=jd(Bd,16),vt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>he.spawn(a)),this.store=s??new Bt,this.tombstones=r.tombstones??new Ut,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Jt({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 o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new zt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,u)=>{let c=this.get(a);if(c){await c.retitle(u);return}await this.persistTitle(a,u)},persistSynopsis:(a,u,c)=>this.persistSynopsis(a,u,c),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,u,c)=>{if(c.targetAgentId)return;let d=this.get(a);d&&(d.compactionState=u),await this.mutateRecord(a,{compactionState:u})},broadcastHydraCompaction:(a,u,c)=>{this.emitSwapPhase(a,c.targetAgentId,u)},onSynthesisArtifact:async(a,u,c,d)=>{await this.dispatchSynthesisSwap(a,u,c,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let o=this.get(e);if(!o){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let i=this.compactionTailK;try{if(await o.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(o,t,i,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let u=o.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,u)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let u=await this.store.read(e).catch(()=>{});u?.synopsis&&u.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,u.synopsis,u.summarizedThroughEntry,u.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,s,o.summarizedThroughEntry,i)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,o){try{let i=o?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:i,summarizedThroughEntry:r,...o?{newAgentId:o}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ne(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let o={...s.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let a=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Wt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:o});a.action==="stop"&&a.payload&&(o=a.payload)}catch{}s.agentCapabilities=o}let r=new Pe({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:o=>this.bootstrapAgent({...o,mcpServers:o.mcpServers??[]}),loadExistingAgentSession:(o,i)=>this.bootstrapAgentLoad(o,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:o=>this.scheduleCompaction(r.sessionId,o),resolveAgentId:async o=>(await this.registry.getAgent(o))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:o=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:o}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=k.AlreadyAttached,o}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let g=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw g.code=k.AgentNotInstalled,g}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await te(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),i;try{let g=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});i=g.agentCapabilities,o.authMethods=ht(g.authMethods)}catch(g){throw await o.kill().catch(()=>{}),Ce(g,o)}let a;try{let g=mo(e.agentId,e.currentModel);a=await o.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...g&&{_meta:g}})}catch(g){if(g&&typeof g=="object"&&g.code===k.AuthRequired)throw await o.kill().catch(()=>{}),Ce(g,o);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
121
+ `),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let u=ls(a??{}),c=e.agentModes??ds(us(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(u)} advertisedModes=${JSON.stringify(c?.map(g=>g.id))}`);let d=await Be({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:u,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(d)} for sessionId=${e.hydraSessionId}`);let l=as(a??{}),f=ds(cs(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(l)} advertisedModels=${JSON.stringify(f?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Ue({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:l,logger:this.logger});if(e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new Pe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:g.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(g,h)=>this.bootstrapAgentLoad(g,{...h,mcpServers:h.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:d,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,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:g=>this.scheduleCompaction(m.sessionId,g),resolveAgentId:async g=>(await this.registry.getAgent(g))?.id,getCompactionState:()=>this.getCompactionState(m.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:g=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:g}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await Be({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let u=new Pe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:c=>this.bootstrapAgent({...c,mcpServers:c.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(c,d)=>this.bootstrapAgentLoad(c,{...d,mcpServers:d.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,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(u.sessionId),scheduleCompaction:c=>this.scheduleCompaction(u.sessionId,c),resolveAgentId:async c=>(await this.registry.getAgent(c))?.id,getCompactionState:()=>this.getCompactionState(u.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(u.sessionId),uncompactHook:()=>this.performUncompact(u.sessionId),onCompactionSwapHook:c=>{this.mutateRecord(u.sessionId,{rollbackBreadcrumb:c}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(u.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(u),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${u.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?u.seedFromFork(e.synopsis).catch(()=>{}):u.seedFromImport().catch(()=>{}),u}async dirExists(e){try{return(await Te.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Y(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=k.AgentNotInstalled,p}let s=await te(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Qt.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=ht(o.authMethods),(o.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 u=new Set;for(let p of this.sessions.values())u.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)u.add(`${p.agentId}::${p.upstreamSessionId}`);let d=I.sessionsDir(),l=[],f=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(u.has(m)){f+=1;continue}if(Ud(p.cwd,d)){f+=1;continue}let g=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(g){if(!qr(g,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 ${g.upstreamUpdatedAt??"<unset>"})`)}u.add(m);let h=`${ye}${Wt()}`,y=new Date().toISOString(),v=p.updatedAt??y,w={sessionId:h,lineageId:ft(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:v,updatedAt:v};p.title!==void 0&&(w.title=p.title);let b=ts(w);await this.store.write(b),l.push({version:1,...b})}return{synced:l,skipped:f}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let o=0;o<100;o+=1){let i={};s!==void 0&&(i.cursor=s);let a=await e.connection.request("session/list",i),u=Array.isArray(a.sessions)?a.sessions:[];for(let c of u){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let d={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(d.title=c.title),typeof c.updatedAt=="string"&&(d.updatedAt=c.updatedAt),t.push(d)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=k.AgentNotInstalled,o}let s=await te(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),i=o.agentCapabilities;r.authMethods=ht(o.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),u=a.sessionId;if(typeof u!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=as(a),d=cs(a),l=e.model??this.defaultModels[e.agentId];if(l&&l!==c){let m=qe(l,d),g=e.model!==void 0?`model=${JSON.stringify(l)}`:`defaultModels[${e.agentId}]=${JSON.stringify(l)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,u,l,g)&&(c=l);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(r,u,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(c=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${g} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=d.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let f=us(a),p=ls(a);return{agent:r,upstreamSessionId:u,agentMeta:a._meta,agentCapabilities:i,initialModel:c,initialModels:d.length>0?d:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(o){throw await r.kill().catch(()=>{}),Ce(ho(o,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let i=new Error(`agent ${t.agentId} not found in registry`);throw i.code=k.AgentNotInstalled,i}let r=await te(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=ht(i.authMethods);let u=mo(t.agentId,void 0),c=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...u&&{_meta:u}}),d=as(c),l=ds(cs(c)),f=us(c),p=ls(c);return{agent:o,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:a,initialModel:d,initialModels:l,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await o.kill().catch(()=>{}),Ce(ho(i,o,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),o)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=s.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let u=new Error(`agent ${e} not found in registry`);throw u.code=k.AgentNotInstalled,u}let o=await te(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let u=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});a.authMethods=ht(u.authMethods)}catch(u){throw await a.kill().catch(()=>{}),Ce(u,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=k.AgentNotInstalled,s}return te(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Ge({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:wo(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Dd(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return _t(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Ld(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=Je(r.update.prompt),i=Qn(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ye))return;let t=ye+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=k.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await yt(t.sessionId),u=Ge({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),c=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:u,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await yt(s.sessionId),o=Ge(s,r.hasContent),i=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:o,priority:s.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=d=>e.includeNonInteractive?!0:d===!0,o=[...this.sessions.values()].filter(d=>!e.cwd||d.cwd===e.cwd),i=await Promise.all(o.map(d=>yt(d.sessionId)));for(let d=0;d<o.length;d+=1){let l=o[d],f=i[d];s.add(l.sessionId);let p=Ge({interactive:l.interactive,...l.originatingClient?{originatingClient:l.originatingClient}:{}},f.hasContent);if(!r(p))continue;let m=f.mtime??new Date(l.updatedAt).toISOString();t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:p,priority:l.priority,updatedAt:m,attachedClients:l.attachedCount,status:"warm",busy:l.turnStartedAt!==void 0,awaitingInput:l.awaitingInput,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}let u=(await this.store.list().catch(d=>{throw this.logger?.warn(`session list: store.list() failed: ${d?.message??String(d)}`),d})).filter(d=>!s.has(d.sessionId)&&(!e.cwd||d.cwd===e.cwd)),c=await Promise.all(u.map(d=>yt(d.sessionId)));for(let d=0;d<u.length;d+=1){let l=u[d],f=c[d],p=Ge(l,f.hasContent);if(!r(p))continue;let m=f.mtime??l.updatedAt;t.push({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,cwd:l.cwd,title:l.title,agentId:l.agentId,currentModel:l.currentModel,currentUsage:l.currentUsage?{...l.currentUsage,costAmount:(l.currentUsage.cumulativeCost??0)+(l.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:l.importedFromMachine,importedFromUpstreamSessionId:l.importedFromUpstreamSessionId,parentSessionId:l.parentSessionId,forkedFromSessionId:l.forkedFromSessionId,forkedFromMessageId:l.forkedFromMessageId,originatingClient:l.originatingClient,interactive:p,priority:l.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:l.compactionState,forkSynthesisState:l.forkSynthesisState})}return t.sort((d,l)=>d.updatedAt<l.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=ft(),d={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let l=await this.store.read(e);l&&(l.lineageId||await this.store.write({...l,lineageId:c}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await yo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let u={};for(let c of oo(i)){let d=await Js(e,c);d&&(u[c]=d.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:u}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=k.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=k.SessionNotFound,w}let r=t.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,u,c=t.mode??"synthesis",d,l,f,p=12e4;if(c==="verbatim")if(t.forkAt!==void 0){let w=Wn(i,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=k.InvalidParams,b}u=t.forkAt,a=i.slice(0,w+1)}else{let w=zd(i);w?(u=w.messageId,a=i.slice(0,w.index+1)):(u="",a=i.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),u="",a=i;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=k.AgentNotInstalled,b}f=w,l=s.currentModel,d="running"}let m=await yo(e),g=c==="synthesis",h={...s,lineageId:ft(),agentId:r,interactive:!1,...d!==void 0?{forkSynthesisState:d}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},y=gt({record:h,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:K,machine:Qt.hostname()}),v=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:v,bundle:y,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:u,...d!==void 0?{forkSynthesisState:d}:{}}),g&&(async()=>{try{let w=await te(f,[],{npmRegistry:this.npmRegistry}),b=await qt({agentId:r,cwd:t.cwd??I.sessionDir(e),plan:w,history:i,modelId:l,sessionId:e,logger:this.logger,timeoutMs:p});b&&b.synopsis?await this.mutateRecord(v,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(v,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(v,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:v,forkedFromSessionId:e,forkedAt:u}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await Ws(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(I.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await lo(I.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await yt(e),o=Ge(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...o!==void 0?{interactive:o}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,...t,updatedAt:new Date().toISOString()};for(let i of s)delete o[i];await this.store.write(o)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let o=s.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(s.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Mr(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(u=>r-u.enqueuedAt<po),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${po/1e3}s)`),await ct(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await ct(t.sessionId,[]).catch(()=>{});continue}try{let u=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),u.replayPersistedQueue(o)}catch(u){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${u.message}`)}}}};function Ud(n,e){if(typeof n!="string"||n.length===0)return!1;let t=wt.resolve(n),s=wt.resolve(e);return t===s||t.startsWith(s+wt.sep)}function Dd(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(d=>d.description!==void 0?{name:d.name,description:d.description}:{name:d.name}):void 0)??e?.agentCommands,r=n.availableModes(),i=(r.length>0?r.map(d=>{let l={id:d.id};return d.name!==void 0&&(l.name=d.name),d.description!==void 0&&(l.description=d.description),l}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(d=>{let l={modelId:d.modelId};return d.name!==void 0&&(l.name=d.name),d.description!==void 0&&(l.description=d.description),l}):void 0)??e?.agentModels;return ts({sessionId:n.sessionId,lineageId:e?.lineageId??ft(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:wo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:c,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function wo(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Ld(n){return n?{...n}:void 0}function mo(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Vt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let i=e.fromObject(s);if(i!==void 0)return i}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let u=e.fromObject(a);if(u!==void 0)return u}}let o=qd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function as(n){return Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>ge(e.currentModelId)??ge(e.currentModel)??ge(e.modelId)??ge(e.model),fromConfig:e=>ge(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==k.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},o=s(r._meta)?r._meta:{},i=s(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",u=new Error(a);return u.code=k.AuthRequired,u.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},u}function go(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function ho(n,e,t,s){if(n&&typeof n=="object"&&n.code===k.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=s?`to reproduce: (cd ${go(s.cwd)} && ${[s.command,...s.args].map(go).join(" ")})`:"";if(!i&&!a)return n;let u=[o?r:`agent ${t} failed to start: ${r}`];i&&u.push(`stderr: ${i}`),a&&u.push(a);let c=new Error(u.join(`
122
+ `));if(n&&typeof n=="object"){let d=n;typeof d.code=="number"&&(c.code=d.code),d.data!==void 0&&(c.data=d.data)}return c}function ht(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",o=s.type==="agent"||s.type==="terminal"?s.type:void 0,i=typeof s.name=="string"?s.name:void 0,a=s._meta,u=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...u&&{_meta:u}})}return e.length>0?e:void 0}function ge(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function qd(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function ds(n){return n.length>0?n:void 0}function cs(n){return Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=We(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=We(e.options);return t.length>0?t:void 0}})??[]}function us(n){return Vt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=ut(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=ut(e.options);return t.length>0?t:void 0}})??[]}function ls(n){return Vt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ge(e.currentModeId)??ge(e.currentMode)??ge(e.modeId)??ge(e.mode),fromConfig:e=>ge(e.currentValue)})}function zd(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function yo(n){try{let e=await Te.readFile(I.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
123
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function yt(n){try{let e=await Te.stat(I.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ge(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Lt?!1:e?!0:void 0}import{spawn as Jd}from"child_process";import*as Gt from"fs";import*as be from"fs/promises";import*as Yt from"path";import Wd from"pino-roll";var Kt=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Qd=1e3,Vd=6e4,fs=3e3,Ye=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Qd,this.restartCapMs=r.restartCapMs??Vd;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await be.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},fs);s.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw bt(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw bt(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},fs);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Kt(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await be.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let o=await be.readFile(s,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&ps(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+fs;for(;Date.now()<o&&ps(r);)await new Promise(i=>setTimeout(i,50));if(ps(r))try{process.kill(r,"SIGKILL")}catch{}}await be.unlink(s).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Yt.dirname(this.adapter.paths.logFile(r.name));await be.mkdir(i,{recursive:!0});let a=await Wd({file:Yt.join(i,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}});if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
124
+ `);let u=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=u,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:u,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...l]=o;if(d===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
125
+ `),a.end();return}let f=Y(d),p=[...l,...r.args].map(Y),m;try{m=Jd(f,p,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
126
+ `),a.end(),this.scheduleRestart(e,t);return}let g=h=>{try{a.write(typeof h=="string"?h:h.toString())}catch{}};if(m.stdout?.on("data",g),m.stderr?.on("data",g),typeof m.pid=="number")try{Gt.writeFileSync(this.adapter.paths.pidFile(r.name),`${m.pid}
127
+ `,{encoding:"utf8",mode:384})}catch(h){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
128
+ `)}e.child=m,e.logStream=a,e.pid=typeof m.pid=="number"?m.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,m.on("error",h=>{a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${h.message}
129
+ `)}),m.on("exit",(h,y)=>{try{Gt.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${y??"null"}
130
+ `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let v=e.exitWaiters.splice(0);for(let b of v)b();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let w=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof w=="object"){e.failureReason=w.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${w.tripped}
131
+ `);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ps(n){try{return process.kill(n,0),!0}catch{return!1}}function bt(n,e){return n.code=e,n}var Kd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:I.extensionsDir,logFile:I.extensionLogFile,pidFile:I.extensionPidFile}},Xt=class extends Ye{constructor(e,t,s={}){super(e,Kd,t,s)}};var Gd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:I.transformersDir,logFile:I.transformerLogFile,pidFile:I.transformerPidFile}},Zt=class extends Ye{connected=new Map;constructor(e,t,s={}){super(e,Gd,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var en=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};import*as ms from"fs/promises";async function vo(n){await ms.writeFile(I.pidFile(),JSON.stringify(n)+`
132
+ `,{encoding:"utf8",mode:384})}import*as St from"fs/promises";import*as tn from"path";var It=n=>{process.stderr.write(n+`
133
+ `)};function gs(n){It=n??(e=>process.stderr.write(e+`
134
+ `))}async function bo(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let u of s.agents)r.set(u.id,u.version??"current");let o=e.activeAgentVersions(),i=tn.join(I.agentsDir(),t),a;try{a=await St.readdir(i,{withFileTypes:!0})}catch(u){let c=u;if(c.code==="ENOENT")return;It(`hydra-acp: prune: failed to read ${i}: ${c.message}`);return}for(let u of a){if(!u.isDirectory())continue;let c=u.name,d=r.get(c);if(d===void 0)continue;let l=o.get(c)??new Set,f=tn.join(i,c),p;try{p=await St.readdir(f,{withFileTypes:!0})}catch(m){It(`hydra-acp: prune: failed to read ${f}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let g=m.name;if(g===d||l.has(g)||g.includes(".partial-"))continue;let h=tn.join(f,g);try{await St.rm(h,{recursive:!0,force:!0}),It(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(y){It(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function Io(n){let e,t=!1,s=0,r=(a,u)=>{n.logger&&n.logger[a](`agent-sync: ${u}`)},o=async()=>{let a=[];try{let d=await n.registry.load();for(let l of d.agents)await Fn(l)==="yes"&&a.push(l.id)}catch(d){return r("warn",`registry load failed: ${d.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let u=s%a.length;s=(s+1)%a.length;let c=a[u];try{let{synced:d,skipped:l}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${d.length}, skipped ${l}`)}catch(d){r("warn",`${c}: ${d.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(u=>{i(u)}).catch(u=>{r("warn",`tick crashed: ${u.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function hs(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),i=[];for(let p of o){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let g=Date.parse(p.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:p.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),u=a[0]?.lastUsedMs,c=0,d=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p,"expired")&&(c+=1)}catch(m){d+=1,t("warn",`delete ${p} failed: ${m.message}`)}let l=i.length-a.length;if(n.verbose||c>0||d>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Yd(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(l>0?`; ${l} deferred to next sweep`:""))}let f={considered:i.length,deleted:c,failed:d,deferred:l};return u!==void 0&&(f.oldestLastUsedMs=u),f}function So(n){let e,t=!1,s=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await hs({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},o),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Yd(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as Xd}from"crypto";function ys(n){if(Array.isArray(n))return n.map(ys);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=ys(n[t]);return e}return n}function ko(n){let{tui:e,...t}=n,s=JSON.stringify(ys(t));return Xd("sha256").update(s).digest("hex").slice(0,16)}import*as xo from"path";import{createHash as Zd,randomBytes as ec,timingSafeEqual as tc}from"crypto";var Mo="hydra_session_",nc=3600*24*30,Ao=12,sc=32,rc=50;function oc(){return xo.join(I.home(),"session-tokens.json")}function Co(n){return Zd("sha256").update(n).digest("hex")}function Ro(n){return ec(n).toString("hex")}function ic(){return Ro(Ao).slice(0,Ao*2)}function ac(){return`${Mo}${Ro(sc)}`}var nn=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=oc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(dc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=ac(),s=Co(t),r=ic(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:nc,a=new Date(o.getTime()+i*1e3),u={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,u),this.scheduleWrite(),{id:r,token:t,expiresAt:u.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Mo))return;let t=Co(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!tc(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},rc))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ae(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 dc(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var Eo="Bearer ",sn=class{constructor(e){this.token=e}token;async validate(e){return cc(e,this.token)?"service":void 0}},rn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},on=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function Po(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Eo)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Eo.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function To(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var an=class{tokens=new Map;mint(e,t){let s=Et();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function cc(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var dn=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Ss from"fs";import*as Ct from"os";import*as Zo from"path";import*as ks from"readline";function ws(n){return Math.floor(n/4)}function _o(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=ws(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}import{posix as uc}from"path";import lc from"strip-ansi";function kt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var fc=/[\x00-\x08\x0b-\x1f\x7f]/g;function oe(n){return lc(n).replace(fc,"")}function W(n){return oe(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Oo(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return vc(t);case"agent_thought_chunk":case"agent_thought":return bc(t);case"user_message_chunk":return Ic(t);case"prompt_received":return Sc(t);case"tool_call":return kc(t,e);case"tool_call_update":return Rc(t,e);case"plan":return Tc(t);case"current_mode_update":return _c(t);case"current_model_update":return $c(t);case"turn_complete":return Fc(t);case"usage_update":return wc(t);case"available_commands_update":return hc(t);case"available_modes_update":return yc(t);case"session_info_update":return mc(t);case"config_option_update":return pc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function pc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function mc(n){let e=J(n,"title"),t=e!==void 0?W(e):void 0,s=n._meta,r,o;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let u=a.agentId;if(typeof u=="string"&&(r=u),"pendingAgentSwap"in a){let c=a.pendingAgentSwap;typeof c=="string"?o=c:c===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function gc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:W(r)};typeof s.description=="string"&&(o.description=W(s.description)),e.push(o)}return e}function hc(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:gc(e)}:null}function yc(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:W(r.id)};typeof r.name=="string"&&(o.name=W(r.name)),typeof r.description=="string"&&(o.description=W(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function wc(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function vc(n){let e=At(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:kt(n)}}function bc(n){let e=typeof n.text=="string"?oe(n.text):At(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:kt(n)}}function Ic(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=At(n.content);return t===null?null:{kind:"user-text",text:t}}function Sc(n){let e=Oc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Ho(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function $o(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function cn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=$o(r.oldText),i=$o(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function No(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:oe(t)}function kc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title")??J(n,"name")??J(n,"label")??"tool call",r=J(n,"name")??J(n,"title");if(Ho(r)){let m=No(n);if(m!==null){let g=J(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:m};return g!==void 0&&(h.status=g),h}}let o=Uo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),u={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(u.status=i),a!==void 0&&(u.rawKind=a);let c=cn(n);c!==null&&(u.editDiff=c);let d=Bo(n);d!==void 0&&(u.detail=d);let l=vs(n);l!==void 0&&(u.detailFull=l);let f=jo(n);f!==void 0&&(u.locations=f);let p=kt(n);return p!==void 0&&(u.workerTaskId=p),u}function jo(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Fo=64;function Bo(n){let e=vs(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?xc(t,Fo):Mc(t,Fo)}function vs(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return oe(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Me(W(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return Me(W(s))}}}var Ac=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Cc(n){for(let e of Ac)if(n.startsWith(e))return!0;return!1}function Uo(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return Me(i)}return Cc(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(uc.resolve(t.cwd,n)):n}function xc(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Mc(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Rc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Uo(W(s),n,e):void 0,o=J(n,"status"),i=cn(n),a=Bo(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let c=J(n,"name")??s;if(Ho(c)){let m={kind:"exit-plan-mode",toolCallId:t},g=No(n);return g!==null&&(m.plan=g),o!==void 0&&(m.status=o),m}let d={kind:"tool-call-update",toolCallId:t};r!==void 0&&(d.title=r),a!==void 0&&(d.detail=a);let l=vs(n);l!==void 0&&(d.detailFull=l);let f=jo(n);if(f!==void 0&&(d.locations=f),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let m=Ec(n);m!==null&&(d.errorText=m),Pc(n,m)&&(d.upstreamInterrupted=!0)}let p=kt(n);return p!==void 0&&(d.workerTaskId=p),d}function Ec(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=At(s.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return oe(s)}return null}function Pc(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Tc(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?W(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function _c(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function $c(n){let e=J(n,"currentModel")??J(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:W(e),...s&&s.length>0?{availableModels:s}:{}}}function Fc(n){let e=J(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function At(n){if(typeof n=="string")return oe(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?oe(e.text):null}function Oc(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=At(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function J(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Do(n){let e=new Map,t=new Map;for(let r of n){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let u=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,c=Nc(i);if(c.length===0)continue;let d=c;if(u!==void 0){let l=e.get(u)??[],f=[];for(let p of c)l.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(u,[...l,...f]),d=f}for(let l of d)Hc(t,l)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function Lo(n){let e=[];for(let t of n){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){s=o;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Hc(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Nc(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let u of a){if(!u||typeof u!="object")continue;let c=u,d=typeof c.old_string=="string"?c.old_string:void 0,l=typeof c.new_string=="string"?c.new_string:void 0;d===void 0||l===void 0||e.push({path:i,oldText:d,newText:l})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let u=typeof i.oldText=="string"?i.oldText:"",c=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:u,newText:c})}if(e.length>0)return e}let r=cn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function qo(n){let e=jc(n),t=Bc(e),s=[];Uc(s,n),Dc(s,e,t);let r=s.join(`
135
135
  `);return r.endsWith(`
136
136
  `)||(r+=`
137
- `),r}function Nc(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=Oo(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function jc(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Bc(n,e){let t=e.session,s=Fr(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${_e(r)}`),n.push("");let o=[];o.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let u=[];if(a.used!==void 0){let c=a.size!==void 0?`${vs(a.size)}`:void 0;u.push(c?`${vs(a.used)} / ${c} tokens`:`${vs(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";u.push(`$${a.costAmount.toFixed(2)} ${c}`)}o.push(`- **Usage:** ${u.join(" \xB7 ")}`)}n.push(o.join(`
138
- `)),n.push("")}function Uc(n,e,t){if(!e.some(c=>Dc(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,o="",i=!1,a=()=>{o.length!==0&&(n.push(o.trimEnd()),n.push(""),o="")},u=()=>{i||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),i=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),n.push("**User:**"),n.push("");for(let d of c.text.split(`
137
+ `),r}function jc(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=Oo(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Bc(n){let e=new Map;for(let{event:t}of n){if(t.kind==="tool-call"){let s=e.get(t.toolCallId);e.set(t.toolCallId,{title:t.title,status:t.status??s?.status??"pending"});continue}if(t.kind==="tool-call-update"){let s=e.get(t.toolCallId)??{title:"tool call",status:"pending"};e.set(t.toolCallId,{title:t.title??s.title,status:t.status??s.status})}}return e}function Uc(n,e){let t=e.session,s=Or(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${_e(r)}`),n.push("");let o=[];o.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let u=[];if(a.used!==void 0){let c=a.size!==void 0?`${bs(a.size)}`:void 0;u.push(c?`${bs(a.used)} / ${c} tokens`:`${bs(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";u.push(`$${a.costAmount.toFixed(2)} ${c}`)}o.push(`- **Usage:** ${u.join(" \xB7 ")}`)}n.push(o.join(`
138
+ `)),n.push("")}function Dc(n,e,t){if(!e.some(c=>Lc(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,o="",i=!1,a=()=>{o.length!==0&&(n.push(o.trimEnd()),n.push(""),o="")},u=()=>{i||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),i=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{a(),r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),n.push("**User:**"),n.push("");for(let d of c.text.split(`
139
139
  `))n.push(`> ${_e(d)}`);n.push(""),n.push("**Assistant:**"),n.push(""),i=!0;break}case"agent-text":u(),o+=c.text;break;case"agent-thought":{u(),a();let d=c.text.split(`
140
- `);for(let l of d)n.push(`> _${_e(l)}_`);n.push("");break}case"tool-call":{if(u(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let d=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${qc(d.status)} ${Lc(d)}`),n.push("");break}case"tool-call-update":break;case"plan":{u(),a(),n.push("**Plan:**"),n.push("");for(let d of c.entries){let l=d.status==="completed"?"[x]":"[ ]";n.push(`- ${l} ${_e(d.content)}`)}n.push("");break}case"mode-changed":u(),a(),n.push(`_mode: ${_e(c.mode)}_`),n.push("");break;case"model-changed":u(),a(),n.push(`_model: ${_e(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Dc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Lc(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${_e(n.title)}${t}`}function qc(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function _e(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function vs(n){return n.toLocaleString("en-US")}function zo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function zc(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,u=[];for(let d of s){let l=d.toUpperCase();l==="AND"?i=!0:l==="OR"?a=!0:u.push(d)}i?o="AND":a&&(o="OR");let c=u.map(d=>Jc(d)).filter(d=>d.term.length>0);return{operator:o,terms:c}}function Jc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Jo(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Jo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Jo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Wc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Qc=5,Vc=200,Wo=30;async function Ko(n,e,t={}){let s=zc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Qc,o=t.maxSessions??Vc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),u=i?a.filter(l=>i.has(l.sessionId)):a,c=[],d=!1;for(let l of u){if(c.length>=o){d=!0;break}let p=await n.loadHistory(l.sessionId).catch(()=>[]),f=Kc(p,s,r);if(f.snippets.length===0)continue;let m={sessionId:l.sessionId,cwd:l.cwd,status:l.status,updatedAt:l.updatedAt,totalMatches:f.totalMatches,snippets:f.snippets};l.title!==void 0&&(m.title=l.title),c.push(m)}return{query:e,truncated:d,results:c}}function Kc(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=Gc(n,i,o,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Gc(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let u=Yc(a).filter(c=>Wc(t,c.kind));for(let c of u){let d=c.text.toLowerCase(),l=d.indexOf(r);if(l===-1)continue;let p=0;for(;l!==-1;)p++,l=d.indexOf(r,l+r.length);if(o+=p,i.length<s){let f=d.indexOf(r),m={kind:c.kind,text:nu(c.text,f,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function Yc(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=cn(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?oe(s.text):cn(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(eu(s))return[];let o=cn(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=tu(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return Xc(s);default:return[]}}function Xc(n){let e=Qo(n,"name"),t=Qo(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let u={kind:"tool",text:a};e!==void 0&&(u.toolName=e),s.push(u)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Vo(r);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Vo(o);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let i=Zc(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Zc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=W(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=W(s);if(r.length>0)return r}}return null}function eu(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function cn(n){if(typeof n=="string")return oe(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?oe(e.text):""}function tu(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=cn(t);s.length>0&&e.push(s)}return e.join("")}function Qo(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Vo(n){try{return JSON.stringify(n)}catch{return""}}function nu(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-Wo),u=Math.min(s.length,i+o.length+Wo),c=a>0?"\u2026":"",d=u<s.length?"\u2026":"";return`${c}${s.slice(a,u)}${d}`}import{randomBytes as Yo}from"crypto";function Go(n){let e=Yo(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function bs(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Go({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Go({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let o=Ze(n.deps);return o!==void 0&&(o.bindToSession(s),r=[...r,...o.descriptors]),r}}function Ze(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Yo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{s.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>s.abandon(a)}}var un=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Xo(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!zo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ei(n,e,t,s={}){n.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})}}),n.get("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.getOne(p);return f||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(c,d)=>{let l=c.body??{},p=typeof l.q=="string"?l.q:"";if(p.trim().length===0)return d.code(400).send({error:"q is required"}),d;let f=Array.isArray(l.sessionIds)?l.sessionIds.filter(g=>typeof g=="string"&&g.length>0):void 0;return await Ko(e,p,{sessionIds:f})}),n.post("/v1/sessions",async(c,d)=>{let l=c.body??{},p=Y(l.cwd??t.cwd),f=l.agentId??t.agentId,m=Ze(s),g=m!==void 0?[...l.mcpServers??[],...m.descriptors]:l.mcpServers;try{let h=await e.create({cwd:p,agentId:f,mcpServers:g});m!==void 0&&m.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){m!==void 0&&m.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),n.post("/v1/sessions/collect",async(c,d)=>{let l=c.body??{},p=typeof l.maxAgeDays=="number"&&l.maxAgeDays>0?l.maxAgeDays*24*60*60*1e3:0,f=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,m=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let g=await gs({manager:e,maxAgeMs:p,maxDeletions:f,selection:m,verbose:!1});d.code(200).send(g)}catch(g){d.code(500).send({error:g.message})}}),n.post("/v1/sessions/:id/kill",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(f){f.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(!f)return d.code(404).send({error:"session not found"}),d;let m=c.body??{},g={};(m.mode==="memory"||m.mode==="file")&&(g.mode=m.mode),typeof m.capacityBytes=="number"&&(g.capacityBytes=m.capacityBytes),typeof m.fileCapBytes=="number"&&(g.fileCapBytes=m.fileCapBytes),(g.mode??"memory")==="file"&&(g.filePathFor=h=>Zo.join(xt.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return f.openStream(g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(!f)return d.code(404).send({error:"session not found"}),d;let m=c.body??{},g=typeof m.chunk=="string"?m.chunk:"",h=m.eof===!0;try{return f.streamWrite(g,h)}catch(y){return d.code(409).send({error:y.message}),d}}),n.patch("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=c.body??{};if(f.priority!==void 0){let g=f.priority,h;if(g===null||g===0)h=void 0;else if(typeof g=="number"&&Number.isInteger(g)&&g>0)h=g;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(f.regen===!0){if(!(e.get(p)!==void 0||await e.hasRecord(p))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(p),d.code(202).send();return}if(typeof f.title!="string"||f.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,f.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);if(f){await f.close({deleteRecord:!0}),await e.waitForDeletion(p),await e.hasRecord(p)&&await e.deleteRecord(p),d.code(204).send();return}if(!await e.deleteRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.get("/v1/sessions/:id/export",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=c.query?.tools,m=f==="references"?"references":to(f),g=await e.exportBundle(p,m==="references"?{tools:"references"}:{});if(!g){d.code(404).send({error:"session not found"});return}let h=ht({record:g.record,history:m==="summary"?no(g.history,"summary"):g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,...g.toolBlobs!==void 0?{toolBlobs:g.toolBlobs}:{},hydraVersion:K,machine:xt.hostname(),hydraHost:Xo(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${p}-${y}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.exportBundle(p);if(!f){d.code(404).send({error:"session not found"});return}let m=c.query??{},g=m.fold==="true"||m.fold==="1",h=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,y=Do(f.history);h&&(y=y.filter(v=>h.has(v.path))),g&&(y=y.map(v=>({...v,hunks:Lo(v.hunks)}))),d.code(200).send(y)}),n.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let l=c.params,p=await e.resolveCanonicalId(l.id)??l.id,f=await e.loadToolBlob(p,l.hash);if(f===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(f)}),n.get("/v1/sessions/:id/transcript",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=await e.exportBundle(p);if(!f){d.code(404).send({error:"session not found"});return}let m=ht({record:f.record,history:f.history,promptHistory:f.promptHistory.length>0?f.promptHistory:void 0,hydraVersion:K,machine:xt.hostname(),hydraHost:Xo(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(qo(m))}),n.post("/v1/sessions/:id/fork",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=c.body??{},m={};if(f.forkAt!==void 0){if(typeof f.forkAt!="string"||f.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}m.forkAt=f.forkAt}if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}m.cwd=Y(f.cwd)}if(f.agentId!==void 0){if(typeof f.agentId!="string"||f.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}m.agentId=f.agentId}if(f.title!==void 0){if(typeof f.title!="string"){d.code(400).send({error:"title must be a string"});return}m.title=f.title}if(f.mode!==void 0){if(f.mode!=="verbatim"&&f.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=f.mode}if(f.model!==void 0){if(typeof f.model!="string"||f.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}m.model=f.model}try{let g=await e.forkSession(p,m);d.code(201).send(g)}catch(g){let h=g;if(h.code===k.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===k.InvalidParams||h.code===k.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),n.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 p;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}p=l.cwd}let f;try{f=lo(l.bundle)}catch(m){d.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(f,{replace:l.replace===!0,...p!==void 0?{cwd:p}:{}});d.code(201).send(m)}catch(m){let g=m;if(g.code===k.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:g.existingSessionId});return}d.code(500).send({error:g.message})}}),n.get("/v1/sessions/:id/compact/status",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p),m;if(f?m=f.summarizedThroughEntry:m=await e.getSummarizedThroughEntry(p),m===void 0&&!await e.hasRecord(p))return d.code(404).send({error:"session not found"}),d;let g=await e.getCompactionState(p),h=await e.getRollbackBreadcrumb(p),y=!1,v,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=m??0,C=b.length,_=b.slice(A).reduce((E,B)=>E+JSON.stringify(B.params).length,0);v=ys(_);let H=f?.currentModel,D=b.at(-1).recordedAt,R=f?.currentUsage;y=_o({summarizedThroughEntry:A,totalEntries:C,unsummarizedChars:_,compactionInFlight:e.getCompactionInFlight(),currentModel:H,lastActivityMs:D,nowMs:Date.now(),config:t.compaction,...typeof R?.used=="number"?{agentReportedUsed:R.used}:{},...typeof R?.size=="number"?{agentReportedSize:R.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...v!=null?{approxTokens:v}:{},...g!=null?{compactionState:g}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l;if(e.get(p)){e.scheduleCompaction(p),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(p),d.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l;if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(p),d.code(202).send({rolledBack:!0})}catch(f){let m=f instanceof Error?f.message:String(f);d.code(409).send({error:m})}}),n.get("/v1/sessions/:id/history",async(c,d)=>{let l=c.params.id,p=c.query,f=p?.follow==="1"||p?.follow==="true",m=await e.resolveCanonicalId(l)??l,g=e.get(m),h,y,v=!1,w=1e4,b=[];if(g){f&&(y=g.onBroadcast(C=>{d.raw.writableEnded||(v?d.raw.write(JSON.stringify(C)+`
140
+ `);for(let l of d)n.push(`> _${_e(l)}_`);n.push("");break}case"tool-call":{if(u(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let d=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${zc(d.status)} ${qc(d)}`),n.push("");break}case"tool-call-update":break;case"plan":{u(),a(),n.push("**Plan:**"),n.push("");for(let d of c.entries){let l=d.status==="completed"?"[x]":"[ ]";n.push(`- ${l} ${_e(d.content)}`)}n.push("");break}case"mode-changed":u(),a(),n.push(`_mode: ${_e(c.mode)}_`),n.push("");break;case"model-changed":u(),a(),n.push(`_model: ${_e(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Lc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function qc(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${_e(n.title)}${t}`}function zc(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function _e(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function bs(n){return n.toLocaleString("en-US")}function zo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Jc(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,u=[];for(let d of s){let l=d.toUpperCase();l==="AND"?i=!0:l==="OR"?a=!0:u.push(d)}i?o="AND":a&&(o="OR");let c=u.map(d=>Wc(d)).filter(d=>d.term.length>0);return{operator:o,terms:c}}function Wc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Jo(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Jo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Jo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Qc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Vc=5,Kc=200,Wo=30;async function Ko(n,e,t={}){let s=Jc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Vc,o=t.maxSessions??Kc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),u=i?a.filter(l=>i.has(l.sessionId)):a,c=[],d=!1;for(let l of u){if(c.length>=o){d=!0;break}let f=await n.loadHistory(l.sessionId).catch(()=>[]),p=Gc(f,s,r);if(p.snippets.length===0)continue;let m={sessionId:l.sessionId,cwd:l.cwd,status:l.status,updatedAt:l.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};l.title!==void 0&&(m.title=l.title),c.push(m)}return{query:e,truncated:d,results:c}}function Gc(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=Yc(n,i,o,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Yc(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let u=Xc(a).filter(c=>Qc(t,c.kind));for(let c of u){let d=c.text.toLowerCase(),l=d.indexOf(r);if(l===-1)continue;let f=0;for(;l!==-1;)f++,l=d.indexOf(r,l+r.length);if(o+=f,i.length<s){let p=d.indexOf(r),m={kind:c.kind,text:su(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function Xc(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=un(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?oe(s.text):un(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(tu(s))return[];let o=un(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=nu(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return Zc(s);default:return[]}}function Zc(n){let e=Qo(n,"name"),t=Qo(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let u={kind:"tool",text:a};e!==void 0&&(u.toolName=e),s.push(u)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Vo(r);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Vo(o);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let i=eu(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function eu(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=W(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=W(s);if(r.length>0)return r}}return null}function tu(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function un(n){if(typeof n=="string")return oe(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?oe(e.text):""}function nu(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=un(t);s.length>0&&e.push(s)}return e.join("")}function Qo(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Vo(n){try{return JSON.stringify(n)}catch{return""}}function su(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-Wo),u=Math.min(s.length,i+o.length+Wo),c=a>0?"\u2026":"",d=u<s.length?"\u2026":"";return`${c}${s.slice(a,u)}${d}`}import{randomBytes as Yo}from"crypto";function Go(n){let e=Yo(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Is(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Go({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Go({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let o=Xe(n.deps);return o!==void 0&&(o.bindToSession(s),r=[...r,...o.descriptors]),r}}function Xe(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Yo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{s.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>s.abandon(a)}}var ln=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function Xo(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!zo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ei(n,e,t,s={}){n.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})}}),n.get("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.getOne(f);return p||(d.code(404).send({error:"session not found"}),d)}),n.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 p=Array.isArray(l.sessionIds)?l.sessionIds.filter(g=>typeof g=="string"&&g.length>0):void 0;return await Ko(e,f,{sessionIds:p})}),n.post("/v1/sessions",async(c,d)=>{let l=c.body??{},f=Y(l.cwd??t.cwd),p=l.agentId??t.agentId,m=Xe(s),g=m!==void 0?[...l.mcpServers??[],...m.descriptors]:l.mcpServers;try{let h=await e.create({cwd:f,agentId:p,mcpServers:g});m!==void 0&&m.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){m!==void 0&&m.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),n.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,p=typeof l.limit=="number"&&l.limit>0?l.limit:1e3,m=l.selection==="explicit"||l.selection==="unpromoted"?l.selection:"unpromoted";try{let g=await hs({manager:e,maxAgeMs:f,maxDeletions:p,selection:m,verbose:!1});d.code(200).send(g)}catch(g){d.code(500).send({error:g.message})}}),n.post("/v1/sessions/:id/kill",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(p){p.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()}),n.post("/v1/sessions/:id/stdin/open",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(!p)return d.code(404).send({error:"session not found"}),d;let m=c.body??{},g={};(m.mode==="memory"||m.mode==="file")&&(g.mode=m.mode),typeof m.capacityBytes=="number"&&(g.capacityBytes=m.capacityBytes),typeof m.fileCapBytes=="number"&&(g.fileCapBytes=m.fileCapBytes),(g.mode??"memory")==="file"&&(g.filePathFor=h=>Zo.join(Ct.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return p.openStream(g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(!p)return d.code(404).send({error:"session not found"}),d;let m=c.body??{},g=typeof m.chunk=="string"?m.chunk:"",h=m.eof===!0;try{return p.streamWrite(g,h)}catch(y){return d.code(409).send({error:y.message}),d}}),n.patch("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.body??{};if(p.priority!==void 0){let g=p.priority,h;if(g===null||g===0)h=void 0;else if(typeof g=="number"&&Number.isInteger(g)&&g>0)h=g;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(p.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 p.title!="string"||p.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(f,p.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);if(p){await p.close({deleteRecord:!0}),await e.waitForDeletion(f),await e.hasRecord(f)&&await e.deleteRecord(f),d.code(204).send();return}if(!await e.deleteRecord(f)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.get("/v1/sessions/:id/export",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.query?.tools,m=p==="references"?"references":no(p),g=await e.exportBundle(f,m==="references"?{tools:"references"}:{});if(!g){d.code(404).send({error:"session not found"});return}let h=gt({record:g.record,history:m==="summary"?so(g.history,"summary"):g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,...g.toolBlobs!==void 0?{toolBlobs:g.toolBlobs}:{},hydraVersion:K,machine:Ct.hostname(),hydraHost:Xo(t)}),y=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${f}-${y}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.exportBundle(f);if(!p){d.code(404).send({error:"session not found"});return}let m=c.query??{},g=m.fold==="true"||m.fold==="1",h=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(v=>v.trim()).filter(v=>v.length>0)):void 0,y=Do(p.history);h&&(y=y.filter(v=>h.has(v.path))),g&&(y=y.map(v=>({...v,hunks:Lo(v.hunks)}))),d.code(200).send(y)}),n.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let l=c.params,f=await e.resolveCanonicalId(l.id)??l.id,p=await e.loadToolBlob(f,l.hash);if(p===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(p)}),n.get("/v1/sessions/:id/transcript",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=await e.exportBundle(f);if(!p){d.code(404).send({error:"session not found"});return}let m=gt({record:p.record,history:p.history,promptHistory:p.promptHistory.length>0?p.promptHistory:void 0,hydraVersion:K,machine:Ct.hostname(),hydraHost:Xo(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(qo(m))}),n.post("/v1/sessions/:id/fork",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=c.body??{},m={};if(p.forkAt!==void 0){if(typeof p.forkAt!="string"||p.forkAt.length===0){d.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){d.code(400).send({error:"cwd must be a non-empty string"});return}m.cwd=Y(p.cwd)}if(p.agentId!==void 0){if(typeof p.agentId!="string"||p.agentId.length===0){d.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"){d.code(400).send({error:"title must be a string"});return}m.title=p.title}if(p.mode!==void 0){if(p.mode!=="verbatim"&&p.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=p.mode}if(p.model!==void 0){if(typeof p.model!="string"||p.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}m.model=p.model}try{let g=await e.forkSession(f,m);d.code(201).send(g)}catch(g){let h=g;if(h.code===k.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===k.InvalidParams||h.code===k.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),n.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 p;try{p=fo(l.bundle)}catch(m){d.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(p,{replace:l.replace===!0,...f!==void 0?{cwd:f}:{}});d.code(201).send(m)}catch(m){let g=m;if(g.code===k.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:g.existingSessionId});return}d.code(500).send({error:g.message})}}),n.get("/v1/sessions/:id/compact/status",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f),m;if(p?m=p.summarizedThroughEntry:m=await e.getSummarizedThroughEntry(f),m===void 0&&!await e.hasRecord(f))return d.code(404).send({error:"session not found"}),d;let g=await e.getCompactionState(f),h=await e.getRollbackBreadcrumb(f),y=!1,v,b=await e.getHistory(f).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=m??0,C=b.length,_=b.slice(A).reduce((E,B)=>E+JSON.stringify(B.params).length,0);v=ws(_);let H=p?.currentModel,D=b.at(-1).recordedAt,R=p?.currentUsage;y=_o({summarizedThroughEntry:A,totalEntries:C,unsummarizedChars:_,compactionInFlight:e.getCompactionInFlight(),currentModel:H,lastActivityMs:D,nowMs:Date.now(),config:t.compaction,...typeof R?.used=="number"?{agentReportedUsed:R.used}:{},...typeof R?.size=="number"?{agentReportedSize:R.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:y,...v!=null?{approxTokens:v}:{},...g!=null?{compactionState:g}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.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})}),n.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(p){let m=p instanceof Error?p.message:String(p);d.code(409).send({error:m})}}),n.get("/v1/sessions/:id/history",async(c,d)=>{let l=c.params.id,f=c.query,p=f?.follow==="1"||f?.follow==="true",m=await e.resolveCanonicalId(l)??l,g=e.get(m),h,y,v=!1,w=1e4,b=[];if(g){p&&(y=g.onBroadcast(C=>{d.raw.writableEnded||(v?d.raw.write(JSON.stringify(C)+`
141
141
  `):(b.push(C),b.length>w&&b.shift()))})),c.raw.on("close",()=>{y?.(),d.raw.writableEnded||d.raw.end()});try{h=await g.getHistorySnapshot()}catch(C){throw y?.(),C}}else{let C=await e.getHistory(m);if(C===void 0)return d.code(404).send({error:"session not found"}),d;h=C}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let A=new Set;for(let C of h??[]){d.raw.write(JSON.stringify(C)+`
142
142
  `);let x=C;typeof x.recordedAt=="number"&&A.add(String(x.recordedAt))}for(;b.length>0;){let C=b.splice(0,b.length);for(let x of C){let _=x,H=typeof _.recordedAt=="number"?String(_.recordedAt):"";H&&A.has(H)||d.raw.write(JSON.stringify(x)+`
143
- `)}}return v=!0,y||d.raw.end(),d});function r(c,d,l){let p=typeof c=="string"?c.trim():"";if(p.length===0)return null;let f;try{f=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!f||typeof f!="object"||Array.isArray(f))return console.debug("events endpoint: skipping non-object JSONL line"),null;let m=f;if(typeof m.recordedAt!="number"||l!==void 0&&m.recordedAt<l||typeof m.params!="object"||m.params===null||Array.isArray(m.params))return null;let g=m.params;if(typeof g.update!="object"||g.update===null||Array.isArray(g.update))return null;let y=g.update.sessionUpdate;return typeof y!="string"||!d.has(y)?null:{recordedAt:m.recordedAt,entry:f}}function o(c,d,l){let f=d.params.update,m={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:l,update:f};return f.messageId!==void 0&&f.messageId!==null&&(m.messageId=f.messageId),m}async function*i(c,d,l,p){for await(let f of d){let m=r(f,l,p);if(m){let g=m.entry.params.update.sessionUpdate;yield{ts:m.recordedAt,row:o(c,m.entry,g)}}}}async function a(c,d,l,p){let f=Ss.createInterface({input:Is.createReadStream(d),crlfDelay:1/0}),m=i(c,f,l,p),g=await m.next(),h=g.done?null:g.value;return{sessionId:c,rl:f,gen:m,current:h,exhausted:h===null}}async function u(c){let d=await c.gen.next();d.done?(c.exhausted=!0,c.current=null):c.current=d.value}n.get("/v1/sessions/events",async(c,d)=>{let l=c.query,p=l.kinds;if(!p||p.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let f=p.split(",").map(w=>w.trim());if(f.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of f)if(!un.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...un].join(", ")}`}),d;let m=new Set(f),g;if(l.since!==void 0&&l.since.trim().length>0){let w=new Date(l.since);if(isNaN(w.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;g=w.getTime()}let h=await e.list({includeNonInteractive:!0}),y=g!==void 0?h.filter(w=>new Date(w.updatedAt).getTime()>=g):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let v=[];for(let w of y)try{let b=I.historyFile(w.sessionId),A=await a(w.sessionId,b,m,g);A.exhausted||v.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}c.raw.on("close",()=>{for(let w of v)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;v.length>0;){let w=-1,b=1/0;for(let C=0;C<v.length;C++){let x=v[C];x.current!==null&&x.current.ts<b&&(b=x.current.ts,w=C)}if(w===-1)break;let A=v[w];if(d.raw.write(JSON.stringify(A.current.row)+`
144
- `),await u(A),A.exhausted){try{A.rl.close()}catch{}v.splice(w,1)}}}catch(w){for(let b of v)try{b.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(c,d)=>{let l=c.params.id,p=c.query,f=await e.resolveCanonicalId(l)??l;if(!e.get(f)&&!await e.hasRecord(f))return d.code(404).send({error:"session not found"}),d;let g=p.kinds;if(!g||g.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=g.split(",").map(C=>C.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let C of h)if(!un.has(C))return d.code(400).send({error:`kind "${C}" is not queryable; allowed kinds: ${[...un].join(", ")}`}),d;let y=new Set(h),v;if(p.since!==void 0&&p.since.trim().length>0){let C=new Date(p.since);if(isNaN(C.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;v=C.getTime()}let w=I.historyFile(f),b=Is.createReadStream(w),A=Ss.createInterface({input:b,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let C of A){let x=typeof C=="string"?C.trim():"";if(x.length===0)continue;let _;try{_=JSON.parse(x)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!_||typeof _!="object"||Array.isArray(_)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let H=_;if(typeof H.recordedAt!="number"||typeof H.params!="object"||H.params===null||Array.isArray(H.params))continue;let D=H.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let R=D.update,E=R.sessionUpdate;if(typeof E!="string"||!y.has(E)||v!==void 0&&H.recordedAt<v)continue;let B={ts:new Date(H.recordedAt).toISOString(),kind:E,update:R};R.messageId!==void 0&&R.messageId!==null&&(B.messageId=R.messageId),d.raw.write(JSON.stringify(B)+`
145
- `)}}catch(C){if(C.code==="ENOENT")return d.raw.end(),d;throw C}return d.raw.end(),d}),n.get("/v1/sessions/:id/attention",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,f=e.get(p);return!f&&!await e.hasRecord(p)?(d.code(404).send({error:"session not found"}),d):f?{flags:f.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(c,d)=>{let l=c.query;if(!l.source||l.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let p=await e.list({includeNonInteractive:!0}),f=[];for(let m of p){let g=e.get(m.sessionId),h;g?h=g.listAttentionFlags():h=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let y of h)y.source===l.source&&f.push({...y,sessionId:m.sessionId})}return{flags:f}}),n.post("/v1/sessions/:id/attention/clear",async(c,d)=>{let l=c.params.id,p=await e.resolveCanonicalId(l)??l,m=c.body??{},g=typeof m.source=="string"?m.source:"",h=typeof m.reason=="string"?m.reason:"";if((g.length>0||h.length>0)&&!(g.length>0&&h.length>0)){d.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}g.length===0&&h.length;let y=e.get(p);if(y){if(g.length>0&&h.length>0)y.clearAttentionFlag(g,h);else{let C=Array.from(y.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of C)y.clearAttentionFlag(x.split("::")[0],x.split("::").slice(1).join("::"))}d.code(204).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}let v=e.store,w=await v.read(p);if(!w){d.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(g.length>0&&h.length>0){let C=`${g}::${h}`;A=b.filter(x=>`${x.source}::${x.reason}`!==C)}else A=[];if(A.length===b.length&&A.every((C,x)=>C.source===b[x].source&&C.reason===b[x].reason)){d.code(204).send();return}await v.write({...w,attentionFlags:A}),d.code(204).send()})}function ti(n,e,t,s={}){n.get("/v1/agents",async()=>Ne(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.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 u=await te(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:u.version,distribution:c,installed:!0,command:u.command})}catch(u){o.code(500).send({error:u.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:u}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:u}}catch(a){let u=a;if(u.code===k.AgentNotInstalled){o.code(404).send({error:u.message});return}o.code(409).send({error:u.message})}})}function ni(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var su=/^[A-Za-z0-9._-]+$/;function ln(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,u=t.get(a);if(!u){i.code(404).send({error:`unknown ${e}: ${a}`});return}return u}),n.post(r,async(o,i)=>{let a=o.body??{},u=ru(a);if("error"in u){i.code(400).send({error:u.error});return}try{let c=t.register(u.config);i.code(201).send(c)}catch(c){Mt(i,c)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(u){Mt(i,u)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let u=await t.startByName(a);i.code(200).send(u)}catch(u){Mt(i,u)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let u=await t.stopByName(a);i.code(200).send(u)}catch(u){Mt(i,u)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let u=await t.restartByName(a);i.code(200).send(u)}catch(u){Mt(i,u)}})}function Mt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function ru(n){let e=n.name;if(typeof e!="string"||!su.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function si(n,e){ln(n,"extension",e)}function ri(n,e){ln(n,"transformer",e)}function oi(n,e){n.get("/v1/config",async()=>e)}import{z as tt}from"zod";import*as et from"fs/promises";import*as ii from"path";import{randomBytes as yg,scrypt as ou,timingSafeEqual as iu}from"crypto";import{promisify as au}from"util";var du=au(ou);function ai(){return ii.join(I.home(),"password-hash")}var cu=128*1024*1024;async function di(){try{return(await et.readFile(ai(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ci(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await et.readFile(ai(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let u=await du(n,i,a.length,{N:s,r,p:o,maxmem:cu});return u.length!==a.length?!1:iu(u,a)}var uu=tt.object({password:tt.string().min(1),label:tt.string().min(1).max(256).optional(),ttlSec:tt.number().int().positive().optional()}),lu=tt.object({id:tt.string().optional()}).optional();function ui(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=fu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=uu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await di())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ci(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=lu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function fu(n){return n.ip||"unknown"}import{nanoid as As}from"nanoid";function ks(n){let e=[],t=[],s=!1,r=o=>{if(!s){s=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let u=JSON.parse(a);for(let c of e)c(u)}catch(u){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse WS frame: ${u.message}`}})}}),n.on("close",()=>r()),n.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,u)=>{n.send(i,c=>{if(c){u(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){s||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(u),o())},u=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as fi}from"crypto";import*as pi from"os";import*as mi from"path";function O(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function yu(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,o=s.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=s.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let u=a;if(typeof u.text=="string"&&(r+=u.text.length),u.content&&typeof u.content=="object"){let c=u.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function se(n,e,t){let s=n.get(e);if(!s)throw O(k.SessionNotFound,t??`session ${e} not found`);return s}async function fn(n,e){let t=Ze(n),s,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=fi(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],u=bs({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...u?{mintMcpServersForSwap:u}:{}})}catch(d){throw t!==void 0&&t.abandon(d instanceof Error?d:void 0),r!==void 0&&r.abandon(d instanceof Error?d:void 0),d}if(t!==void 0&&t.bindToSession(c),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let d=s,l=n.mcpTokenRegistry;r.complete(c),c.onClose(()=>{l.unbind(d)})}return Cu(c,n),c}function gi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=To({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=ks(t),a=new Ee(i),u={clientId:`hydra_client_${As(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let l of u.attached.values())e.manager.get(l.sessionId)?.detach(l.clientId);u.attached.clear()});let c=(l,p)=>{if(u.attached.get(l)?.readonly)throw O(k.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async l=>{let p=rr.parse(l??{});p.clientInfo?.name&&(u.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let f=p.clientInfo?.version;return f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f)),Au()}),o&&e.extensionCommands){let l=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let f=p??{},m=Array.isArray(f.commands)?f.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(g=>g!==void 0):[];return l.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{l.clear(o.name)})}if(o&&e.extensionMcp){let l=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async p=>{let f=p??{},m=typeof f.instructions=="string"?f.instructions:void 0,g=Array.isArray(f.tools)?f.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let v={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(v.outputSchema=y.outputSchema),v}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return l.register(o.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{l.clear(o.name)})}o?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async l=>{let p=l??{},f=Array.isArray(p.intercepts)?p.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,f),e.manager?.defaultTransformers.includes(o.name))){let m=e.transformers.resolveChain([o.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0,m=typeof p.method=="string"?p.method:void 0,g=p.envelope,h=p.route;if(!f)throw O(-32602,"emit_message requires sessionId");if(!m&&h!=="client_broadcast")throw O(-32602,"emit_message requires method");let y=se(e.manager,f),v=typeof p.respondsTo=="string"?p.respondsTo:void 0;if(v)return y.dischargeClaim(v,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(o.name,m,g)};if(h==="queue"){if(m!=="session/prompt")throw O(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,g)}}if(h==="daemon")return{ok:!0,response:await y.emitToChain(o.name,m,g)};if(h==="client_broadcast"){if(!g||typeof g!="object")throw O(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(g),{ok:!0}}throw O(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0;if(!f)throw O(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,f).requestPermissionFromClients(p)}),a.onRequest("hydra-acp/transformer/attach",async l=>bu(l,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async l=>{let p=l??{},f=typeof p.agentId=="string"?p.agentId:e.defaultAgent,m=typeof p.cwd=="string"?p.cwd:void 0,g=typeof p.parentSessionId=="string"?p.parentSessionId:void 0,h=p._meta&&typeof p._meta=="object"?p._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,v=y&&typeof y.title=="string"?y.title:void 0,w=y&&typeof y.model=="string"?y.model:void 0;if(!m&&g){let C=e.manager.get(g);C&&(m=C.cwd)}if(!m)throw O(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let b=typeof p.interactive=="boolean"?p.interactive:!1;return{childSessionId:(await e.manager.create({agentId:f,cwd:m,parentSessionId:g,interactive:b,transformChain:[],title:v,model:w})).sessionId}}),a.onRequest("hydra-acp/session/fork",async l=>{let p=l??{};if(typeof p.sessionId!="string")throw O(k.InvalidParams,"fork_session requires sessionId");let f=typeof p.forkAt=="string"?p.forkAt:void 0,m=typeof p.cwd=="string"?p.cwd:void 0,g=typeof p.agentId=="string"?p.agentId:void 0,h=typeof p.mode=="string"&&(p.mode==="verbatim"||p.mode==="synthesis")?p.mode:void 0,y=typeof p.model=="string"&&p.model.length>0?p.model:void 0;return await e.manager.forkSession(p.sessionId,{...f!==void 0?{forkAt:f}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{},...h!==void 0?{mode:h}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("hydra-acp/session/delete",async l=>{let p=l??{};if(typeof p.sessionId!="string")throw O(k.InvalidParams,"hydra-acp/session/delete requires sessionId");let f=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=e.manager.get(f);if(m)return await m.close({deleteRecord:!0}),await e.manager.waitForDeletion(f),await e.manager.hasRecord(f)&&await e.manager.deleteRecord(f),{deleted:!0,sessionId:f};if(!await e.manager.deleteRecord(f))throw O(k.SessionNotFound,`session ${f} not found`);return{deleted:!0,sessionId:f}}),a.onRequest("hydra-acp/child_session/await",async l=>{let p=l??{},f=typeof p.childSessionId=="string"?p.childSessionId:void 0,m=p.until==="idle"?"idle":"turn_complete",g=typeof p.timeoutMs=="number"?Math.min(p.timeoutMs,18e5):3e5;if(!f)throw O(-32602,"await_child requires childSessionId");let h=se(e.manager,f,`child session ${f} not found`);return new Promise(y=>{let b=[],A=[],C=0,x=!1,_,H,D=!1,R=()=>{D||(D=!0,clearTimeout(E),_?.(),H?.(),y(x?{entries:b,truncated:!0}:{entries:b}))};_=h.onBroadcast(B=>{let z=yu(B);for(b.push(B),A.push(z),C+=z;b.length>0&&(b.length>1e3||C>1048576);)b.shift(),C-=A.shift()??0,x=!0;m==="turn_complete"&&B.params?.update?.sessionUpdate==="turn_complete"&&R()});let E=setTimeout(R,g);typeof E.unref=="function"&&E.unref(),H=h.onClose(()=>R())})}),a.onRequest("hydra-acp/child_session/close",async l=>{let p=l??{},f=typeof p.childSessionId=="string"?p.childSessionId:void 0;if(!f)throw O(-32602,"close_child_session requires childSessionId");let m=e.manager.get(f);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async l=>Iu(l,o.name,e)),a.onRequest("hydra-acp/attention/clear",async l=>Su(l,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async l=>{let p=l??{},f=typeof p.token=="string"?p.token:void 0,m=typeof p.sessionId=="string"?p.sessionId:void 0,g=typeof p.estimatedRemainingMs=="number"?p.estimatedRemainingMs:void 0;return f&&m&&e.manager.get(m)?.keepAliveClaim(f,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async l=>{let p=l??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw O(k.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let f=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=await e.manager.loadToolBlob(f,p.hash);if(m===null)throw O(k.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async l=>wu(l,e)),a.onRequest("session/new",async l=>{let p=or.parse(l),f=dt(l?._meta),m=Array.isArray(f.transformers)&&f.transformers.every(E=>typeof E=="string")?f.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,v=p.mcpServers;if(f.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=fi(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let B={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};v=[...p.mcpServers??[],B]}let w,b,A=Ze(e);A!==void 0&&(v=[...v??[],...A.descriptors]);let C=bs({baselineMcpServers:p.mcpServers,stdinEnabled:f.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:p.cwd,agentId:f.agentId??e.defaultAgent,mcpServers:v,title:f.title,agentArgs:f.agentArgs,model:f.model,onInstallProgress:li(a),transformChain:g,originatingClient:u.clientInfo,...f.interactive!==void 0?{interactive:f.interactive}:{},...f.env!==void 0?{forwardedEnv:f.env}:{},...C?{mintMcpServersForSwap:C}:{}})}catch(E){throw y!==void 0&&y.abandon(E instanceof Error?E:void 0),b!==void 0&&b.abandon(E instanceof Error?E:void 0),A!==void 0&&A.abandon(E instanceof Error?E:void 0),E}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let E=h,B=e.mcpTokenRegistry;y.complete(x),x.onClose(()=>{B.unbind(E)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let E=w,B=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{B.unbind(E)})}A!==void 0&&A.bindToSession(x);let _,H;try{_=Rt(a,x,u),{entries:H}=await x.attach(_,"full")}catch(E){throw await x.close({deleteRecord:!1}).catch(()=>{}),E}u.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:_.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let E of H){if(a.isClosed())break;await a.notify(E.method,E.params).catch(()=>{})}})()});let D=pn(x),R=mn(x);return{sessionId:x.sessionId,...D?{modes:D}:{},...R?{models:R}:{},configOptions:x.buildConfigOptions(),_meta:gn(e.manager,x,{clientId:_.clientId})}}),a.onRequest("session/attach",async l=>{let p=ar.parse(l),f=p.clientInfo?.version;f&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,f):e.onTransformerVersion?.(o.name,f));let m=dt(p._meta),g=m.resume,h=m.readonly===!0,y=m.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!g} readonly=${h}`);let v=g?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(v);if(!w&&h){let R=await e.manager.loadFromDisk(v);if(!R)throw O(k.SessionNotFound,`session ${p.sessionId} not found`);let E=await e.manager.loadHistory(v),B=p.clientId??`cli_${As(8)}`;u.attached.set(R.hydraSessionId,{sessionId:R.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${R.hydraSessionId} clientId=${B} attachedCount=${u.attached.size} replayed=${E.length}`);for(let z of E)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:R.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:E.length,_meta:ku(R)}}let b=!w;if(!w){let R=await e.manager.loadFromDisk(v),E=R;if(g&&(E={...R,hydraSessionId:p.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!E)throw O(k.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(E.agentId,E.upstreamSessionId))throw O(k.SessionNotFound,`session ${p.sessionId} was deleted`);let B=E.originatingClient?E:{...E,originatingClient:u.clientInfo},z=y!==void 0?{...B,forwardedEnv:y}:B;w=await fn(e,{...z,onInstallProgress:li(a)})}let A=Rt(a,w,u,p.clientInfo,p.clientId),C=m.replayMode==="drip",{entries:x,appliedPolicy:_}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:C,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(u.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${u.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${_} replayed=${x.length} readonly=${h}${C?" replayMode=drip":""}`),C){let R=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,E=750;(async()=>{let B=null;for(let z of x){let de=typeof z.recordedAt=="number"?z.recordedAt:null;if(B!==null&&de!==null){let rt=Math.min(E,Math.max(0,(de-B)/R));rt>0&&await new Promise(Et=>setTimeout(Et,rt))}de!==null&&(B=de);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let R=0;R<x.length&&!a.isClosed();R++){let E=x[R],B=a.notify(E.method,E.params).catch(()=>{});(R+1)%200===0&&await B}w.replayPendingPermissions(A);let H=pn(w),D=mn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:_,replayed:x.length,...H?{modes:H}:{},...D?{models:D}:{},configOptions:w.buildConfigOptions(),_meta:gn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async l=>{let p=dr.parse(l),f=u.attached.get(p.sessionId);if(!f)throw O(k.SessionNotFound,"client not attached to that session");let m=e.manager.get(p.sessionId);return m?.detach(f.clientId),u.attached.delete(p.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[at]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async l=>{let p=cr.parse(l??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==qt).map(ur)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw O(k.InternalError,"agent registry unavailable");return Ne(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async l=>{let p=l??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw O(k.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(p.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async l=>{let p=lr.parse(l);c(p.sessionId,"session/prompt");let f=u.attached.get(p.sessionId);if(!f)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),O(k.SessionNotFound,"not attached to session");let m=e.manager.get(p.sessionId);if(!m){let g=await e.manager.loadFromDisk(p.sessionId);if(!g)throw O(k.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),m=await fn(e,g);let h=Rt(a,m,u,void 0,f.clientId);await m.attach(h,"none")}return m.prompt(f.clientId,p)});let d=l=>{let p;try{p=Ht.parse(l)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let f=u.attached.get(p.sessionId);if(!f)return;if(f.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let m=e.manager.get(p.sessionId);m&&m.cancel(f.clientId).catch(g=>{n.log.warn(`session/cancel for ${p.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async l=>{let p=Ht.parse(l);return c(p.sessionId,"session/cancel"),d(l),null}),a.onRequest("hydra-acp/prompt/cancel",async l=>{let p=pr.parse(l);return c(p.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async l=>{let p=Ht.parse(l);return c(p.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async l=>{let p=mr.parse(l);return c(p.sessionId,"hydra-acp/prompt/update"),se(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async l=>{let p=gr.parse(l);c(p.sessionId,"hydra-acp/prompt/amend");let f=u.attached.get(p.sessionId);if(!f)throw O(k.SessionNotFound,"not attached to session");return se(e.manager,p.sessionId).amendPrompt(f.clientId,p)}),a.onRequest("session/resume",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0;if(!f)throw O(k.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(f)??f,g=e.manager.get(m);if(!g){let w=await e.manager.loadFromDisk(m);if(!w)throw O(k.SessionNotFound,`session ${f} not found in memory or on disk`);g=await fn(e,w)}let h=Rt(a,g,u);await g.attach(h,"pending_only"),u.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1}),g.replayPendingPermissions(h);let y=pn(g),v=mn(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...v?{models:v}:{},configOptions:g.buildConfigOptions(),_meta:gn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/load",async l=>{let p=l??{},f=typeof p.sessionId=="string"?p.sessionId:void 0;if(!f)throw O(k.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(f)??f,g=e.manager.get(m);if(!g){let b=await e.manager.loadFromDisk(m);if(!b)throw O(k.SessionNotFound,`session ${f} not found in memory or on disk`);g=await fn(e,b)}let h=Rt(a,g,u),{entries:y}=await g.attach(h,"pending_only");u.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}g.replayPendingPermissions(h);let v=pn(g),w=mn(g);return{sessionId:g.sessionId,...v?{modes:v}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:gn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async l=>{let p=l?.sessionId;typeof p=="string"&&c(p,"session/set_model");let f=vu(l,e.manager);if(f.kind==="error")throw n.log.warn(f.logMessage),O(f.code,f.message);if(f.kind==="no_op")return n.log.warn(f.logMessage),await a.notify("session/update",{sessionId:f.sessionId,update:{sessionUpdate:"current_model_update",currentModel:f.currentModel}}).catch(()=>{}),null;n.log.info(f.logMessage);let{modelId:m}=f,g=await f.session.forwardRequest("session/set_model",{...l,modelId:m});return f.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async l=>{let p=l,f=p?.sessionId;if(typeof f=="string"&&c(f,"session/set_mode"),!p||typeof p.sessionId!="string")throw O(k.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw O(k.InvalidParams,"session/set_mode requires string modeId");let m=se(e.manager,p.sessionId),g=await m.forwardRequest("session/set_mode",l);return m.applyModeChange(p.modeId),g}),a.onRequest("session/set_config_option",async l=>{let p=l,f=y=>O(k.InvalidParams,y),m=p?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!p||typeof p.sessionId!="string")throw f("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw f("session/set_config_option requires string configId");if(typeof p.value!="string")throw f("session/set_config_option requires string value");let g=se(e.manager,p.sessionId),h=g.buildConfigOptions().find(y=>y.id===p.configId);if(!h)throw f(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(y=>y.value===p.value))throw f(`value ${JSON.stringify(p.value)} is not valid for configId ${JSON.stringify(p.configId)}`);switch(p.configId){case"model":{p.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:p.sessionId,modelId:p.value}),g.applyModelChange(p.value);break}case"mode":{p.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:p.sessionId,modeId:p.value}),g.applyModeChange(p.value);break}case"agent":{p.value!==g.agentId&&await g.setAgent(p.value);break}default:throw f(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(l,p)=>{let f=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=p.startsWith("session/"),g=p.startsWith("hydra-acp/");if(!m&&!g||l===null||typeof l!="object"||f.has(p))throw O(k.MethodNotFound,`Method not found: ${p}`);let h=l.sessionId;if(typeof h!="string")throw O(k.MethodNotFound,`Method not found: ${p}`);return c(h,p),se(e.manager,h).forwardRequest(p,l)})})}async function wu(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw O(k.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let f=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(f)}let u=a.authMethods??[],c=u.find(f=>f.id===s);if(!c){let f=u.map(m=>m.id);throw O(k.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${f.map(m=>JSON.stringify(m)).join(", ")}]`)}let d=c._meta?.type,l=(()=>{let f=c._meta?.["terminal-auth"];if(f&&typeof f=="object"&&!Array.isArray(f))return f})();if((c.type??(d==="agent"||d==="terminal"?d:l!==void 0?"terminal":"agent"))==="terminal"){let f=(w,b)=>{if(!Array.isArray(w))throw O(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw O(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be string[]; got non-string entry ${JSON.stringify(A)}`);return w},m=await e.manager.planSpawnForAgent(a.agentId),g,h;if(l?.args!==void 0){let w=typeof l.command=="string"?l.command:void 0;g=w!==void 0&&mi.isAbsolute(w)?w:m.command,h=f(l.args,'_meta["terminal-auth"].args')}else{let w=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,b=w!==void 0?f(w.raw,w.label):[];g=m.command,h=[...m.args,...b]}let y={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(y[w]=b);Object.assign(y,m.env);let v=pi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g,args:h,env:y,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(f){throw Ae(f,a)}}function li(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(hr,t).catch(()=>{})}}function pn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function mn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function vu(n,e){if(!n||typeof n!="object")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:k.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=qe(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(u=>u.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:k.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function bu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw O(k.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw O(k.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw O(k.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function Iu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw O(k.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw O(k.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function Su(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw O(k.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw O(k.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function ku(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[at]:Ot(e,t)}}function gn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return it(e.agentMeta,Ot(s,r))}function Au(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{},resume:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:it(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Cu(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Rt(n,e,t,s,r){return{clientId:r??`cli_${As(8)}`,connection:n,clientInfo:s}}var hn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((i,a)=>{t=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as xu}from"crypto";import{McpServer as Mu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ru}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as G}from"zod";function*Cs(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;if(s.method!=="session/update")continue;let o=s.params?.update;!o||typeof o.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:o.sessionUpdate,update:o})}}function re(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var hi="Bearer ";function nt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(hi))return;let t=e.slice(hi.length).trim();return t.length>0?t:void 0}function Eu(n){let e=new Mu({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:G.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return re(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:G.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return re(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:G.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:G.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:G.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let o=await n.streamRead(t,s,r);return re(o)}),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:G.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:G.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),o=n.streamInfo();return re({outcome:r,writeCursor:o.writeCursor,closed:o.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:G.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:G.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:G.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:G.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:G.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:G.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:G.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:G.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:G.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return re(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return re(t)}),e}var Pu=1e4;function yi(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let c=Eu(a),d=new Ru({sessionIdGenerator:()=>xu()});await c.connect(d);let l={server:c,transport:d};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await c.close()}catch{}}),d}async function r(i,a){let u=nt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(u);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let d;if(c.session!==void 0)d=c.session;else{let p,f=new Promise(g=>{p=setTimeout(()=>g(void 0),Pu)}),m=await Promise.race([c.sessionReady.catch(()=>{}),f]);if(p!==void 0&&clearTimeout(p),m===void 0){a.code(503).send({error:"session not ready"});return}d=m}let l=await s(u,d);a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as Tu}from"crypto";import{McpServer as _u}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as $u}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function Fu(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Ou(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function Hu(n){let e=new _u({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:xe.string().min(1).describe("Case-insensitive substring to search for."),limit:xe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:xe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=await o.getHistorySnapshot(),a=[];for(let{entryId:c,entry:d,kind:l}of Cs(i)){if(l==="tool_call"&&!r)continue;let p=ze([d]),f=p.toLowerCase().indexOf(t.toLowerCase());if(f<0)continue;let m=Fu(l),g=Ou(p,f),h=typeof d.recordedAt=="number"?String(d.recordedAt):void 0;if(a.push({entryId:c,speaker:m,snippet:g,timestamp:h}),a.length>=s)break}let u=a.length>=s&&a.length<i.length;return re({matches:a,total_matched:a.length,truncated:u})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:xe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:xe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return re({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let o=s-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getHistorySnapshot(),a=Math.min(t,i.length-1),u=Math.min(s,i.length-1),c=a>t||u<s;if(a>u)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let d=i.slice(a,u+1),l=ze(d);return{content:[{type:"text",text:l}],structuredContent:{text:l,entry_count:d.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:xe.string().optional(),file_path:xe.string().optional(),limit:xe.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let i=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!i&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let u=await o.getHistorySnapshot(),c=[],d=new Map;for(let{entryId:f,entry:m,kind:g,update:h}of Cs(u)){if(g!=="tool_call"&&g!=="tool_call_update")continue;let y=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${f}`,v=d.get(y);v||(v={entryId:f,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(y,v),c.push(y)),typeof h.name=="string"&&h.name.length>0?v.toolName=h.name:(v.toolName==="(unnamed)"||g==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(v.toolName=h.title);let w=h.rawInput;if(w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0)for(let[b,A]of Object.entries(w))v.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!v.locations.includes(A)&&v.locations.push(A)}typeof h.status=="string"&&(v.status=h.status),m.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(m.recordedAt))}let l=[];for(let f of c){let m=d.get(f);if(t!==void 0&&m.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),y=["file_path","filePath","path"],v=!1;for(let w of y){let b=m.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){v=!0;break}}if(!v){for(let w of m.locations)if(w.toLowerCase().includes(h)){v=!0;break}}if(!v)continue}let g={};for(let[h,y]of Object.entries(m.rawInput))typeof y=="string"?g[h]=y.length>500?y.slice(0,497)+"\u2026":y:(typeof y=="number"||typeof y=="boolean")&&(g[h]=y);if(m.locations.length>0&&g.locations===void 0&&(g.locations=m.locations),l.push({entryId:m.entryId,tool:m.toolName,args:g,status:m.status,timestamp:m.timestamp}),l.length>=r)break}let p=l.length>=r;return re({calls:l,truncated:p})}),e}var Nu=1e4;function wi(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let c=Hu(a),d=new $u({sessionIdGenerator:()=>Tu()});await c.connect(d);let l={server:c,transport:d};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await c.close()}catch{}}),d}async function r(i,a){let u=nt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(u);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let l=await s(u,async()=>{if(c.session!==void 0)return c.session;let p,f=new Promise(g=>{p=setTimeout(()=>g(void 0),Nu)}),m=await Promise.race([c.sessionReady.catch(()=>{}),f]);if(p!==void 0&&clearTimeout(p),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var yn=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Ju}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Wu}from"crypto";import{Server as ju}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Bu,ListToolsRequestSchema as Uu}from"@modelcontextprotocol/sdk/types.js";function vi(n,e,t){let s=typeof t=="function"?async()=>t():async()=>t,r=new ju({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=new Map(e.tools.map(i=>[i.name,i]));return r.setRequestHandler(Uu,async()=>({tools:e.tools.map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema!==void 0?{outputSchema:i.outputSchema}:{}}))})),r.setRequestHandler(Bu,async(i,a)=>{let u=i.params.name;if(!o.has(u))return wn(`unknown tool: ${u}`);let c=a._meta?.progressToken??a.requestId,d=Lu(c,a.sendNotification);try{let l=await s(),p=await qu(e.connection,n,u,i.params.arguments??{},l);return zu(p,u)}catch(l){return wn(l instanceof Error?l.message:String(l))}finally{d()}}),r}var Du=15e3;function Lu(n,e,t=Du){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function qu(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function zu(n,e){if(n===null||typeof n!="object")return wn(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:wn(`extension ${e} omitted content array`)}function wn(n){return{content:[{type:"text",text:n}],isError:!0}}var Qu=1e4;function bi(n,e,t){let s=new Map;async function r(c){try{await c.transport.close()}catch{}try{await c.server.close()}catch{}}function o(c){for(let d of s.values()){let l=d.get(c);l!==void 0&&(d.delete(c),r(l))}}t.onChange(c=>{o(c)});async function i(c,d){let l=s.get(c);l===void 0&&(l=new Map,s.set(c,l),e.addDisposer(c,async()=>{let y=s.get(c);if(y!==void 0){s.delete(c);for(let v of y.values())await r(v)}}));let p=l.get(d);if(p!==void 0)return p.transport;let f=t.lookup(d);if(f===void 0)return;let g=vi(d,f,async()=>{let y=e.lookup(c);if(y===void 0)throw new Error("mcp token no longer bound");if(y.session!==void 0)return y.session.sessionId;let v,w=new Promise(A=>{v=setTimeout(()=>A(void 0),Qu)}),b=await Promise.race([y.sessionReady.catch(()=>{}),w]);if(v!==void 0&&clearTimeout(v),b===void 0)throw new Error("session not ready");return b.sessionId}),h=new Ju({sessionIdGenerator:()=>Wu()});return await g.connect(h),l.set(d,{server:g,transport:h}),h}async function a(c,d){let l=nt(c);if(l===void 0){d.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){d.code(404).send({error:"unknown mcp token"});return}let f=c.params.name,m=await i(l,f);if(m===void 0){d.code(404).send({error:`unknown mcp server: ${f}`});return}d.hijack(),await m.handleRequest(c.raw,d.raw,c.body)}let u={config:{skipAuth:!0}};n.post("/mcp/:name",u,async(c,d)=>{await a(c,d)}),n.get("/mcp/:name",u,async(c,d)=>{await a(c,d)}),n.delete("/mcp/:name",u,async(c,d)=>{await a(c,d)})}async function Yu(n,e){el(n);let t=n.daemon.tls?await st.readFile(Y(n.daemon.tls.key)):void 0,s=n.daemon.tls?await st.readFile(Y(n.daemon.tls.cert)):void 0;await st.mkdir(I.home(),{recursive:!0});let{stream:r,fileStream:o}=await Xu(n.daemon.logLevel),i=Vu({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(Ku,{options:{handleProtocols:Es}}),Rn($=>{i.log.info($)}),Tn($=>{i.log.info($)});let a=await tn.load(),u=new an,c=new on,d=new rn([new nn(e),new sn(a),c]),l=Po({validator:d});i.addHook("onRequest",async($,ce)=>{$.routeOptions.config?.skipAuth||$.url==="/acp"||$.url?.startsWith("/acp?")||await l($,ce)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let f=setInterval(()=>{u.sweepExpired()},300*1e3);f.unref();let m=new ot(n,{onFetched:()=>{bo(m,v)}});ms($=>i.log.info($));let g={info:$=>i.log.info($),warn:$=>i.log.warn($)},h=$=>he.spawn({...$,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});qs(n.compressToolContent);let y=new Zt,v=new bt(m,h,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:y,defaultCwd:n.defaultCwd}),w=new Yt(Hs(n),void 0,{tokenRegistry:c}),b=new Xt(Ns(n),void 0,{tokenRegistry:c});ni(i,K,ko(n));let A=new hn,C=new yn,x,_=()=>{if(x!==void 0)return x;let $=i.server.address();return x=`http://127.0.0.1:${$&&typeof $=="object"?$.port:n.daemon.port}`,x};ei(i,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:C,mcpTokenRegistry:A,getDaemonOrigin:_}),ti(i,m,v,{npmRegistry:n.npmRegistry}),si(i,w),ri(i,b),oi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),ui(i,{store:a,rateLimiter:u}),yi(i,A),wi(i,A),bi(i,A,C),gi(i,{validator:d,manager:v,defaultAgent:n.defaultAgent,processRegistry:c,onExtensionVersion:($,ce)=>w.reportVersion($,ce),onTransformerVersion:($,ce)=>b.reportVersion($,ce),transformers:b,extensionCommands:y,mcpTokenRegistry:A,extensionMcp:C,getDaemonOrigin:_,registry:m});let H=!!n.daemon.tls;await i.listen({host:H?"127.0.0.1":n.daemon.host,port:H?0:n.daemon.port});let D=i.server.address(),R=D&&typeof D=="object"?D.port:n.daemon.port,E,B=n.daemon.host,z=R;if(H&&t&&s){E=Zu({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:R,tlsOptions:{key:t,cert:s},logger:i.log});let $=E.address();$&&typeof $=="object"&&(z=$.port)}await st.mkdir(I.home(),{recursive:!0}),await vo({pid:process.pid,host:B,port:z,loopbackPort:R,startedAt:new Date().toISOString()});let de={daemonUrl:`http://127.0.0.1:${R}`,daemonHost:"127.0.0.1",daemonPort:R,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${R}/acp`,hydraHome:I.home()};w.setContext(de),b.setContext(de),await w.start(),await b.start();try{await v.reconcilePermissionFlags()}catch($){i.log.warn(`permission flag reconcile failed: ${$.message}`)}v.resurrectPendingQueues().catch($=>{i.log.warn(`queue replay scan failed: ${$.message}`)}),v.resumePendingCompactions().catch($=>{i.log.warn(`compaction resume scan failed: ${$.message}`)}),v.resumePendingAgentSwaps().catch($=>{i.log.warn(`agent-swap resume scan failed: ${$.message}`)});let rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Et=rt>0?Io({registry:m,manager:v,intervalMs:rt,logger:g}):void 0,xs=n.daemon.sessionGcIntervalMinutes*60*1e3,Ci=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ms=xs>0?So({manager:v,intervalMs:xs,maxAgeMs:Ci,logger:g}):void 0;return{app:i,manager:v,registry:m,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:C,processRegistry:c,shutdown:async()=>{Ms&&Ms(),Et&&Et(),clearInterval(p),clearInterval(f);let $=async(ce,xi)=>{try{await xi()}catch(vn){i.log.warn(`shutdown step ${ce} failed: ${vn instanceof Error?vn.message:String(vn)}`)}};await $("sessionTokenStore.flush",()=>a.flush()),await $("extensions.stop",()=>w.stop()),await $("transformers.stop",()=>b.stop()),await $("manager.closeAll",()=>v.closeAll()),await $("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await $("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await $("manager.flushMetaWrites",()=>v.flushMetaWrites()),await $("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),Rn(null),Tn(null),ms(null),E&&await $("tlsTerminator.close",()=>new Promise(ce=>E.close(()=>ce()))),await $("app.close",()=>i.close());try{Si.unlinkSync(I.pidFile())}catch{}await $("fileStream.flushSync",()=>o.flushSync())}}}async function Xu(n){let e=await Gu({file:I.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=Ii.destination(2);return{stream:Ii.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Zu(n){let e=Ai.createServer(n.tlsOptions,t=>{let s=ki.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",o),s.on("error",o),t.on("close",()=>o()),s.on("close",()=>o()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function el(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{he as AgentInstance,Ee as JsonRpcConnection,ot as Registry,Pe as Session,bt as SessionManager,Qi as defaultConfig,Pi as ensureServiceToken,Pt as generateServiceToken,Bs as loadConfig,Ei as loadServiceToken,On as ndjsonStreamFromStdio,I as paths,te as planSpawn,Yu as startDaemon,Wi as writeConfig,ks as wsToMessageStream};
143
+ `)}}return v=!0,y||d.raw.end(),d});function r(c,d,l){let f=typeof c=="string"?c.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"||l!==void 0&&m.recordedAt<l||typeof m.params!="object"||m.params===null||Array.isArray(m.params))return null;let g=m.params;if(typeof g.update!="object"||g.update===null||Array.isArray(g.update))return null;let y=g.update.sessionUpdate;return typeof y!="string"||!d.has(y)?null:{recordedAt:m.recordedAt,entry:p}}function o(c,d,l){let p=d.params.update,m={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:l,update:p};return p.messageId!==void 0&&p.messageId!==null&&(m.messageId=p.messageId),m}async function*i(c,d,l,f){for await(let p of d){let m=r(p,l,f);if(m){let g=m.entry.params.update.sessionUpdate;yield{ts:m.recordedAt,row:o(c,m.entry,g)}}}}async function a(c,d,l,f){let p=ks.createInterface({input:Ss.createReadStream(d),crlfDelay:1/0}),m=i(c,p,l,f),g=await m.next(),h=g.done?null:g.value;return{sessionId:c,rl:p,gen:m,current:h,exhausted:h===null}}async function u(c){let d=await c.gen.next();d.done?(c.exhausted=!0,c.current=null):c.current=d.value}n.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 p=f.split(",").map(w=>w.trim());if(p.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of p)if(!ln.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let m=new Set(p),g;if(l.since!==void 0&&l.since.trim().length>0){let w=new Date(l.since);if(isNaN(w.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;g=w.getTime()}let h=await e.list({includeNonInteractive:!0}),y=g!==void 0?h.filter(w=>new Date(w.updatedAt).getTime()>=g):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let v=[];for(let w of y)try{let b=I.historyFile(w.sessionId),A=await a(w.sessionId,b,m,g);A.exhausted||v.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}c.raw.on("close",()=>{for(let w of v)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;v.length>0;){let w=-1,b=1/0;for(let C=0;C<v.length;C++){let x=v[C];x.current!==null&&x.current.ts<b&&(b=x.current.ts,w=C)}if(w===-1)break;let A=v[w];if(d.raw.write(JSON.stringify(A.current.row)+`
144
+ `),await u(A),A.exhausted){try{A.rl.close()}catch{}v.splice(w,1)}}}catch(w){for(let b of v)try{b.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(c,d)=>{let l=c.params.id,f=c.query,p=await e.resolveCanonicalId(l)??l;if(!e.get(p)&&!await e.hasRecord(p))return d.code(404).send({error:"session not found"}),d;let g=f.kinds;if(!g||g.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=g.split(",").map(C=>C.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let C of h)if(!ln.has(C))return d.code(400).send({error:`kind "${C}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let y=new Set(h),v;if(f.since!==void 0&&f.since.trim().length>0){let C=new Date(f.since);if(isNaN(C.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;v=C.getTime()}let w=I.historyFile(p),b=Ss.createReadStream(w),A=ks.createInterface({input:b,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let C of A){let x=typeof C=="string"?C.trim():"";if(x.length===0)continue;let _;try{_=JSON.parse(x)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!_||typeof _!="object"||Array.isArray(_)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let H=_;if(typeof H.recordedAt!="number"||typeof H.params!="object"||H.params===null||Array.isArray(H.params))continue;let D=H.params;if(typeof D.update!="object"||D.update===null||Array.isArray(D.update))continue;let R=D.update,E=R.sessionUpdate;if(typeof E!="string"||!y.has(E)||v!==void 0&&H.recordedAt<v)continue;let B={ts:new Date(H.recordedAt).toISOString(),kind:E,update:R};R.messageId!==void 0&&R.messageId!==null&&(B.messageId=R.messageId),d.raw.write(JSON.stringify(B)+`
145
+ `)}}catch(C){if(C.code==="ENOENT")return d.raw.end(),d;throw C}return d.raw.end(),d}),n.get("/v1/sessions/:id/attention",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,p=e.get(f);return!p&&!await e.hasRecord(f)?(d.code(404).send({error:"session not found"}),d):p?{flags:p.listAttentionFlags()}:{flags:(await e.store.read(f))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(c,d)=>{let l=c.query;if(!l.source||l.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let f=await e.list({includeNonInteractive:!0}),p=[];for(let m of f){let g=e.get(m.sessionId),h;g?h=g.listAttentionFlags():h=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let y of h)y.source===l.source&&p.push({...y,sessionId:m.sessionId})}return{flags:p}}),n.post("/v1/sessions/:id/attention/clear",async(c,d)=>{let l=c.params.id,f=await e.resolveCanonicalId(l)??l,m=c.body??{},g=typeof m.source=="string"?m.source:"",h=typeof m.reason=="string"?m.reason:"";if((g.length>0||h.length>0)&&!(g.length>0&&h.length>0)){d.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}g.length===0&&h.length;let y=e.get(f);if(y){if(g.length>0&&h.length>0)y.clearAttentionFlag(g,h);else{let C=Array.from(y.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of C)y.clearAttentionFlag(x.split("::")[0],x.split("::").slice(1).join("::"))}d.code(204).send();return}if(!await e.hasRecord(f)){d.code(404).send({error:"session not found"});return}let v=e.store,w=await v.read(f);if(!w){d.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(g.length>0&&h.length>0){let C=`${g}::${h}`;A=b.filter(x=>`${x.source}::${x.reason}`!==C)}else A=[];if(A.length===b.length&&A.every((C,x)=>C.source===b[x].source&&C.reason===b[x].reason)){d.code(204).send();return}await v.write({...w,attentionFlags:A}),d.code(204).send()})}function ti(n,e,t,s={}){n.get("/v1/agents",async()=>Ne(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.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 u=await te(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:u.version,distribution:c,installed:!0,command:u.command})}catch(u){o.code(500).send({error:u.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:u}=await t.syncFromAgent(i);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:u}}catch(a){let u=a;if(u.code===k.AgentNotInstalled){o.code(404).send({error:u.message});return}o.code(409).send({error:u.message})}})}function ni(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var ru=/^[A-Za-z0-9._-]+$/;function fn(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,u=t.get(a);if(!u){i.code(404).send({error:`unknown ${e}: ${a}`});return}return u}),n.post(r,async(o,i)=>{let a=o.body??{},u=ou(a);if("error"in u){i.code(400).send({error:u.error});return}try{let c=t.register(u.config);i.code(201).send(c)}catch(c){xt(i,c)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(u){xt(i,u)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let u=await t.startByName(a);i.code(200).send(u)}catch(u){xt(i,u)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let u=await t.stopByName(a);i.code(200).send(u)}catch(u){xt(i,u)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let u=await t.restartByName(a);i.code(200).send(u)}catch(u){xt(i,u)}})}function xt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function ou(n){let e=n.name;if(typeof e!="string"||!ru.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function si(n,e){fn(n,"extension",e)}function ri(n,e){fn(n,"transformer",e)}function oi(n,e){n.get("/v1/config",async()=>e)}import{z as et}from"zod";import*as Ze from"fs/promises";import*as ii from"path";import{randomBytes as vg,scrypt as iu,timingSafeEqual as au}from"crypto";import{promisify as du}from"util";var cu=du(iu);function ai(){return ii.join(I.home(),"password-hash")}var uu=128*1024*1024;async function di(){try{return(await Ze.readFile(ai(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ci(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await Ze.readFile(ai(),"utf8")).trim()}catch(c){if(c.code==="ENOENT")return!1;throw c}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let u=await cu(n,i,a.length,{N:s,r,p:o,maxmem:uu});return u.length!==a.length?!1:au(u,a)}var lu=et.object({password:et.string().min(1),label:et.string().min(1).max(256).optional(),ttlSec:et.number().int().positive().optional()}),fu=et.object({id:et.string().optional()}).optional();function ui(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=pu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=lu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await di())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ci(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=fu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function pu(n){return n.ip||"unknown"}import{nanoid as Cs}from"nanoid";function As(n){let e=[],t=[],s=!1,r=o=>{if(!s){s=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let u=JSON.parse(a);for(let c of e)c(u)}catch(u){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:k.ParseError,message:`Failed to parse WS frame: ${u.message}`}})}}),n.on("close",()=>r()),n.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,u)=>{n.send(i,c=>{if(c){u(c);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){s||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(u),o())},u=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as fi}from"crypto";import*as pi from"os";import*as mi from"path";function O(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function wu(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,o=s.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=s.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let u=a;if(typeof u.text=="string"&&(r+=u.text.length),u.content&&typeof u.content=="object"){let c=u.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function se(n,e,t){let s=n.get(e);if(!s)throw O(k.SessionNotFound,t??`session ${e} not found`);return s}async function pn(n,e){let t=Xe(n),s,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=fi(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],u=Is({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),c;try{c=await n.manager.resurrect({...e,mcpServers:a,...u?{mintMcpServersForSwap:u}:{}})}catch(d){throw t!==void 0&&t.abandon(d instanceof Error?d:void 0),r!==void 0&&r.abandon(d instanceof Error?d:void 0),d}if(t!==void 0&&t.bindToSession(c),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let d=s,l=n.mcpTokenRegistry;r.complete(c),c.onClose(()=>{l.unbind(d)})}return xu(c,n),c}function gi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=To({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=As(t),a=new Ee(i),u={clientId:`hydra_client_${Cs(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let l of u.attached.values())e.manager.get(l.sessionId)?.detach(l.clientId);u.attached.clear()});let c=(l,f)=>{if(u.attached.get(l)?.readonly)throw O(k.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async l=>{let f=or.parse(l??{});f.clientInfo?.name&&(u.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p)),Cu()}),o&&e.extensionCommands){let l=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},m=Array.isArray(p.commands)?p.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(g=>g!==void 0):[];return l.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{l.clear(o.name)})}if(o&&e.extensionMcp){let l=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},m=typeof p.instructions=="string"?p.instructions:void 0,g=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let v={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(v.outputSchema=y.outputSchema),v}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return l.register(o.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{l.clear(o.name)})}o?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async l=>{let f=l??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,p),e.manager?.defaultTransformers.includes(o.name))){let m=e.transformers.resolveChain([o.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.method=="string"?f.method:void 0,g=f.envelope,h=f.route;if(!p)throw O(-32602,"emit_message requires sessionId");if(!m&&h!=="client_broadcast")throw O(-32602,"emit_message requires method");let y=se(e.manager,p),v=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(v)return y.dischargeClaim(v,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(o.name,m,g)};if(h==="queue"){if(m!=="session/prompt")throw O(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,g)}}if(h==="daemon")return{ok:!0,response:await y.emitToChain(o.name,m,g)};if(h==="client_broadcast"){if(!g||typeof g!="object")throw O(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(g),{ok:!0}}throw O(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw O(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async l=>Iu(l,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async l=>{let f=l??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,m=typeof f.cwd=="string"?f.cwd:void 0,g=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,h=f._meta&&typeof f._meta=="object"?f._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,v=y&&typeof y.title=="string"?y.title:void 0,w=y&&typeof y.model=="string"?y.model:void 0;if(!m&&g){let C=e.manager.get(g);C&&(m=C.cwd)}if(!m)throw O(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let b=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:g,interactive:b,transformChain:[],title:v,model:w})).sessionId}}),a.onRequest("hydra-acp/session/fork",async l=>{let f=l??{};if(typeof f.sessionId!="string")throw O(k.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,m=typeof f.cwd=="string"?f.cwd:void 0,g=typeof f.agentId=="string"?f.agentId:void 0,h=typeof f.mode=="string"&&(f.mode==="verbatim"||f.mode==="synthesis")?f.mode:void 0,y=typeof f.model=="string"&&f.model.length>0?f.model:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{},...h!==void 0?{mode:h}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("hydra-acp/session/delete",async l=>{let f=l??{};if(typeof f.sessionId!="string")throw O(k.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}),await e.manager.waitForDeletion(p),await e.manager.hasRecord(p)&&await e.manager.deleteRecord(p),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw O(k.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async l=>{let f=l??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,m=f.until==="idle"?"idle":"turn_complete",g=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw O(-32602,"await_child requires childSessionId");let h=se(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let b=[],A=[],C=0,x=!1,_,H,D=!1,R=()=>{D||(D=!0,clearTimeout(E),_?.(),H?.(),y(x?{entries:b,truncated:!0}:{entries:b}))};_=h.onBroadcast(B=>{let z=wu(B);for(b.push(B),A.push(z),C+=z;b.length>0&&(b.length>1e3||C>1048576);)b.shift(),C-=A.shift()??0,x=!0;m==="turn_complete"&&B.params?.update?.sessionUpdate==="turn_complete"&&R()});let E=setTimeout(R,g);typeof E.unref=="function"&&E.unref(),H=h.onClose(()=>R())})}),a.onRequest("hydra-acp/child_session/close",async l=>{let f=l??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw O(-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 l=>Su(l,o.name,e)),a.onRequest("hydra-acp/attention/clear",async l=>ku(l,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async l=>{let f=l??{},p=typeof f.token=="string"?f.token:void 0,m=typeof f.sessionId=="string"?f.sessionId:void 0,g=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async l=>{let f=l??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw O(k.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 O(k.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async l=>vu(l,e)),a.onRequest("session/new",async l=>{let f=ir.parse(l),p=at(l?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(E=>typeof E=="string")?p.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,v=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=fi(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let B={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};v=[...f.mcpServers??[],B]}let w,b,A=Xe(e);A!==void 0&&(v=[...v??[],...A.descriptors]);let C=Is({baselineMcpServers:f.mcpServers,stdinEnabled:p.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:v,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:li(a),transformChain:g,originatingClient:u.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{},...C?{mintMcpServersForSwap:C}:{}})}catch(E){throw y!==void 0&&y.abandon(E instanceof Error?E:void 0),b!==void 0&&b.abandon(E instanceof Error?E:void 0),A!==void 0&&A.abandon(E instanceof Error?E:void 0),E}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let E=h,B=e.mcpTokenRegistry;y.complete(x),x.onClose(()=>{B.unbind(E)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let E=w,B=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{B.unbind(E)})}A!==void 0&&A.bindToSession(x);let _,H;try{_=Mt(a,x,u),{entries:H}=await x.attach(_,"full")}catch(E){throw await x.close({deleteRecord:!1}).catch(()=>{}),E}u.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:_.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let E of H){if(a.isClosed())break;await a.notify(E.method,E.params).catch(()=>{})}})()});let D=mn(x),R=gn(x);return{sessionId:x.sessionId,...D?{modes:D}:{},...R?{models:R}:{},configOptions:x.buildConfigOptions(),_meta:hn(e.manager,x,{clientId:_.clientId})}}),a.onRequest("session/attach",async l=>{let f=dr.parse(l),p=f.clientInfo?.version;p&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,p):e.onTransformerVersion?.(o.name,p));let m=at(f._meta),g=m.resume,h=m.readonly===!0,y=m.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!g} readonly=${h}`);let v=g?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,w=e.manager.get(v);if(!w&&h){let R=await e.manager.loadFromDisk(v);if(!R)throw O(k.SessionNotFound,`session ${f.sessionId} not found`);let E=await e.manager.loadHistory(v),B=f.clientId??`cli_${Cs(8)}`;u.attached.set(R.hydraSessionId,{sessionId:R.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${R.hydraSessionId} clientId=${B} attachedCount=${u.attached.size} replayed=${E.length}`);for(let z of E)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:R.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:E.length,_meta:Au(R)}}let b=!w;if(!w){let R=await e.manager.loadFromDisk(v),E=R;if(g&&(E={...R,hydraSessionId:f.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!E)throw O(k.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(E.agentId,E.upstreamSessionId))throw O(k.SessionNotFound,`session ${f.sessionId} was deleted`);let B=E.originatingClient?E:{...E,originatingClient:u.clientInfo},z=y!==void 0?{...B,forwardedEnv:y}:B;w=await pn(e,{...z,onInstallProgress:li(a)})}let A=Mt(a,w,u,f.clientInfo,f.clientId),C=m.replayMode==="drip",{entries:x,appliedPolicy:_}=await w.attach(A,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:C,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(u.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(w.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${u.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${_} replayed=${x.length} readonly=${h}${C?" replayMode=drip":""}`),C){let R=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,E=750;(async()=>{let B=null;for(let z of x){let de=typeof z.recordedAt=="number"?z.recordedAt:null;if(B!==null&&de!==null){let st=Math.min(E,Math.max(0,(de-B)/R));st>0&&await new Promise(Rt=>setTimeout(Rt,st))}de!==null&&(B=de);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let R=0;R<x.length&&!a.isClosed();R++){let E=x[R],B=a.notify(E.method,E.params).catch(()=>{});(R+1)%200===0&&await B}w.replayPendingPermissions(A);let H=mn(w),D=gn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:_,replayed:x.length,...H?{modes:H}:{},...D?{models:D}:{},configOptions:w.buildConfigOptions(),_meta:hn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async l=>{let f=cr.parse(l),p=u.attached.get(f.sessionId);if(!p)throw O(k.SessionNotFound,"client not attached to that session");let m=e.manager.get(f.sessionId);return m?.detach(p.clientId),u.attached.delete(f.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[it]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async l=>{let f=ur.parse(l??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(h=>h.originatingClient?.name!==Lt).map(lr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw O(k.InternalError,"agent registry unavailable");return Ne(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async l=>{let f=l??{};if(typeof f.agentId!="string"||f.agentId.length===0)throw O(k.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(f.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async l=>{let f=fr.parse(l);c(f.sessionId,"session/prompt");let p=u.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),O(k.SessionNotFound,"not attached to session");let m=e.manager.get(f.sessionId);if(!m){let g=await e.manager.loadFromDisk(f.sessionId);if(!g)throw O(k.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),m=await pn(e,g);let h=Mt(a,m,u,void 0,p.clientId);await m.attach(h,"none")}return m.prompt(p.clientId,f)});let d=l=>{let f;try{f=Ot.parse(l)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let p=u.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let m=e.manager.get(f.sessionId);m&&m.cancel(p.clientId).catch(g=>{n.log.warn(`session/cancel for ${f.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async l=>{let f=Ot.parse(l);return c(f.sessionId,"session/cancel"),d(l),null}),a.onRequest("hydra-acp/prompt/cancel",async l=>{let f=mr.parse(l);return c(f.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async l=>{let f=Ot.parse(l);return c(f.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async l=>{let f=gr.parse(l);return c(f.sessionId,"hydra-acp/prompt/update"),se(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async l=>{let f=hr.parse(l);c(f.sessionId,"hydra-acp/prompt/amend");let p=u.attached.get(f.sessionId);if(!p)throw O(k.SessionNotFound,"not attached to session");return se(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/resume",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw O(k.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,g=e.manager.get(m);if(!g){let w=await e.manager.loadFromDisk(m);if(!w)throw O(k.SessionNotFound,`session ${p} not found in memory or on disk`);g=await pn(e,w)}let h=Mt(a,g,u);await g.attach(h,"pending_only"),u.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1}),g.replayPendingPermissions(h);let y=mn(g),v=gn(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...v?{models:v}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/load",async l=>{let f=l??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw O(k.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,g=e.manager.get(m);if(!g){let b=await e.manager.loadFromDisk(m);if(!b)throw O(k.SessionNotFound,`session ${p} not found in memory or on disk`);g=await pn(e,b)}let h=Mt(a,g,u),{entries:y}=await g.attach(h,"pending_only");u.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}g.replayPendingPermissions(h);let v=mn(g),w=gn(g);return{sessionId:g.sessionId,...v?{modes:v}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async l=>{let f=l?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=bu(l,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),O(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:m}=p,g=await p.session.forwardRequest("session/set_model",{...l,modelId:m});return p.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async l=>{let f=l,p=f?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw O(k.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw O(k.InvalidParams,"session/set_mode requires string modeId");let m=se(e.manager,f.sessionId),g=await m.forwardRequest("session/set_mode",l);return m.applyModeChange(f.modeId),g}),a.onRequest("session/set_config_option",async l=>{let f=l,p=y=>O(k.InvalidParams,y),m=f?.sessionId;if(typeof m=="string"&&c(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 g=se(e.manager,f.sessionId),h=g.buildConfigOptions().find(y=>y.id===f.configId);if(!h)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!h.options.some(y=>y.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!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),g.applyModelChange(f.value);break}case"mode":{f.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),g.applyModeChange(f.value);break}case"agent":{f.value!==g.agentId&&await g.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(l,f)=>{let p=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=f.startsWith("session/"),g=f.startsWith("hydra-acp/");if(!m&&!g||l===null||typeof l!="object"||p.has(f))throw O(k.MethodNotFound,`Method not found: ${f}`);let h=l.sessionId;if(typeof h!="string")throw O(k.MethodNotFound,`Method not found: ${f}`);return c(h,f),se(e.manager,h).forwardRequest(f,l)})})}async function vu(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw O(k.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let p=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(p)}let u=a.authMethods??[],c=u.find(p=>p.id===s);if(!c){let p=u.map(m=>m.id);throw O(k.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${p.map(m=>JSON.stringify(m)).join(", ")}]`)}let d=c._meta?.type,l=(()=>{let p=c._meta?.["terminal-auth"];if(p&&typeof p=="object"&&!Array.isArray(p))return p})();if((c.type??(d==="agent"||d==="terminal"?d:l!==void 0?"terminal":"agent"))==="terminal"){let p=(w,b)=>{if(!Array.isArray(w))throw O(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw O(k.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be string[]; got non-string entry ${JSON.stringify(A)}`);return w},m=await e.manager.planSpawnForAgent(a.agentId),g,h;if(l?.args!==void 0){let w=typeof l.command=="string"?l.command:void 0;g=w!==void 0&&mi.isAbsolute(w)?w:m.command,h=p(l.args,'_meta["terminal-auth"].args')}else{let w=c.args!==void 0?{raw:c.args,label:"args"}:c._meta?.args!==void 0?{raw:c._meta.args,label:"_meta.args"}:void 0,b=w!==void 0?p(w.raw,w.label):[];g=m.command,h=[...m.args,...b]}let y={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(y[w]=b);Object.assign(y,m.env);let v=pi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g,args:h,env:y,cwd:v}}try{return await a.connection.request("authenticate",{methodId:s})}catch(p){throw Ce(p,a)}}function li(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(yr,t).catch(()=>{})}}function mn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function gn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function bu(n,e){if(!n||typeof n!="object")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:k.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:k.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=qe(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(u=>u.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:k.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function Iu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw O(k.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw O(k.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw O(k.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function Su(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw O(k.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw O(k.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function ku(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw O(k.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw O(k.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function Au(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[it]:Ft(e,t)}}function hn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return ot(e.agentMeta,Ft(s,r))}function Cu(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{},resume:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:ot(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function xu(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function Mt(n,e,t,s,r){return{clientId:r??`cli_${Cs(8)}`,connection:n,clientInfo:s}}var yn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((i,a)=>{t=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Mu}from"crypto";import{McpServer as Ru}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Eu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as G}from"zod";function*xs(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;if(s.method!=="session/update")continue;let o=s.params?.update;!o||typeof o.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:o.sessionUpdate,update:o})}}function re(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var hi="Bearer ";function tt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(hi))return;let t=e.slice(hi.length).trim();return t.length>0?t:void 0}function Pu(n){let e=new Ru({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:G.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return re(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:G.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return re(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:G.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:G.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:G.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let o=await n.streamRead(t,s,r);return re(o)}),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:G.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:G.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),o=n.streamInfo();return re({outcome:r,writeCursor:o.writeCursor,closed:o.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:G.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:G.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:G.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:G.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:G.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:G.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:G.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:G.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:G.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return re(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return re(t)}),e}var Tu=1e4;function yi(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let c=Pu(a),d=new Eu({sessionIdGenerator:()=>Mu()});await c.connect(d);let l={server:c,transport:d};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await c.close()}catch{}}),d}async function r(i,a){let u=tt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(u);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let d;if(c.session!==void 0)d=c.session;else{let f,p=new Promise(g=>{f=setTimeout(()=>g(void 0),Tu)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0){a.code(503).send({error:"session not ready"});return}d=m}let l=await s(u,d);a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as _u}from"crypto";import{McpServer as $u}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Fu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function Ou(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Hu(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function Nu(n){let e=new $u({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:xe.string().min(1).describe("Case-insensitive substring to search for."),limit:xe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:xe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=await o.getHistorySnapshot(),a=[];for(let{entryId:c,entry:d,kind:l}of xs(i)){if(l==="tool_call"&&!r)continue;let f=ze([d]),p=f.toLowerCase().indexOf(t.toLowerCase());if(p<0)continue;let m=Ou(l),g=Hu(f,p),h=typeof d.recordedAt=="number"?String(d.recordedAt):void 0;if(a.push({entryId:c,speaker:m,snippet:g,timestamp:h}),a.length>=s)break}let u=a.length>=s&&a.length<i.length;return re({matches:a,total_matched:a.length,truncated:u})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:xe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:xe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return re({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let o=s-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getHistorySnapshot(),a=Math.min(t,i.length-1),u=Math.min(s,i.length-1),c=a>t||u<s;if(a>u)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:c}};let d=i.slice(a,u+1),l=ze(d);return{content:[{type:"text",text:l}],structuredContent:{text:l,entry_count:d.length,truncated:c}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:xe.string().optional(),file_path:xe.string().optional(),limit:xe.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let i=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!i&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let u=await o.getHistorySnapshot(),c=[],d=new Map;for(let{entryId:p,entry:m,kind:g,update:h}of xs(u)){if(g!=="tool_call"&&g!=="tool_call_update")continue;let y=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${p}`,v=d.get(y);v||(v={entryId:p,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(y,v),c.push(y)),typeof h.name=="string"&&h.name.length>0?v.toolName=h.name:(v.toolName==="(unnamed)"||g==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(v.toolName=h.title);let w=h.rawInput;if(w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0)for(let[b,A]of Object.entries(w))v.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!v.locations.includes(A)&&v.locations.push(A)}typeof h.status=="string"&&(v.status=h.status),m.recordedAt!==void 0&&v.timestamp===void 0&&(v.timestamp=String(m.recordedAt))}let l=[];for(let p of c){let m=d.get(p);if(t!==void 0&&m.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),y=["file_path","filePath","path"],v=!1;for(let w of y){let b=m.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){v=!0;break}}if(!v){for(let w of m.locations)if(w.toLowerCase().includes(h)){v=!0;break}}if(!v)continue}let g={};for(let[h,y]of Object.entries(m.rawInput))typeof y=="string"?g[h]=y.length>500?y.slice(0,497)+"\u2026":y:(typeof y=="number"||typeof y=="boolean")&&(g[h]=y);if(m.locations.length>0&&g.locations===void 0&&(g.locations=m.locations),l.push({entryId:m.entryId,tool:m.toolName,args:g,status:m.status,timestamp:m.timestamp}),l.length>=r)break}let f=l.length>=r;return re({calls:l,truncated:f})}),e}var ju=1e4;function wi(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let c=Nu(a),d=new Fu({sessionIdGenerator:()=>_u()});await c.connect(d);let l={server:c,transport:d};return t.set(i,l),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await c.close()}catch{}}),d}async function r(i,a){let u=tt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(u);if(c===void 0){a.code(404).send({error:"unknown recall token"});return}let l=await s(u,async()=>{if(c.session!==void 0)return c.session;let f,p=new Promise(g=>{f=setTimeout(()=>g(void 0),ju)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await l.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var wn=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Wu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Qu}from"crypto";import{Server as Bu}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Uu,ListToolsRequestSchema as Du}from"@modelcontextprotocol/sdk/types.js";function vi(n,e,t){let s=typeof t=="function"?async()=>t():async()=>t,r=new Bu({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),o=new Map(e.tools.map(i=>[i.name,i]));return r.setRequestHandler(Du,async()=>({tools:e.tools.map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema!==void 0?{outputSchema:i.outputSchema}:{}}))})),r.setRequestHandler(Uu,async(i,a)=>{let u=i.params.name;if(!o.has(u))return vn(`unknown tool: ${u}`);let c=a._meta?.progressToken??a.requestId,d=qu(c,a.sendNotification);try{let l=await s(),f=await zu(e.connection,n,u,i.params.arguments??{},l);return Ju(f,u)}catch(l){return vn(l instanceof Error?l.message:String(l))}finally{d()}}),r}var Lu=15e3;function qu(n,e,t=Lu){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function zu(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function Ju(n,e){if(n===null||typeof n!="object")return vn(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:vn(`extension ${e} omitted content array`)}function vn(n){return{content:[{type:"text",text:n}],isError:!0}}var Vu=1e4;function bi(n,e,t){let s=new Map;async function r(c){try{await c.transport.close()}catch{}try{await c.server.close()}catch{}}function o(c){for(let d of s.values()){let l=d.get(c);l!==void 0&&(d.delete(c),r(l))}}t.onChange(c=>{o(c)});async function i(c,d){let l=s.get(c);l===void 0&&(l=new Map,s.set(c,l),e.addDisposer(c,async()=>{let y=s.get(c);if(y!==void 0){s.delete(c);for(let v of y.values())await r(v)}}));let f=l.get(d);if(f!==void 0)return f.transport;let p=t.lookup(d);if(p===void 0)return;let g=vi(d,p,async()=>{let y=e.lookup(c);if(y===void 0)throw new Error("mcp token no longer bound");if(y.session!==void 0)return y.session.sessionId;let v,w=new Promise(A=>{v=setTimeout(()=>A(void 0),Vu)}),b=await Promise.race([y.sessionReady.catch(()=>{}),w]);if(v!==void 0&&clearTimeout(v),b===void 0)throw new Error("session not ready");return b.sessionId}),h=new Wu({sessionIdGenerator:()=>Qu()});return await g.connect(h),l.set(d,{server:g,transport:h}),h}async function a(c,d){let l=tt(c);if(l===void 0){d.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){d.code(404).send({error:"unknown mcp token"});return}let p=c.params.name,m=await i(l,p);if(m===void 0){d.code(404).send({error:`unknown mcp server: ${p}`});return}d.hijack(),await m.handleRequest(c.raw,d.raw,c.body)}let u={config:{skipAuth:!0}};n.post("/mcp/:name",u,async(c,d)=>{await a(c,d)}),n.get("/mcp/:name",u,async(c,d)=>{await a(c,d)}),n.delete("/mcp/:name",u,async(c,d)=>{await a(c,d)})}async function Xu(n,e){tl(n);let t=n.daemon.tls?await nt.readFile(Y(n.daemon.tls.key)):void 0,s=n.daemon.tls?await nt.readFile(Y(n.daemon.tls.cert)):void 0;await nt.mkdir(I.home(),{recursive:!0});let{stream:r,fileStream:o}=await Zu(n.daemon.logLevel),i=Ku({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(Gu,{options:{handleProtocols:Ps}}),En($=>{i.log.info($)}),_n($=>{i.log.info($)});let a=await nn.load(),u=new dn,c=new an,d=new on([new sn(e),new rn(a),c]),l=Po({validator:d});i.addHook("onRequest",async($,ce)=>{$.routeOptions.config?.skipAuth||$.url==="/acp"||$.url?.startsWith("/acp?")||await l($,ce)});let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=setInterval(()=>{u.sweepExpired()},300*1e3);p.unref();let m=new rt(n,{onFetched:()=>{bo(m,v)}});gs($=>i.log.info($));let g={info:$=>i.log.info($),warn:$=>i.log.warn($)},h=$=>he.spawn({...$,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});zs(n.compressToolContent);let y=new en,v=new vt(m,h,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:y,defaultCwd:n.defaultCwd}),w=new Xt(Ns(n),void 0,{tokenRegistry:c}),b=new Zt(js(n),void 0,{tokenRegistry:c});ni(i,K,ko(n));let A=new yn,C=new wn,x,_=()=>{if(x!==void 0)return x;let $=i.server.address();return x=`http://127.0.0.1:${$&&typeof $=="object"?$.port:n.daemon.port}`,x};ei(i,v,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:C,mcpTokenRegistry:A,getDaemonOrigin:_}),ti(i,m,v,{npmRegistry:n.npmRegistry}),si(i,w),ri(i,b),oi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),ui(i,{store:a,rateLimiter:u}),yi(i,A),wi(i,A),bi(i,A,C),gi(i,{validator:d,manager:v,defaultAgent:n.defaultAgent,processRegistry:c,onExtensionVersion:($,ce)=>w.reportVersion($,ce),onTransformerVersion:($,ce)=>b.reportVersion($,ce),transformers:b,extensionCommands:y,mcpTokenRegistry:A,extensionMcp:C,getDaemonOrigin:_,registry:m});let H=!!n.daemon.tls;await i.listen({host:H?"127.0.0.1":n.daemon.host,port:H?0:n.daemon.port});let D=i.server.address(),R=D&&typeof D=="object"?D.port:n.daemon.port,E,B=n.daemon.host,z=R;if(H&&t&&s){E=el({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:R,tlsOptions:{key:t,cert:s},logger:i.log});let $=E.address();$&&typeof $=="object"&&(z=$.port)}await nt.mkdir(I.home(),{recursive:!0}),await vo({pid:process.pid,host:B,port:z,loopbackPort:R,startedAt:new Date().toISOString()});let de={daemonUrl:`http://127.0.0.1:${R}`,daemonHost:"127.0.0.1",daemonPort:R,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${R}/acp`,hydraHome:I.home()};w.setContext(de),b.setContext(de),await w.start(),await b.start();try{await v.reconcilePermissionFlags()}catch($){i.log.warn(`permission flag reconcile failed: ${$.message}`)}v.resurrectPendingQueues().catch($=>{i.log.warn(`queue replay scan failed: ${$.message}`)}),v.resumePendingCompactions().catch($=>{i.log.warn(`compaction resume scan failed: ${$.message}`)}),v.resumePendingAgentSwaps().catch($=>{i.log.warn(`agent-swap resume scan failed: ${$.message}`)});let st=n.daemon.agentSyncIntervalMinutes*60*1e3,Rt=st>0?Io({registry:m,manager:v,intervalMs:st,logger:g}):void 0,Ms=n.daemon.sessionGcIntervalMinutes*60*1e3,Ci=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Rs=Ms>0?So({manager:v,intervalMs:Ms,maxAgeMs:Ci,logger:g}):void 0;return{app:i,manager:v,registry:m,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:C,processRegistry:c,shutdown:async()=>{Rs&&Rs(),Rt&&Rt(),clearInterval(f),clearInterval(p);let $=async(ce,xi)=>{try{await xi()}catch(bn){i.log.warn(`shutdown step ${ce} failed: ${bn instanceof Error?bn.message:String(bn)}`)}};await $("sessionTokenStore.flush",()=>a.flush()),await $("extensions.stop",()=>w.stop()),await $("transformers.stop",()=>b.stop()),await $("manager.closeAll",()=>v.closeAll()),await $("manager.flushSynopsis",()=>v.flushSynopsis(3e4)),await $("manager.shutdownSynopsis",()=>v.shutdownSynopsis()),await $("manager.flushMetaWrites",()=>v.flushMetaWrites()),await $("manager.flushHistoryWrites",()=>v.flushHistoryWrites()),En(null),_n(null),gs(null),E&&await $("tlsTerminator.close",()=>new Promise(ce=>E.close(()=>ce()))),await $("app.close",()=>i.close());try{Si.unlinkSync(I.pidFile())}catch{}await $("fileStream.flushSync",()=>o.flushSync())}}}async function Zu(n){let e=await Yu({file:I.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=Ii.destination(2);return{stream:Ii.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function el(n){let e=Ai.createServer(n.tlsOptions,t=>{let s=ki.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",o),s.on("error",o),t.on("close",()=>o()),s.on("close",()=>o()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function tl(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{he as AgentInstance,Ee as JsonRpcConnection,rt as Registry,Pe as Session,vt as SessionManager,Qi as defaultConfig,Pi as ensureServiceToken,Et as generateServiceToken,Us as loadConfig,Ei as loadServiceToken,Hn as ndjsonStreamFromStdio,I as paths,te as planSpawn,Xu as startDaemon,Wi as writeConfig,As as wsToMessageStream};