@hydra-acp/cli 0.1.104 → 0.1.105

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,38 +1,38 @@
1
- import*as Ai from"fs";import*as st from"fs/promises";import*as Ci from"net";import*as xi from"tls";import Xu from"fastify";import Zu from"@fastify/websocket";var Ps="acp.v1";function Ts(n,e){return n.has(Ps)?Ps:!1}import ki from"pino";import el from"pino-roll";import*as Ie from"fs/promises";import{homedir as Sn}from"os";import{z as k}from"zod";import*as N from"path";import*as bn from"os";var Ei="HYDRA_ACP_HOME";function Me(n){let e=bn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Pi(){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 B(){let n=process.env[Ei];if(n&&n.length>0)return N.resolve(n);let e=Pi();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 S={home:B,config:()=>N.join(B(),"config.json"),authToken:()=>N.join(B(),"auth-token"),remotes:()=>N.join(B(),"remotes.json"),pidFile:()=>N.join(B(),"daemon.pid"),logFile:()=>N.join(B(),"daemon.log"),currentLogFile:()=>N.join(B(),"current.log"),registryCache:()=>N.join(B(),"registry.json"),agentsDir:()=>N.join(B(),"agents"),agentLogFile:n=>N.join(B(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>N.join(B(),"sessions"),sessionDir:n=>N.join(B(),"sessions",n),sessionFile:n=>N.join(B(),"sessions",n,"meta.json"),historyFile:n=>N.join(B(),"sessions",n,"history.jsonl"),toolsDir:n=>N.join(B(),"sessions",n,"tools"),toolBlobFile:(n,e)=>N.join(B(),"sessions",n,"tools",e),queueFile:n=>N.join(B(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>N.join(B(),"sessions",".tombstones"),tombstoneAgentDir:n=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>N.join(B(),"extensions"),extensionLogDir:n=>N.join(B(),"extensions",n),extensionLogFile:n=>N.join(B(),"extensions",n,"current.log"),extensionPidFile:n=>N.join(B(),"extensions",n,"extension.pid"),transformersDir:()=>N.join(B(),"transformers"),transformerLogDir:n=>N.join(B(),"transformers",n),transformerLogFile:n=>N.join(B(),"transformers",n,"current.log"),transformerPidFile:n=>N.join(B(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>N.join(B(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>N.join(B(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>N.join(B(),"prompt-history"),tuiLogFile:()=>N.join(B(),"tui.log"),shimWireLogFile:()=>N.join(B(),"shim-wire.log")};import*as Fe 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 _s(){try{let e=(await Fe.readFile(S.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ti(){let n=await _s();if(!n)throw new Error(`No service token found at ${S.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function In(n){await Fe.mkdir(S.home(),{recursive:!0}),await Fe.writeFile(S.authToken(),n+`
2
- `,{encoding:"utf8",mode:384})}async function _i(){let n=await _s();if(n)return n;let e=Et();return await In(e),process.stderr.write(`hydra-acp: initialized ${S.authToken()} with a fresh service token.
3
- `),e}import*as Q from"fs/promises";import*as $s from"fs";import*as ae from"path";import{randomBytes as $i}from"crypto";async function de(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
- `;await Fi(n,r,t)}async function Fi(n,e,t={}){let s=await Oi(n),r=Hi(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${Ni()}`;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 Oi(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=ae.isAbsolute(t)?t:ae.resolve(ae.dirname(n),t);try{let r=await Q.realpath(ae.dirname(s));return ae.join(r,ae.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 Hi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Ni(){return $i(4).toString("hex")}var Os="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",ji=k.object({cert:k.string(),key:k.string()}),Hs=55514,Bi=k.object({host:k.string().default("127.0.0.1"),port:k.number().int().positive().default(Hs),logLevel:k.enum(["debug","info","warn","error"]).default("info"),tls:ji.optional(),sessionIdleTimeoutSeconds:k.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:k.number().int().positive().default(1e4),agentStderrTailBytes:k.number().int().positive().default(4096),publicHost:k.string().optional(),agentSyncIntervalMinutes:k.number().nonnegative().default(60),sessionGcIntervalMinutes:k.number().nonnegative().default(60),sessionGcMaxAgeDays:k.number().positive().default(2)}),Ui=k.object({url:k.string().url().default(Os),ttlHours:k.number().positive().default(24),pinned:k.boolean().default(!1)}),Di=k.object({name:k.string().optional(),description:k.string().optional(),command:k.string().optional(),args:k.array(k.string()).optional(),env:k.record(k.string()).optional()}),Li=k.object({packageSpec:k.string().optional()}),qi=k.object({repaintThrottleMs:k.number().int().nonnegative().default(1e3),maxScrollbackLines:k.number().int().positive().default(1e4),mouse:k.boolean().default(!0),inAppSelection:k.boolean().optional(),selectionClipboard:k.enum(["primary","clipboard","both"]).default("both"),openFileCommand:k.union([k.string(),k.array(k.string())]).optional(),logMaxBytes:k.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:k.number().int().positive().default(32),progressIndicator:k.boolean().default(!0),defaultEnterAction:k.enum(["enqueue","amend"]).default("amend"),showThoughts:k.boolean().default(!0),ambiguousWidth:k.enum(["auto","narrow","wide"]).default("auto"),toolContent:k.enum(["inline","references"]).default("references"),diffContextLines:k.number().int().min(0).default(3),promptHistoryMaxEntries:k.number().int().positive().default(2e3),maxToolItems:k.number().int().nonnegative().default(5),maxPlanItems:k.number().int().nonnegative().default(5),showFileUpdates:k.enum(["none","edit","diff"]).default("edit"),sessionColumns:k.array(k.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Fs=k.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),zi=k.object({command:k.array(k.string()).default([]),args:k.array(k.string()).default([]),env:k.record(k.string()).default({}),enabled:k.boolean().default(!0)}),Ji=k.object({command:k.array(k.string()).default([]),args:k.array(k.string()).default([]),env:k.record(k.string()).default({}),enabled:k.boolean().default(!0)}),Ns=k.object({daemon:Bi.default({}),registry:Ui.default({url:Os,ttlHours:24,pinned:!1}),agents:k.record(k.string(),Di).default({}),agentOverrides:k.record(k.string(),Li).default({}),defaultAgent:k.string().default("opencode"),defaultModels:k.record(k.string(),k.string()).default({}),synopsisAgent:k.string().optional(),synopsisModel:k.string().optional(),compaction:k.object({agent:k.string().optional(),model:k.string().optional(),tailK:k.number().int().nonnegative().default(20),maxIterations:k.number().int().positive().default(3),contextFraction:k.number().min(0).max(1).default(.5),hardCeilingFraction:k.number().min(0).max(1).default(.85),absoluteFallback:k.number().int().positive().default(12e4),idleBeforePromptMs:k.number().int().nonnegative().default(3e5),modelContextWindows:k.record(k.string(),k.number().int().positive()).default({})}).default({}),defaultCwd:k.string().default("~"),compressToolContent:k.boolean().default(!0),sessionListColdLimit:k.number().int().nonnegative().default(20),extensions:k.record(Fs,zi).default({}),transformers:k.record(Fs,Ji).default({}),defaultTransformers:k.array(k.string()).default([]),npmRegistry:k.string().url().optional(),tui:qi.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 js(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Bs(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Us(){return await Wi(),await ue(S.config())??{}}async function Wi(){let n;try{n=await Ie.lstat(S.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Ie.stat(S.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Ie.readlink(S.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${S.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 Qi(){let n=await Us(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Ie.access(S.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${S.authToken()} and ${S.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 de(S.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${S.config()} to ${S.authToken()}.
5
- `)}async function Ds(){return await Qi(),Ns.parse(await Us())}async function Vi(n){await de(S.config(),n,{mode:384})}function Ki(){return Ns.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 Gi}from"crypto";import{gzip as Yi,gunzip as Xi}from"zlib";import{promisify as Ls}from"util";var qs=Ls(Yi),Zi=Ls(Xi),zs=/^[A-Za-z0-9_-]+$/,ea=/^[a-f0-9]{64}$/,kn=!0;function Js(n){kn=n}function Pt(n,e){return zs.test(n)?e===void 0||ea.test(e):!1}function Tt(n,e){return`${S.toolBlobFile(n,e)}.gz`}async function An(n,e){if(!Pt(n))return null;let t=Gi("sha256").update(e,"utf8").digest("hex"),s=Tt(n,t),r=S.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(S.toolsDir(n),{recursive:!0});let o=kn?s:r,i=kn?await qs(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 Zi(t)).toString("utf8")}catch{}try{return await V.readFile(S.toolBlobFile(n,e),"utf8")}catch{return null}}async function Ws(n,e){if(!Pt(n,e))return null;try{return await V.readFile(Tt(n,e))}catch{}try{let t=await V.readFile(S.toolBlobFile(n,e));return await qs(t)}catch{return null}}async function Qs(n,e,t){if(!Pt(n,e))return;let s=Tt(n,e);try{await V.access(s);return}catch{}await V.mkdir(S.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Vs(n){zs.test(n)&&await V.rm(S.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as or from"fs/promises";import*as $t from"path";import{z as F}from"zod";import*as Gs from"fs";import*as X from"fs/promises";import*as Se from"path";import{spawn as Ys}from"child_process";import{Readable as ta}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 Oe=n=>{process.stderr.write(n+`
6
- `)};function Rn(n){Oe=n??(e=>process.stderr.write(e+`
7
- `))}async function Xs(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=S.agentInstallDir(n.agentId,e,n.version),s=Se.resolve(t,n.target.cmd);if(await xn(s))return s;if(await na({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 na(n){await X.mkdir(Se.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{Oe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await sa({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Oe(`hydra-acp: extracting ${n.agentId}`),He(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await oa(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(()=>{}),He(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Oe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),He(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function He(n,e){if(n)try{n(e)}catch{}}async function sa(n){let e=ra(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=Gs.createWriteStream(t),i=ta.fromWeb(s.body);He(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,u=Date.now(),c=0,d=2e3,f=150;return i.on("data",p=>{a+=p.length;let l=Date.now();l-c>=f&&(c=l,He(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),l-u>=d&&(u=l,Oe(Ks(n.agentId,a,r)))}),await new Promise((p,l)=>{i.on("error",l),o.on("error",l),o.on("finish",()=>p()),i.pipe(o)}),Oe(Ks(n.agentId,a,r,!0)),He(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Ks(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 ra(n){let e=new URL(n);return Se.posix.basename(e.pathname)||"archive"}async function oa(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 ia("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=Ys(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 ia(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Ys(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 aa}from"child_process";var Pn=n=>{process.stderr.write(n+`
8
- `)};function Tn(n){Pn=n??(e=>process.stderr.write(e+`
9
- `))}async function er(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentNpmInstallDir(n.agentId,e,n.version),s=fa(n.packageSpec),r=pa(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 f=await Zs(o);if(f)return f.binPath}await da({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Zs(o);if(a)return a.binPath;let u=await nr(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 da(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 la({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 ca=5,ua=25;function la(n){return tr(n,0)}async function tr(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=aa("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<ca)return await new Promise(r=>setTimeout(r,ua*(e+1))),tr(n,e+1);throw t}}function fa(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 pa(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function nr(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 Zs(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 nr(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 ma=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Ne=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),ga=F.object({"darwin-aarch64":Ne.optional(),"darwin-x86_64":Ne.optional(),"linux-aarch64":Ne.optional(),"linux-x86_64":Ne.optional(),"windows-x86_64":Ne.optional(),"windows-aarch64":Ne.optional()}),ha=F.object({package:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),ya=F.object({command:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),wa=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),va=F.object({npx:ma.optional(),binary:ga.optional(),uvx:ha.optional(),exec:ya.optional()}),ba=F.object({id:F.string(),name:F.string(),version:F.string().optional(),description:F.string().optional(),authors:F.array(F.string()).optional(),license:F.string().optional(),icon:F.string().optional(),repository:F.string().optional(),website:F.string().optional(),distribution:va,onboarding:wa.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),sr=F.object({version:F.string(),agents:F.array(ba),extensions:F.array(F.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:Ia(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=sr.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(S.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=sr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await de(S.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Ia(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 je(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=$t.resolve(S.agentInstallDir(n.id,e,t),s.cmd);if(await rr(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??_n(n)??s.package,o=S.agentNpmInstallDir(n.id,e,t),i=$t.join(o,"node_modules",".bin",r);if(await rr(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function rr(n){try{return await or.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 er({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 Xs({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 xa}from"child_process";import*as Ht from"fs";import*as vr from"path";var I={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 ir=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),Sa=L.enum(["full","pending_only","none","after_message"]),ar=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),dr=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),cr=L.object({sessionId:L.string(),historyPolicy:Sa.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 H}from"zod";var ur=H.object({sessionId:H.string()}),lr=H.object({cwd:H.string().optional(),cursor:H.string().optional()}),Fn=H.object({used:H.number().optional(),size:H.number().optional(),costAmount:H.number().optional(),costCurrency:H.string().optional()}),ql=H.object({sessionId:H.string(),upstreamSessionId:H.string().optional(),cwd:H.string(),title:H.string().optional(),agentId:H.string().optional(),currentModel:H.string().optional(),currentUsage:Fn.optional(),importedFromMachine:H.string().optional(),importedFromUpstreamSessionId:H.string().optional(),parentSessionId:H.string().optional(),forkedFromSessionId:H.string().optional(),forkedFromMessageId:H.string().optional(),originatingClient:H.object({name:H.string(),version:H.string().optional()}).optional(),interactive:H.boolean().optional(),priority:H.number().int().nonnegative().optional(),updatedAt:H.string(),attachedClients:H.number().int().nonnegative(),status:H.enum(["warm","cold"]).default("warm"),busy:H.boolean().default(!1),awaitingInput:H.boolean().default(!1),compactionState:H.any().optional(),forkSynthesisState:H.enum(["running","failed"]).optional(),_meta:H.record(H.unknown()).optional()}),ka=H.object({sessionId:H.string(),cwd:H.string(),title:H.string().optional(),updatedAt:H.string().optional(),_meta:H.record(H.unknown()).optional()}),zl=H.object({sessions:H.array(ka),nextCursor:H.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 fr(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 Aa(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=dr.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=Aa(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 pr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ot=M.object({sessionId:M.string()}),mr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Gl=M.object({sessionId:M.string(),messageId:M.string(),originator:mr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Yl=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Xl=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),gr=M.object({sessionId:M.string(),messageId:M.string()}),Zl=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),hr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),ef=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),yr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),tf=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),nf=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:mr,amendedAt:M.number()});import{z as ke}from"zod";var of=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()}),wr="hydra-acp/agents/install_progress",Be={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(`
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 f of s)f(d)}catch(d){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse ndjson line: ${d.message}`}})}u=t.indexOf(`
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,f=>{if(f){d(f);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as Ca}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=Ca(),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:I.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??I.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 Ma=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??Ma,this.killEscalationMs=e.killEscalationMs??Ra,this.logger=e.logger,this.fileLog=Ea(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()} ---
1
+ import*as Ci from"fs";import*as st from"fs/promises";import*as xi from"net";import*as Mi from"tls";import Zu from"fastify";import el from"@fastify/websocket";var Ts="acp.v1";function _s(n,e){return n.has(Ts)?Ts:!1}import Ai from"pino";import tl from"pino-roll";import*as Ie from"fs/promises";import{homedir as kn}from"os";import{z as k}from"zod";import*as N from"path";import*as In from"os";var Pi="HYDRA_ACP_HOME";function Me(n){let e=In.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Ti(){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 B(){let n=process.env[Pi];if(n&&n.length>0)return N.resolve(n);let e=Ti();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 S={home:B,config:()=>N.join(B(),"config.json"),authToken:()=>N.join(B(),"auth-token"),remotes:()=>N.join(B(),"remotes.json"),pidFile:()=>N.join(B(),"daemon.pid"),logFile:()=>N.join(B(),"daemon.log"),currentLogFile:()=>N.join(B(),"current.log"),registryCache:()=>N.join(B(),"registry.json"),agentsDir:()=>N.join(B(),"agents"),agentLogFile:n=>N.join(B(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>N.join(B(),"sessions"),sessionDir:n=>N.join(B(),"sessions",n),sessionFile:n=>N.join(B(),"sessions",n,"meta.json"),historyFile:n=>N.join(B(),"sessions",n,"history.jsonl"),toolsDir:n=>N.join(B(),"sessions",n,"tools"),toolBlobFile:(n,e)=>N.join(B(),"sessions",n,"tools",e),queueFile:n=>N.join(B(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>N.join(B(),"sessions",".tombstones"),tombstoneAgentDir:n=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>N.join(B(),"extensions"),extensionLogDir:n=>N.join(B(),"extensions",n),extensionLogFile:n=>N.join(B(),"extensions",n,"current.log"),extensionPidFile:n=>N.join(B(),"extensions",n,"extension.pid"),transformersDir:()=>N.join(B(),"transformers"),transformerLogDir:n=>N.join(B(),"transformers",n),transformerLogFile:n=>N.join(B(),"transformers",n,"current.log"),transformerPidFile:n=>N.join(B(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>N.join(B(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>N.join(B(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>N.join(B(),"prompt-history"),tuiLogFile:()=>N.join(B(),"tui.log"),shimWireLogFile:()=>N.join(B(),"shim-wire.log")};import*as Fe 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 $s(){try{let e=(await Fe.readFile(S.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function _i(){let n=await $s();if(!n)throw new Error(`No service token found at ${S.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Sn(n){await Fe.mkdir(S.home(),{recursive:!0}),await Fe.writeFile(S.authToken(),n+`
2
+ `,{encoding:"utf8",mode:384})}async function $i(){let n=await $s();if(n)return n;let e=Et();return await Sn(e),process.stderr.write(`hydra-acp: initialized ${S.authToken()} with a fresh service token.
3
+ `),e}import*as Q from"fs/promises";import*as Fs from"fs";import*as ae from"path";import{randomBytes as Fi}from"crypto";async function de(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
+ `;await Oi(n,r,t)}async function Oi(n,e,t={}){let s=await Hi(n),r=Ni(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${ji()}`;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{Fs.chmodSync(s,t.mode)}catch{}}async function Hi(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=ae.isAbsolute(t)?t:ae.resolve(ae.dirname(n),t);try{let r=await Q.realpath(ae.dirname(s));return ae.join(r,ae.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 Ni(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function ji(){return Fi(4).toString("hex")}var Hs="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Bi=k.object({cert:k.string(),key:k.string()}),Ns=55514,Ui=k.object({host:k.string().default("127.0.0.1"),port:k.number().int().positive().default(Ns),logLevel:k.enum(["debug","info","warn","error"]).default("info"),tls:Bi.optional(),sessionIdleTimeoutSeconds:k.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:k.number().int().positive().default(1e4),agentStderrTailBytes:k.number().int().positive().default(4096),publicHost:k.string().optional(),agentSyncIntervalMinutes:k.number().nonnegative().default(60),sessionGcIntervalMinutes:k.number().nonnegative().default(60),sessionGcMaxAgeDays:k.number().positive().default(2)}),Di=k.object({url:k.string().url().default(Hs),ttlHours:k.number().positive().default(24),pinned:k.boolean().default(!1)}),Li=k.object({name:k.string().optional(),description:k.string().optional(),command:k.string().optional(),args:k.array(k.string()).optional(),env:k.record(k.string()).optional()}),qi=k.object({packageSpec:k.string().optional()}),zi=k.object({repaintThrottleMs:k.number().int().nonnegative().default(1e3),maxScrollbackLines:k.number().int().positive().default(1e4),mouse:k.boolean().default(!0),inAppSelection:k.boolean().optional(),selectionClipboard:k.enum(["primary","clipboard","both"]).default("both"),openFileCommand:k.union([k.string(),k.array(k.string())]).optional(),logMaxBytes:k.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:k.number().int().positive().default(32),progressIndicator:k.boolean().default(!0),defaultEnterAction:k.enum(["enqueue","amend"]).default("amend"),showThoughts:k.boolean().default(!0),ambiguousWidth:k.enum(["auto","narrow","wide"]).default("auto"),toolContent:k.enum(["inline","references"]).default("references"),diffContextLines:k.number().int().min(0).default(3),promptHistoryMaxEntries:k.number().int().positive().default(2e3),maxToolItems:k.number().int().nonnegative().default(5),maxPlanItems:k.number().int().nonnegative().default(5),showFileUpdates:k.enum(["none","edit","diff"]).default("edit"),sessionColumns:k.array(k.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Os=k.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Ji=k.object({command:k.array(k.string()).default([]),args:k.array(k.string()).default([]),env:k.record(k.string()).default({}),enabled:k.boolean().default(!0)}),Wi=k.object({command:k.array(k.string()).default([]),args:k.array(k.string()).default([]),env:k.record(k.string()).default({}),enabled:k.boolean().default(!0)}),js=k.object({daemon:Ui.default({}),registry:Di.default({url:Hs,ttlHours:24,pinned:!1}),agents:k.record(k.string(),Li).default({}),agentOverrides:k.record(k.string(),qi).default({}),defaultAgent:k.string().default("opencode"),defaultModels:k.record(k.string(),k.string()).default({}),synopsisAgent:k.string().optional(),synopsisModel:k.string().optional(),compaction:k.object({agent:k.string().optional(),model:k.string().optional(),tailK:k.number().int().nonnegative().default(20),maxIterations:k.number().int().positive().default(3),contextFraction:k.number().min(0).max(1).default(.5),hardCeilingFraction:k.number().min(0).max(1).default(.85),absoluteFallback:k.number().int().positive().default(12e4),idleBeforePromptMs:k.number().int().nonnegative().default(3e5),modelContextWindows:k.record(k.string(),k.number().int().positive()).default({})}).default({}),defaultCwd:k.string().default("~"),compressToolContent:k.boolean().default(!0),sessionListColdLimit:k.number().int().nonnegative().default(20),extensions:k.record(Os,Ji).default({}),transformers:k.record(Os,Wi).default({}),defaultTransformers:k.array(k.string()).default([]),npmRegistry:k.string().url().optional(),tui:zi.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 Bs(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Us(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Ds(){return await Qi(),await ue(S.config())??{}}async function Qi(){let n;try{n=await Ie.lstat(S.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Ie.stat(S.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Ie.readlink(S.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${S.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 Vi(){let n=await Ds(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Ie.access(S.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${S.authToken()} and ${S.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 de(S.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${S.config()} to ${S.authToken()}.
5
+ `)}async function Ls(){return await Vi(),js.parse(await Ds())}async function Ki(n){await de(S.config(),n,{mode:384})}function Gi(){return js.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 Yi}from"crypto";import{gzip as Xi,gunzip as Zi}from"zlib";import{promisify as qs}from"util";var zs=qs(Xi),ea=qs(Zi),Js=/^[A-Za-z0-9_-]+$/,ta=/^[a-f0-9]{64}$/,An=!0;function Ws(n){An=n}function Pt(n,e){return Js.test(n)?e===void 0||ta.test(e):!1}function Tt(n,e){return`${S.toolBlobFile(n,e)}.gz`}async function Cn(n,e){if(!Pt(n))return null;let t=Yi("sha256").update(e,"utf8").digest("hex"),s=Tt(n,t),r=S.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(S.toolsDir(n),{recursive:!0});let o=An?s:r,i=An?await zs(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 ea(t)).toString("utf8")}catch{}try{return await V.readFile(S.toolBlobFile(n,e),"utf8")}catch{return null}}async function Qs(n,e){if(!Pt(n,e))return null;try{return await V.readFile(Tt(n,e))}catch{}try{let t=await V.readFile(S.toolBlobFile(n,e));return await zs(t)}catch{return null}}async function Vs(n,e,t){if(!Pt(n,e))return;let s=Tt(n,e);try{await V.access(s);return}catch{}await V.mkdir(S.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ks(n){Js.test(n)&&await V.rm(S.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as ir from"fs/promises";import*as $t from"path";import{z as F}from"zod";import*as Ys from"fs";import*as X from"fs/promises";import*as Se from"path";import{spawn as Xs}from"child_process";import{Readable as na}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 Oe=n=>{process.stderr.write(n+`
6
+ `)};function En(n){Oe=n??(e=>process.stderr.write(e+`
7
+ `))}async function Zs(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=S.agentInstallDir(n.agentId,e,n.version),s=Se.resolve(t,n.target.cmd);if(await Mn(s))return s;if(await sa({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 sa(n){await X.mkdir(Se.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{Oe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ra({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Oe(`hydra-acp: extracting ${n.agentId}`),He(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await ia(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(()=>{}),He(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Oe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),He(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function He(n,e){if(n)try{n(e)}catch{}}async function ra(n){let e=oa(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=Ys.createWriteStream(t),i=na.fromWeb(s.body);He(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,c=Date.now(),u=0,d=2e3,f=150;return i.on("data",p=>{a+=p.length;let l=Date.now();l-u>=f&&(u=l,He(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),l-c>=d&&(c=l,Oe(Gs(n.agentId,a,r)))}),await new Promise((p,l)=>{i.on("error",l),o.on("error",l),o.on("finish",()=>p()),i.pipe(o)}),Oe(Gs(n.agentId,a,r,!0)),He(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Gs(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 oa(n){let e=new URL(n);return Se.posix.basename(e.pathname)||"archive"}async function ia(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 aa("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=Xs(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 aa(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Xs(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 da}from"child_process";var Tn=n=>{process.stderr.write(n+`
8
+ `)};function _n(n){Tn=n??(e=>process.stderr.write(e+`
9
+ `))}async function tr(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=S.agentNpmInstallDir(n.agentId,e,n.version),s=pa(n.packageSpec),r=ma(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 f=await er(o);if(f)return f.binPath}await ca({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await er(o);if(a)return a.binPath;let c=await sr(t,s),u=typeof c=="object"&&c!==null?Object.keys(c):typeof c=="string"?[r]:[],d=u.length>0?` (package declares bins: ${u.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 ca(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 fa({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 ua=5,la=25;function fa(n){return nr(n,0)}async function nr(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=da("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,c)=>{if(a===0){t();return}let u=a!==null?`exit code ${a}`:`signal ${c??"unknown"}`,d=i.trim();s(new Error(d?`npm install ${n.packageSpec} failed (${u})
10
+ stderr: ${d}`:`npm install ${n.packageSpec} failed (${u})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<ua)return await new Promise(r=>setTimeout(r,la*(e+1))),nr(n,e+1);throw t}}function pa(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 ma(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function sr(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 er(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 sr(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 ga=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Ne=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),ha=F.object({"darwin-aarch64":Ne.optional(),"darwin-x86_64":Ne.optional(),"linux-aarch64":Ne.optional(),"linux-x86_64":Ne.optional(),"windows-x86_64":Ne.optional(),"windows-aarch64":Ne.optional()}),ya=F.object({package:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),wa=F.object({command:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),va=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),ba=F.object({npx:ga.optional(),binary:ha.optional(),uvx:ya.optional(),exec:wa.optional()}),Ia=F.object({id:F.string(),name:F.string(),version:F.string().optional(),description:F.string().optional(),authors:F.array(F.string()).optional(),license:F.string().optional(),icon:F.string().optional(),repository:F.string().optional(),website:F.string().optional(),distribution:ba,onboarding:va.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),rr=F.object({version:F.string(),agents:F.array(Ia),extensions:F.array(F.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(c=>c.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:Sa(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=rr.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(S.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=rr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await de(S.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Sa(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 je(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(S.agentInstallDir(n.id,e,t),s.cmd);if(await or(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??$n(n)??s.package,o=S.agentNpmInstallDir(n.id,e,t),i=$t.join(o,"node_modules",".bin",r);if(await or(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function or(n){try{return await ir.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 tr({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?u=>a({source:"npm",...u}):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 Zs({agentId:n.id,version:s,target:r,onProgress:o?c=>o({source:"binary",...c}):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 Ma}from"child_process";import*as Ht from"fs";import*as br from"path";var I={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 ar=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),ka=L.enum(["full","pending_only","none","after_message"]),dr=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),cr=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),ur=L.object({sessionId:L.string(),historyPolicy:ka.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 H}from"zod";var lr=H.object({sessionId:H.string()}),fr=H.object({cwd:H.string().optional(),cursor:H.string().optional()}),On=H.object({used:H.number().optional(),size:H.number().optional(),costAmount:H.number().optional(),costCurrency:H.string().optional()}),zl=H.object({sessionId:H.string(),upstreamSessionId:H.string().optional(),cwd:H.string(),title:H.string().optional(),agentId:H.string().optional(),currentModel:H.string().optional(),currentUsage:On.optional(),importedFromMachine:H.string().optional(),importedFromUpstreamSessionId:H.string().optional(),parentSessionId:H.string().optional(),forkedFromSessionId:H.string().optional(),forkedFromMessageId:H.string().optional(),originatingClient:H.object({name:H.string(),version:H.string().optional()}).optional(),interactive:H.boolean().optional(),priority:H.number().int().nonnegative().optional(),updatedAt:H.string(),attachedClients:H.number().int().nonnegative(),status:H.enum(["warm","cold"]).default("warm"),busy:H.boolean().default(!1),awaitingInput:H.boolean().default(!1),compactionState:H.any().optional(),forkSynthesisState:H.enum(["running","failed"]).optional(),_meta:H.record(H.unknown()).optional()}),Aa=H.object({sessionId:H.string(),cwd:H.string(),title:H.string().optional(),updatedAt:H.string().optional(),_meta:H.record(H.unknown()).optional()}),Jl=H.object({sessions:H.array(Aa),nextCursor:H.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 pr(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 Ca(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=cr.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 c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:i.messageId,originator:c,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=Ca(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 mr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ot=M.object({sessionId:M.string()}),gr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Yl=M.object({sessionId:M.string(),messageId:M.string(),originator:gr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Xl=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Zl=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),hr=M.object({sessionId:M.string(),messageId:M.string()}),ef=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),yr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),tf=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),wr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),nf=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),sf=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:gr,amendedAt:M.number()});import{z as ke}from"zod";var af=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()}),vr="hydra-acp/agents/install_progress",Be={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 c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
11
+ `);for(;c!==-1;){let u=t.slice(0,c).trim();if(t=t.slice(c+1),u.length>0)try{let d=JSON.parse(u);for(let f of s)f(d)}catch(d){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse ndjson line: ${d.message}`}})}c=t.indexOf(`
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 c=JSON.stringify(a)+`
13
+ `;await new Promise((u,d)=>{e.write(c,f=>{if(f){d(f);return}u()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as xa}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=xa(),r={jsonrpc:"2.0",id:s,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(s,{resolve:c=>i(c),reject:a}),this.stream.send(r).catch(c=>{this.pending.delete(s),a(c)})});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:I.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??I.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 Ra=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??Ra,this.killEscalationMs=e.killEscalationMs??Ea,this.logger=e.logger,this.fileLog=Pa(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
- stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=xa(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()} ---
17
+ stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Ma(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)})}},Ra=2e3;function Ea(n){try{let e=S.agentLogFile(n);Ht.mkdirSync(vr.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 Ud}from"nanoid";async function Ue(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 De(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 Ir from"fs/promises";var Pa=64*1024*1024,Ta=1*1024*1024,Le=64*1024,_a=6e4,$a=100,Fa=1e3,Oa=64*1024,Ha=256*1024,br=20;function Na(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??Pa,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ta,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,Le));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}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,Le)),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,Le)),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,_a));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(Na(e.pattern),u),d=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??$a,Fa)),p=Math.max(1,Math.min(e.maxBytes??Oa,Ha)),l=Math.max(0,Math.min(e.contextBefore??0,br)),m=Math.max(0,Math.min(e.contextAfter??0,br)),g=[],h=[],v=[],y=0,w=!1,b=0,A=0,C=(_,U)=>{for(let z of v)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:_,line:U}),z.remaining--,y+=U.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(c.test(U)!==d&&g.length<f){let z={cursor:_,line:U};if(l>0&&h.length>0){z.before=h.slice();for(let oe of z.before)y+=oe.line.length}y+=U.length,g.push(z),m>0&&v.push({match:z,remaining:m})}if(l>0)for(h.push({cursor:_,line:U});h.length>l;)h.shift();let P=g.length>=f&&v.length===0,j=y>=p;return P||j};for(let _=0;_<i.length;_++){if(i[_]!==10)continue;let U=i.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,C($,U)){w=!0;break}}if(!w&&b<i.length&&this.closed){let _=i.subarray(b).toString("utf8"),U=r+b;C(U,_)&&(w=!0),A=i.length}let x=Math.min(r+A,this.writeCursor),T={matches:g,truncated:w,nextCursor:x,scannedBytes:A};return o>0&&(T.gap=o),this.closed&&x>=this.writeCursor&&(T.eof=!0),T}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(()=>Ir.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var qe=[{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."}],Mf=new Map(qe.map(n=>[n.verb,n]));function Sr(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function ze(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=Sr(n),s=e.filter(o=>Sr(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 kr(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 f=t.get(d);f?f.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?Ba(r,o.outIndex,ja(c.content)):(r.push(u),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let p=f!==void 0&&t.has(f)?Ua(u,t.get(f)??[]):u;f!==void 0&&s.has(f)&&!Da(p)&&(p=La(p,s.get(f))),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 ja(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Ba(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 Ua(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Da(n){let t=jn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function La(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Ar=`[older history truncated]
20
- `,qa=["file_path","filePath","path","command","pattern","query"];function Je(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(),Qa(s.join(`
21
- `),t)}function Bn(n){let e=za(n),t=Ja(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function za(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Ja(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of qa){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Wa(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 Wa(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Qa(n,e){if(n.length<=e)return n;let t=n.split(`
22
- `);for(;t.length>0;){let s=Ar+t.join(`
23
- `);if(s.length<=e)return s;t.shift()}return Ar}var Cr="(untitled)";function Ln(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??Cr}`),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 f=xr(t.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let p=xr(t.tools_used);p.length>0&&e.push(`[Tools previously used] ${p}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??Cr}`);let{closedText:s,openText:r,keptCount:o}=Va(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(`
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)})}},Ea=2e3;function Pa(n){try{let e=S.agentLogFile(n);Ht.mkdirSync(br.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 Dd}from"nanoid";async function Ue(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(c=>c.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 De(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 Fr}from"nanoid";import*as Sr from"fs/promises";var Ta=64*1024*1024,_a=1*1024*1024,Le=64*1024,$a=6e4,Fa=100,Oa=1e3,Ha=64*1024,Na=256*1024,Ir=20;function ja(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??Ta,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(_a,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,Le));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}let c=Math.min(a,s),d={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return o>0&&(d.gap=o),this.closed&&r+c>=this.writeCursor&&(d.eof=!0),d}tail(e){let t=Math.max(0,Math.min(e,Le)),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,Le)),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,$a));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,c=e.caseInsensitive===!0?"i":"",u=a?new RegExp(e.pattern,c):new RegExp(ja(e.pattern),c),d=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Fa,Oa)),p=Math.max(1,Math.min(e.maxBytes??Ha,Na)),l=Math.max(0,Math.min(e.contextBefore??0,Ir)),m=Math.max(0,Math.min(e.contextAfter??0,Ir)),g=[],h=[],v=[],y=0,w=!1,b=0,A=0,x=(_,U)=>{for(let z of v)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:_,line:U}),z.remaining--,y+=U.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(u.test(U)!==d&&g.length<f){let z={cursor:_,line:U};if(l>0&&h.length>0){z.before=h.slice();for(let oe of z.before)y+=oe.line.length}y+=U.length,g.push(z),m>0&&v.push({match:z,remaining:m})}if(l>0)for(h.push({cursor:_,line:U});h.length>l;)h.shift();let P=g.length>=f&&v.length===0,j=y>=p;return P||j};for(let _=0;_<i.length;_++){if(i[_]!==10)continue;let U=i.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,x($,U)){w=!0;break}}if(!w&&b<i.length&&this.closed){let _=i.subarray(b).toString("utf8"),U=r+b;x(U,_)&&(w=!0),A=i.length}let C=Math.min(r+A,this.writeCursor),T={matches:g,truncated:w,nextCursor:C,scannedBytes:A};return o>0&&(T.gap=o),this.closed&&C>=this.writeCursor&&(T.eof=!0),T}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(()=>Sr.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var qe=[{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."}],Rf=new Map(qe.map(n=>[n.verb,n]));function kr(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function ze(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=kr(n),s=e.filter(o=>kr(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 Ar(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let u=Bn(c);if(u?.sessionUpdate!=="tool_call_update")continue;let d=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(d!==void 0&&(e.set(d,a),u.rawInput&&typeof u.rawInput=="object"&&!Array.isArray(u.rawInput)&&Object.keys(u.rawInput).length>0&&s.set(d,u.rawInput),Array.isArray(u.content)&&u.content.length>0)){let f=t.get(d);f?f.push(...u.content):t.set(d,[...u.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let u=Bn(c);if(!u||typeof u.sessionUpdate!="string"){r.push(c),o=null;continue}let d=u.sessionUpdate;if(d==="agent_message_chunk"||d==="agent_thought_chunk"||d==="user_message_chunk"){o&&o.kind===d?Ua(r,o.outIndex,Ba(u.content)):(r.push(c),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let f=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let p=f!==void 0&&t.has(f)?Da(c,t.get(f)??[]):c;f!==void 0&&s.has(f)&&!La(p)&&(p=qa(p,s.get(f))),r.push(p);continue}if(d==="plan"){i!==null?r[i]=c:(r.push(c),i=r.length-1);continue}(d==="prompt_received"||d==="turn_complete")&&(i=null),r.push(c)}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 Ba(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Ua(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 Da(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function La(n){let t=Bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function qa(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Cr=`[older history truncated]
20
+ `,za=["file_path","filePath","path","command","pattern","query"];function Je(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 c=i.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let u=c.sessionUpdate;if(u==="prompt_received"){o();let d=Dn(c.prompt).trim();d.length>0&&s.push(`User: ${d}`)}else if(u==="agent_message_chunk"){let d=Ln(c.content);d.length>0&&(r+=d)}else u==="tool_call"?(o(),s.push(Un(c))):u==="turn_complete"&&o()}return o(),Va(s.join(`
21
+ `),t)}function Un(n){let e=Ja(n),t=Wa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Ja(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Wa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of za){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Qa(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 Qa(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Va(n,e){if(n.length<=e)return n;let t=n.split(`
22
+ `);for(;t.length>0;){let s=Cr+t.join(`
23
+ `);if(s.length<=e)return s;t.shift()}return Cr}var xr="(untitled)";function qn(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??xr}`),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 c=dt("File edit intentions",t.file_edit_intentions);c.length>0&&e.push(c);let u=dt("Unresolved errors",t.unresolved_errors);u.length>0&&e.push(u);let d=dt("Tool state",t.tool_state);d.length>0&&e.push(d);let f=Mr(t.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let p=Mr(t.tools_used);p.length>0&&e.push(`[Tools previously used] ${p}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??xr}`);let{closedText:s,openText:r,keptCount:o}=Ka(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
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 xr(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 Va(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Ka(n),i=0,a=[];if(e>0&&r.length>0){let d=r.filter(l=>l.startEntryIndex>=t).length,f=Math.max(d,s),p=Math.min(f,e,r.length);i=p,a=p>0?r.slice(-p):[]}let u=a.length>0?Mr(a):"",c=o?Mr([o]):"";return{closedText:u,openText:c,keptCount:i}}function Mr(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 Ka(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 ct(n,e){let t=S.queueFile(n);if(e.length===0){await pe.unlink(t).catch(()=>{});return}await pe.mkdir(S.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
25
+ `)}`}function Mr(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 Ka(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Ga(n),i=0,a=[];if(e>0&&r.length>0){let d=r.filter(l=>l.startEntryIndex>=t).length,f=Math.max(d,s),p=Math.min(f,e,r.length);i=p,a=p>0?r.slice(-p):[]}let c=a.length>0?Rr(a):"",u=o?Rr([o]):"";return{closedText:c,openText:u,keptCount:i}}function Rr(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 Ga(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 c=a.sessionUpdate;if(c==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Dn(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(c==="agent_message_chunk"&&t!==null){let u=Ln(a.content);u.length>0&&(t.agent+=u)}else c==="tool_call"&&t!==null?t.tools.push(Un(a)):c==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}import*as pe from"fs/promises";async function ct(n,e){let t=S.queueFile(n);if(e.length===0){await pe.unlink(t).catch(()=>{});return}await pe.mkdir(S.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
27
27
  `)+`
28
- `;await pe.writeFile(t,s,"utf8")}async function Rr(n){let e=S.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 Er(n){let e=S.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as Nr from"fs/promises";var Fr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Or=$r(Fr,16),qn=$r(Fr,16),Ga=20,Ya=20,Xa=5,ye="hydra_session_";function Ae(){return`m_${Or()}`}function Hr(n){return n.startsWith(ye)?n.slice(ye.length):n}var Za=1e3,jt=300*1e3,ed=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}${Or()}`,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??Za,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){id(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=Tr(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 f=this.transformChain[d];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${qn()}`,l;try{l=await f.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 ${f.name} error on ${a}: ${g.message}`);continue}let m=l?.action??"continue";if(m==="stop")return;if(m==="processing"){let g=d,h=i,v=new Set(t),y=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:f.name}),this.runResponseChain(h,new Set([...v,f.name]),g+1,y).then(()=>w()).catch(()=>w()))},jt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:y,envelope:h,chainIdx:g,originatedBy:v,side:"response"})});return}l?.payload&&typeof l.payload=="object"&&(i=l.payload),t.add(f.name)}if(r!=="session/update")return;let u=ad(i);if(u!==null){this.setAgentAdvertisedCommands(u);return}let c=od(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,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],l=await f({agentId:r,cwd:i,agentArgs:a,...u?{forwardedEnv:u}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),o||(await De({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:c,agentReportedModel:l.initialModel,logger:this.logger}),await Ue({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger})),l.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 l.agent.connection.request("session/prompt",{sessionId:l.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,v=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=l.initialModel,this.currentMode=l.initialMode,this.setAgentAdvertisedModels(l.initialModels??[]),this.setAgentAdvertisedModes(l.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,...v!==void 0?{previousSummarizedThroughEntry:v}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await y.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 Er(n){let e=S.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 Pr(n){let e=S.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as jr from"fs/promises";var Or="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hr=Fr(Or,16),zn=Fr(Or,16),Ya=20,Xa=20,Za=5,ye="hydra_session_";function Ae(){return`m_${Hr()}`}function Nr(n){return n.startsWith(ye)?n.slice(ye.length):n}var ed=1e3,jt=300*1e3,td=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}${Hr()}`,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??ed,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){ad(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=_r(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 f=this.transformChain[d];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${zn()}`,l;try{l=await f.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 ${f.name} error on ${a}: ${g.message}`);continue}let m=l?.action??"continue";if(m==="stop")return;if(m==="processing"){let g=d,h=i,v=new Set(t),y=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:f.name}),this.runResponseChain(h,new Set([...v,f.name]),g+1,y).then(()=>w()).catch(()=>w()))},jt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:y,envelope:h,chainIdx:g,originatedBy:v,side:"response"})});return}l?.payload&&typeof l.payload=="object"&&(i=l.payload),t.add(f.name)}if(r!=="session/update")return;let c=dd(i);if(c!==null){this.setAgentAdvertisedCommands(c);return}let u=id(i);if(u!==null){this.setAgentAdvertisedModes(u);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,c=this.forwardedEnv,u=this.currentModel,d=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],l=await f({agentId:r,cwd:i,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),o||(await De({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:u,agentReportedModel:l.initialModel,logger:this.logger}),await Ue({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger})),l.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 l.agent.connection.request("session/prompt",{sessionId:l.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,v=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=l.initialModel,this.currentMode=l.initialMode,this.setAgentAdvertisedModels(l.initialModels??[]),this.setAgentAdvertisedModes(l.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(x){this.logger?.warn(`swapUpstream: agentChange handler failed: ${x.message}`)}if(!o&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...v!==void 0?{previousSummarizedThroughEntry:v}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await y.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 De({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:u,agentReportedModel:d.initialModel,logger:this.logger}),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:c,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.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(l){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${l.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Ga){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 f=u.status;(f==="completed"||f==="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"),I.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),I.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:kr(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Pr(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"),I.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),I.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=We(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>ed;){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"),I.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"),I.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()}`,f;try{f=await u.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(l){this.logger?.warn(`transformer ${u.name} error on ${c}: ${l.message}`);continue}let p=f?.action??"continue";if(p==="stop")return o==="notification"?void 0:f?.payload??zn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(i=f.payload),s.add(u.name);continue}if(p==="processing"){let l=a,m=i,g=new Set(s);return new Promise(h=>{let v=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]),l+1,o).then(h).catch(()=>h(o==="notification"?void 0:zn(e))))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(d,{resolve:h,timer:v,transformerName:u.name,method:e,envelope:m,chainIdx:l,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 f=d?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:d?.payload??fd(e)};if(f==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(u.name);continue}if(f==="processing"){let p=a,l=o,m=new Set(s),g=e;return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(c)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:c,transformerName:u.name}),this.runAgentRequestChain(g,l,new Set([...m,u.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:l})))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(c,{resolve:y=>h({shortCircuit:!0,payload:y}),timer:v,transformerName:u.name,method:g,envelope:l,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):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: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=Ae(),a=`transformer:${e}`,u={clientId:a,name:e};return new Promise((c,d)=>{let f={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(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{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=We((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=Qe(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=Qe(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=Qe(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})),f=i.name,p=typeof f=="string"&&f.trim()?f.trim():a,l=i.currentValue,m=typeof l=="string"&&l.trim()?l.trim():d[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=d,typeof l=="string"&&l.trim()&&(h.currentValue=l.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(nd(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(sd(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(",")}]`),rd(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 qe){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}`,f={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(f.description=r.description),e.push(f)}if(u.length>0&&t.get(u)===s){let c=r.verb?`${u} ${r.verb}`:u,f={name:r.argsHint?`${c} ${r.argsHint}`:c};r.description&&(f.description=r.description),e.push(f)}}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 qe)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(qe.some(f=>f.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 f=new Error(`no dispatcher for /hydra verb ${o}`);throw f.code=I.InternalError,f}}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=qe.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:p}of this.extensionCommands.list())f.has(p)||(c.push(p),f.add(p))}let d=new Error(`unknown /hydra verb: ${o} (known: ${c.join(", ")})`);throw d.code=I.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 f,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"};f=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let l=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return l.length>0?this.emitExtensionReply(l):{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,c=this.currentModel,u=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 De({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:c,agentReportedModel:d.initialModel,logger:this.logger}),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:u,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.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(l){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${l.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Ya){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 c=i.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let u=c.sessionUpdate,d=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(d){if(u==="tool_call")r.add(d);else if(u==="tool_call_update"){let f=c.status;(f==="completed"||f==="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"),I.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),I.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:Ar(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Tr(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"),I.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),I.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=We(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>td;){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"),I.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 c=this.promptQueue.find(d=>d.messageId===r&&d.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let u=this.recentlyTerminal.get(r);return u?u.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 c=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}c.push(u)}this.promptQueue=c}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"),I.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 c=this.transformChain[a];if(s.has(c.name))continue;let u=`request:${e}`;if(!c.intercepts.has(u))continue;let d=`t_${zn()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(l){this.logger?.warn(`transformer ${c.name} error on ${u}: ${l.message}`);continue}let p=f?.action??"continue";if(p==="stop")return o==="notification"?void 0:f?.payload??Jn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(i=f.payload),s.add(c.name);continue}if(p==="processing"){let l=a,m=i,g=new Set(s);return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.forwardRequest(e,m,new Set([...g,c.name]),l+1,o).then(h).catch(()=>h(o==="notification"?void 0:Jn(e))))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(d,{resolve:h,timer:v,transformerName:c.name,method:e,envelope:m,chainIdx:l,originatedBy:g,side:"request",tailKind:o})})}s.add(c.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 c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(i))continue;let u=`t_${zn()}`,d;try{d=await c.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${i}: ${p.message}`);continue}let f=d?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:d?.payload??pd(e)};if(f==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(c.name);continue}if(f==="processing"){let p=a,l=o,m=new Set(s),g=e;return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:c.name}),this.runAgentRequestChain(g,l,new Set([...m,c.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:l})))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(u,{resolve:y=>h({shortCircuit:!0,payload:y}),timer:v,transformerName:c.name,method:g,envelope:l,chainIdx:p,originatedBy:m,side:"agent-request"})})}s.add(c.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(u=>u.name===e),r=s>=0?s+1:0,o=(t??{}).prompt??[],i=Ae(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((u,d)=>{let f={kind:"user",messageId:i,originator:c,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:u,reject:d},p=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{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=We((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=Qe(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=Qe(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=i.currentValue;if(typeof c=="string"){let u=c.trim();u&&u!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(u)}`),this.applyModelChange(u))}}else if(i.id==="mode"){let a=ut(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=i.currentValue;if(typeof c=="string"){let u=c.trim();u&&u!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(u)}`),this.applyModeChange(u))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),c=Qe(i.options);if(c.length>0){let u=ut(i.options),d=u.length>0?u.map(h=>({value:h.id,name:h.name??h.id})):c.map(h=>({value:h.modelId,name:h.name??h.modelId})),f=i.name,p=typeof f=="string"&&f.trim()?f.trim():a,l=i.currentValue,m=typeof l=="string"&&l.trim()?l.trim():d[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=d,typeof l=="string"&&l.trim()&&(h.currentValue=l.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(sd(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(rd(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(",")}]`),od(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 qe){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 c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let u=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}if(c.length>0&&t.get(c)===s){let u=r.verb?`${c} ${r.verb}`:c,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}}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 qe)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 c=r.get(a);c===void 0?r.set(a,i):c!==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(qe.some(f=>f.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 f=new Error(`no dispatcher for /hydra verb ${o}`);throw f.code=I.InternalError,f}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let c=`hydra-acp-${o}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,i,t):this.runExtensionCommand(c,i);let u=qe.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:p}of this.extensionCommands.list())f.has(p)||(u.push(p),f.add(p))}let d=new Error(`unknown /hydra verb: ${o} (known: ${u.join(", ")})`);throw d.code=I.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 c={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(c.messageId=s);let u=()=>{},d=new Promise(m=>{u=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>u({stopReason:"cancelled",reason:m})});let f,p=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),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"};f=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let l=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return l.length>0?this.emitExtensionReply(l):{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
- `},_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}):
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":"",c=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${c}`});e=`Sessions (${t.length}):
36
36
  ${s.join(`
37
37
  `)}`}}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
38
38
  ${e}
@@ -40,20 +40,20 @@ ${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 f=d.modelId===i?"\u25B6 ":" ",p=d.name&&d.name!==d.modelId?` ${d.name}`:"";return`${f}${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 c=i?o.some(d=>d.modelId===i):!0,u=o.map(d=>{let f=d.modelId===i?"\u25B6 ":" ",p=d.name&&d.name!==d.modelId?` ${d.name}`:"";return`${f}${d.modelId}${p}`});!c&&i&&u.unshift(`\u25B6 ${i}`),a=u.join(`
44
44
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
45
45
  ${a}
46
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=ze(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(f=>f.modelId),i=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:o.filter(f=>f.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:`
47
- ${c}.
46
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=ze(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(f=>f.modelId),i=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:o.filter(f=>f.toLowerCase().includes(i)),c=a.length>0?a:o,u=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:`
47
+ ${u}.
48
48
  ${d}:
49
- ${u.join(`
49
+ ${c.join(`
50
50
  `)}
51
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(c=>c.id===o):!0,u=r.map(c=>{let d=c.id===o?"\u25B6 ":" ",f=c.name&&c.name!==c.id?` ${c.name}`:"";return`${d}${c.id}${f}`});!a&&o&&u.unshift(`\u25B6 ${o}`),i=u.join(`
51
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(u=>u.id===o):!0,c=r.map(u=>{let d=u.id===o?"\u25B6 ":" ",f=u.name&&u.name!==u.id?` ${u.name}`:"";return`${d}${u.id}${f}`});!a&&o&&c.unshift(`\u25B6 ${o}`),i=c.join(`
52
52
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
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})`),I.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 f=d.map(p=>_r(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 f=d.map(p=>$r(p));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
57
  ${f.join(`
58
58
 
59
59
  `)}
@@ -63,18 +63,18 @@ ${f.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
- ${_r(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(),f=u.kind==="ambiguous"?u.candidates:a.filter(g=>g.toLowerCase().includes(d)),p=f.length>0?f:a,l=u.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${u.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=u.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
66
+ ${$r(i)}
67
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(d=>d.value),c=jn(r,a),u=r;if(c.kind==="resolved")u=c.modelId;else if(c.kind==="ambiguous"||c.kind==="unknown"){let d=r.toLowerCase(),f=c.kind==="ambiguous"?c.candidates:a.filter(g=>g.toLowerCase().includes(d)),p=f.length>0?f:a,l=c.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${c.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,m=c.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
68
68
  ${l}.
69
69
  ${m}:
70
70
  ${p.join(`
71
71
  `)}
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"),I.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw ne(new Error(`already on agent ${r}`),I.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"),I.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"),I.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 f=(c.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let l=f.sessionUpdate;if(l==="prompt_received"){let m=We(f.prompt);m&&s.push({speaker:"user",text:m})}else if(l==="agent_message_chunk"){let g=f.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(l==="tool_call"||l==="tool_call_update"){let m=f.status,g=f.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:Ya,tailFloor:Xa,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??Le,Le)),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=I.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(()=>Er(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(()=>Nr.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 f=d.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=d.line,l={path:f,toolCallId:o};typeof p=="number"&&(l.line=p),this.notifyChain("file.edited",l)}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=!Pr(e,r),i=o?dd(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"),I.PermissionDenied);let s=this.rewriteForClient(e),r=Tr(s),o=Ae(),{toolCall:i,options:a}=s??{};return new Promise((u,c)=>{let d=!1,f=[],p=0,l,m=this.sessionId,g=y=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},h=y=>y?.code===I.MethodNotFound;function v(y){if(d)return;let w=y.connection.request("session/request_permission",s);f.push({client:y}),p++,w.then(b=>{p--,g(()=>{let A=cd({toolCallId:r,result:b,resolver:y});for(let C of f)C.client.clientId!==y.clientId&&C.client.connection.notify("session/update",{sessionId:m,update:A}).catch(()=>{});u(b)})}).catch(b=>{if(p--,h(b)||(l=b),p===0&&!d){let A=l??ne(new Error("no client handled permission request"),I.PermissionDenied);g(()=>c(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,v);for(let y of t)v(y)})}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=We(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 td=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 Pr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&td.has(s)}function nd(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 sd(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 rd(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 Qe(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 od(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 id(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 ad(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 dd(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 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 Tr(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 cd(n){let e=ud(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=ld(n.resolver),t}function ud(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 ld(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 We(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 fd(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function _r(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}
72
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(u!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:u}),this.applyModelChange(u),{stopReason:"end_turn"}):s==="mode"?(u!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:u}),this.applyModeChange(u),{stopReason:"end_turn"}):s==="agent"?(u!==this.agentId&&await this.runAgentCommandInline(u),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:u}),{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"),I.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw ne(new Error(`already on agent ${r}`),I.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"),I.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"),I.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 u of r){if(u.method!=="session/update")continue;let f=(u.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let l=f.sessionUpdate;if(l==="prompt_received"){let m=We(f.prompt);m&&s.push({speaker:"user",text:m})}else if(l==="agent_message_chunk"){let g=f.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(l==="tool_call"||l==="tool_call_update"){let m=f.status,g=f.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let o=[],i;for(let u of s)i&&i.speaker===u.speaker?i.text+=u.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:u.speaker,text:u.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.`,c=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,c,"","--- begin transcript ---",...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:Xa,tailFloor:Za,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??Le,Le)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(i.nextCursor,s);(c==="data"||c==="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=I.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(()=>Pr(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(()=>jr.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 f=d.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=d.line,l={path:f,toolCallId:o};typeof p=="number"&&(l.line=p),this.notifyChain("file.edited",l)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,c);let u={toolCallId:o,status:c};a&&(u.kind=a),s.content!==void 0&&(u.content=s.content),Array.isArray(s.locations)&&(u.locations=s.locations),this.notifyChain("tool.completed",u)}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=!Tr(e,r),i=o?cd(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 c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,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"),I.PermissionDenied);let s=this.rewriteForClient(e),r=_r(s),o=Ae(),{toolCall:i,options:a}=s??{};return new Promise((c,u)=>{let d=!1,f=[],p=0,l,m=this.sessionId,g=y=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},h=y=>y?.code===I.MethodNotFound;function v(y){if(d)return;let w=y.connection.request("session/request_permission",s);f.push({client:y}),p++,w.then(b=>{p--,g(()=>{let A=ud({toolCallId:r,result:b,resolver:y});for(let x of f)x.client.clientId!==y.clientId&&x.client.connection.notify("session/update",{sessionId:m,update:A}).catch(()=>{});c(b)})}).catch(b=>{if(p--,h(b)||(l=b),p===0&&!d){let A=l??ne(new Error("no client handled permission request"),I.PermissionDenied);g(()=>u(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,v);for(let y of t)v(y)})}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,c)=>{let u={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},d=this.insertEntryAt(u,i);this.persistRewrite(),this.broadcastQueueAdded(u,{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=We(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 c=t.slice(s.length).trim(),u=c?`/hydra ${r} ${c}`:`/hydra ${r}`;a=await this.handleSlashCommand(u,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 nd=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 Tr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&nd.has(s)}function sd(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 rd(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 od(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 Qe(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 id(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 ad(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 dd(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 cd(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 _r(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 ud(n){let e=ld(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=fd(n.resolver),t}function ld(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 fd(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 We(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 pd(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function $r(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 Ge from"fs/promises";import*as Gf from"path";import{customAlphabet as gd}from"nanoid";import{z as R}from"zod";import{z as Ve}from"zod";var pd=Ve.object({source:Ve.string(),reason:Ve.string(),raisedAt:Ve.number(),payload:Ve.unknown()}),jr=Ve.array(pd);import{z as q}from"zod";var Br=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()}),Ur=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 Ge from"fs/promises";import*as Yf from"path";import{customAlphabet as hd}from"nanoid";import{z as R}from"zod";import{z as Ve}from"zod";var md=Ve.object({source:Ve.string(),reason:Ve.string(),raisedAt:Ve.number(),payload:Ve.unknown()}),Br=Ve.array(md);import{z as q}from"zod";var Ur=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()}),Dr=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 Dr(n){let e=n.trim();if(e.length===0)return;let t=Ke(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Ke(e.slice(o,i+1)))}if(t===void 0){let o=qr(e);o!==void 0&&(t=Ke(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,Ur))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=lt.safeParse(s.synopsis);o.success&&md(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 Lr(n){let e=n.trim();if(e.length===0)return;let t=Ke(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Ke(e.slice(o,i+1)))}if(t===void 0){let o=zr(e);o!==void 0&&(t=Ke(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,Dr))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=lt.safeParse(s.synopsis);o.success&&gd(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 Dr(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 Lr(n){let e=n.trim();if(e.length===0)return;let t=Ke(e);if(t===void 0){let c=e.indexOf("{"),d=e.lastIndexOf("}");c>=0&&d>c&&(t=Ke(e.slice(c,d+1)))}if(t===void 0){let c=qr(e);c!==void 0&&(t=Ke(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,Ur))}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],f=q.array(q.string()).safeParse(d);f.success&&d.length>0&&(o[c]=f.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ke(n){try{return JSON.parse(n)}catch{return}}function qr(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 md(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 hd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",yd=gd(hd,16),wd="hydra_lineage_";function ft(){return`${wd}${yd()}`}var Gn=R.object({name:R.string(),description:R.string().optional()}),Yn=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),vd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),Xn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),Zn=R.object({name:R.string(),version:R.string().optional()}),bd=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Id=R.object({version:R.literal(1),sessionId:R.string(),lineageId:R.string().optional(),upstreamSessionId:R.string(),importedFromSessionId:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),importedFromMachine:R.string().optional(),agentId:R.string(),cwd:R.string(),title:R.string().optional(),synopsis:lt.optional(),compactionState:Br.optional(),rollbackBreadcrumb:bd.optional(),summarizedThroughEntry:R.number().int().nonnegative().optional(),agentArgs:R.array(R.string()).optional(),currentModel:R.string().optional(),currentMode:R.string().optional(),currentUsage:Xn.optional(),agentCommands:R.array(Gn).optional(),agentModes:R.array(Yn).optional(),agentModels:R.array(vd).optional(),pendingHistorySync:R.boolean().optional(),pendingAgentSwap:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),forkSynthesisState:R.enum(["running","failed"]).optional(),originatingClient:Zn.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:jr.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),Kn=/^[A-Za-z0-9_-]+$/;function Sd(n){if(!Kn.test(n))throw new Error(`unsafe session id: ${n}`)}var Bt=class{async write(e){Sd(e.sessionId);let t={version:1,...e};await de(S.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Kn.test(e))return;let t=await ue(S.sessionFile(e));if(t!==void 0)try{return Id.parse(t)}catch{return}}async delete(e){if(Kn.test(e)){try{await Ge.unlink(S.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ge.rmdir(S.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 Ge.readdir(S.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??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var kd=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 de(S.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(S.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=S.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 kd.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(S.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(S.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(S.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(S.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 zr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as no from"fs/promises";import{fileURLToPath as Ad}from"url";import*as pt from"path";import*as Dt from"fs";function Cd(){try{let n=pt.dirname(Ad(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=Cd(),Lt="hydra-acp-cat";var xd=12e4;async function Wr(n,e,t){let s=n.timeoutMs??xd,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=Rd(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 f=[];r.connection.onNotification("session/update",m=>{let g=Md(m);g.length>0&&f.push(g)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let p=f.join(""),l=t(p);if(!l){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 l})();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=Je(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 qr(n){let e=n.trim();if(e.length===0)return;let t=Ke(e);if(t===void 0){let u=e.indexOf("{"),d=e.lastIndexOf("}");u>=0&&d>u&&(t=Ke(e.slice(u,d+1)))}if(t===void 0){let u=zr(e);u!==void 0&&(t=Ke(u))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let u=s.title.trim();u.length>0&&(r.title=u.slice(0,Dr))}let o={},i=!1,a=["goal","outcome"];for(let u of a)if(typeof s[u]=="string"){let d=s[u].trim();d.length>0&&(o[u]=d,i=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let u of c)if(Array.isArray(s[u])){let d=s[u],f=q.array(q.string()).safeParse(d);f.success&&d.length>0&&(o[u]=f.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ke(n){try{return JSON.parse(n)}catch{return}}function zr(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 gd(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 yd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wd=hd(yd,16),vd="hydra_lineage_";function ft(){return`${vd}${wd()}`}var Yn=R.object({name:R.string(),description:R.string().optional()}),Xn=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),bd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),Zn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),es=R.object({name:R.string(),version:R.string().optional()}),Id=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Sd=R.object({version:R.literal(1),sessionId:R.string(),lineageId:R.string().optional(),upstreamSessionId:R.string(),importedFromSessionId:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),importedFromMachine:R.string().optional(),agentId:R.string(),cwd:R.string(),title:R.string().optional(),synopsis:lt.optional(),compactionState:Ur.optional(),rollbackBreadcrumb:Id.optional(),summarizedThroughEntry:R.number().int().nonnegative().optional(),agentArgs:R.array(R.string()).optional(),currentModel:R.string().optional(),currentMode:R.string().optional(),currentUsage:Zn.optional(),agentCommands:R.array(Yn).optional(),agentModes:R.array(Xn).optional(),agentModels:R.array(bd).optional(),pendingHistorySync:R.boolean().optional(),pendingAgentSwap:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),forkSynthesisState:R.enum(["running","failed"]).optional(),originatingClient:es.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:Br.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),Gn=/^[A-Za-z0-9_-]+$/;function kd(n){if(!Gn.test(n))throw new Error(`unsafe session id: ${n}`)}var Bt=class{async write(e){kd(e.sessionId);let t={version:1,...e};await de(S.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Gn.test(e))return;let t=await ue(S.sessionFile(e));if(t!==void 0)try{return Sd.parse(t)}catch{return}}async delete(e){if(Gn.test(e)){try{await Ge.unlink(S.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ge.rmdir(S.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 Ge.readdir(S.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??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var Ad=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 de(S.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(S.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=S.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 Ad.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(S.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(S.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(S.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(S.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 Jr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as so from"fs/promises";import{fileURLToPath as Cd}from"url";import*as pt from"path";import*as Dt from"fs";function xd(){try{let n=pt.dirname(Cd(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=xd(),Lt="hydra-acp-cat";var Md=12e4;async function Qr(n,e,t){let s=n.timeoutMs??Md,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),u=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=u.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=Ed(u);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 f=[];r.connection.onNotification("session/update",m=>{let g=Rd(m);g.length>0&&f.push(g)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let p=f.join(""),l=t(p);if(!l){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 l})();return await new Promise((c,u)=>{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`),c(void 0)},s),o.unref?.(),a.then(d=>{o&&clearTimeout(o),i||c(d)},d=>{o&&clearTimeout(o),i||u(d)})})}catch(a){let c=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function qt(n){let e=Je(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 Wr(n,s,Dr)}async function Qr(n){let e=Je(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 Qr(n,s,Lr)}async function Vr(n){let e=Je(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 Wr(n,s,Lr)}function Md(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 Rd(n){let e=new Set;Jr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Jr(e,t.availableModels),e}function Jr(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 Ed(n){let e=new Map;for(let t of Xr(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 Gr(n){return Ed(n).map(e=>e.name)}function Pd(n){let e=new Map;for(let t of Xr(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 Yr(n){return Pd(n).map(e=>e.path)}function Xr(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:Vr(o),paths:new Set},e.set(u,c)):c.toolName=Vr(o);for(let d of Kr(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 Kr(o.rawInput,o.locations))a.paths.add(u)}return e}function Vr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Kr(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 Td=2,zt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Td}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}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,l=S.sessionDir(e);if(await no.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${u} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),s==="compaction"){let m=this.opts.compactionMaxIterations??3,g=0,h=a??0,v,y=0,w,b=Date.now(),A={targetAgentId:r},C=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),x=T=>{this.opts.broadcastHydraCompaction?.(e,T,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 T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await Qr({agentId:u,cwd:l,plan:d,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{C({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=Zr(_.synopsis,T);$&&eo($)&&(await this.opts.persistSynopsis(e,$,T.length),v=$,y=T.length,w=void 0,await C({status:"running",requestedAt:b,iter:g}),x({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,y,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${to($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(h=T.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(g<m);if(v)g>=m&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let T=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:T}),x({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await C({status:"failed",requestedAt:b,iter:g,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let m=await qt({agentId:u,cwd:l,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=Zr(m.synopsis,i);g&&eo(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=${to(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 Zr(n,e){let t=Yr(e),s=Gr(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 eo(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 to(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 so(n){return n==="summary"?"summary":"inline"}var ts=256;function ro(n,e){return e!=="summary"?n:n.map(_d)}function _d(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(oo));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 $d(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function oo(n){if($d(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=oo(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 Fd=2048;function io(n){let e=new Set,t=s=>{if(ao(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 ao(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Od(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(!Od(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<=Fd)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 co(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(ao(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 mt=/^[A-Za-z0-9_-]+$/,Hd=1e3,Jt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Hd}async append(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(S.sessionDir(e),{recursive:!0});let s=await os(t,o=>An(e,o)),r=JSON.stringify(s)+`
112
- `;await Z.appendFile(S.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(S.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 Qr(n,s,qr)}function Rd(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 Ed(n){let e=new Set;Wr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Wr(e,t.availableModels),e}function Wr(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 Pd(n){let e=new Map;for(let t of Zr(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 Yr(n){return Pd(n).map(e=>e.name)}function Td(n){let e=new Map;for(let t of Zr(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 Xr(n){return Td(n).map(e=>e.path)}function Zr(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 c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,u=e.get(c);u===void 0?(u={toolName:Kr(o),paths:new Set},e.set(c,u)):u.toolName=Kr(o);for(let d of Gr(o.rawInput,o.locations))u.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 c of Gr(o.rawInput,o.locations))a.paths.add(c)}return e}function Kr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Gr(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 _d=2,zt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??_d}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 c=s==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,u=await this.opts.registry.getAgent(c);if(!u){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let d=await te(u,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,l=S.sessionDir(e);if(await so.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),s==="compaction"){let m=this.opts.compactionMaxIterations??3,g=0,h=a??0,v,y=0,w,b=Date.now(),A={targetAgentId:r},x=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),C=T=>{this.opts.broadcastHydraCompaction?.(e,T,A)};await x({status:"requested",requestedAt:b}),C({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 T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await Vr({agentId:c,cwd:l,plan:d,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{x({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=eo(_.synopsis,T);$&&to($)&&(await this.opts.persistSynopsis(e,$,T.length),v=$,y=T.length,w=void 0,await x({status:"running",requestedAt:b,iter:g}),C({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,y,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${no($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(h=T.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(g<m);if(v)g>=m&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let T=w??(g===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${g} iteration(s)`);await x({status:"failed",requestedAt:b,iter:g,lastError:T}),C({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await x({status:"failed",requestedAt:b,iter:g,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let m=await qt({agentId:c,cwd:l,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=eo(m.synopsis,i);g&&to(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=${no(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 eo(n,e){let t=Xr(e),s=Yr(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 to(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 no(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 ro(n){return n==="summary"?"summary":"inline"}var ns=256;function oo(n,e){return e!=="summary"?n:n.map($d)}function $d(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(io));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,c={};a.error!==void 0&&(c.error=ss(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),o.rawOutput=c}return{...n,params:{...t,update:o}}}function Fd(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function io(n){if(Fd(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=io(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 Od=2048;function ao(n){let e=new Set,t=s=>{if(co(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 co(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Hd(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(!Hd(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<=Od)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 uo(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(co(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_-]+$/,Nd=1e3,Jt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Nd}async append(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(S.sessionDir(e),{recursive:!0});let s=await is(t,o=>Cn(e,o)),r=JSON.stringify(s)+`
112
+ `;await Z.appendFile(S.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(S.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
114
  `;await Z.writeFile(S.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(S.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(S.historyFile(e),o.join(`
116
116
  `)+`
117
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(S.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 l;try{l=JSON.parse(p)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let m=l;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 l=c.get(p);if(l!==void 0)return l;let m=await _t(e,p);return c.set(p,m),m},f=[];for(let p of u)f.push(await co(p,d));return f}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(S.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Vs(e);try{await Z.rmdir(S.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 uo}from"fs";import*as lo from"path";async function fo(n,e){await uo.mkdir(lo.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await uo.writeFile(n,t.length>0?t.join(`
118
+ `)){if(p.length===0)continue;let l;try{l=JSON.parse(p)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let m=l;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,c=i.length>a?i.slice(-a):i;if(!s)return c;let u=new Map,d=async p=>{let l=u.get(p);if(l!==void 0)return l;let m=await _t(e,p);return u.set(p,m),m},f=[];for(let p of c)f.push(await uo(p,d));return f}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(S.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Ks(e);try{await Z.rmdir(S.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 lo}from"fs";import*as fo from"path";async function po(n,e){await lo.mkdir(fo.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await lo.writeFile(n,t.length>0?t.join(`
119
119
  `)+`
120
- `:"")}import{z as D}from"zod";var Nd=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),jd=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:lt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:Xn.optional(),agentCommands:D.array(Gn).optional(),agentModes:D.array(Yn).optional(),interactive:D.boolean().optional(),originatingClient:Zn.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),Bd=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:jd,history:D.array(Nd),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.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 po(n){return Bd.parse(n)}var mo=900*1e3,Dd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=Ud(Dd,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 je(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=I.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=I.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:Be,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=go(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===I.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=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 Ue({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 f=is(a??{}),p=as(ds(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} 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 l=await De({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,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:l,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 Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await De({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 l=new Error(`agent ${e} not found in registry`);throw l.code=I.AgentNotInstalled,l}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:Be,clientInfo:{name:"hydra",version:K}})}catch(l){throw await r.kill().catch(()=>{}),Ce(l,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(l){throw await r.kill().catch(()=>{}),l}await r.kill().catch(()=>{});let u=new Set;for(let l of this.sessions.values())u.add(`${l.agentId}::${l.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let l of c)u.add(`${l.agentId}::${l.upstreamSessionId}`);let d=S.sessionsDir(),f=[],p=0;for(let l of a){let m=`${e}::${l.sessionId}`;if(u.has(m)){p+=1;continue}if(Ld(l.cwd,d)){p+=1;continue}let g=await this.tombstones.read(e,l.sessionId).catch(()=>{});if(g){if(!zr(g,l.updatedAt)){p+=1;continue}await this.tombstones.remove(e,l.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${l.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}u.add(m);let h=`${ye}${Wt()}`,v=new Date().toISOString(),y=l.updatedAt??v,w={sessionId:h,lineageId:ft(),upstreamSessionId:l.sessionId,agentId:e,cwd:l.cwd,pendingHistorySync:!0,interactive:!0,createdAt:y,updatedAt:y};l.title!==void 0&&(w.title=l.title);let b=es(w);await this.store.write(b),f.push({version:1,...b})}return{synced:f,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=I.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:Be,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=is(a),d=ds(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==c){let m=ze(f,d),g=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,u,f,g)&&(c=f);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(v=>v.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),l=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:l}}catch(o){throw await r.kill().catch(()=>{}),Ce(yo(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=I.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:Be,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=ht(i.authMethods);let u=go(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),f=as(ds(c)),p=cs(c),l=us(c);return{agent:o,upstreamSessionId:e,agentMeta:c._meta,agentCapabilities:a,initialModel:d,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:l}}catch(i){throw await o.kill().catch(()=>{}),Ce(yo(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=I.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:Be,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=I.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=Ye({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:vo(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=qd(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:zd(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=We(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=I.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=Ye({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=Ye(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 f=o[d],p=i[d];s.add(f.sessionId);let l=Ye({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(l))continue;let m=p.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.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 f=u[d],p=c[d],l=Ye(f,p.hasContent);if(!r(l))continue;let m=p.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((d,f)=>d.updatedAt<f.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 f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:c}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await wo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let u={};for(let c of io(i)){let d=await Ws(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=I.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=I.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=I.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,u,c=t.mode??"synthesis",d,f,p,l=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=I.InvalidParams,b}u=t.forkAt,a=i.slice(0,w+1)}else{let w=Wd(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=I.AgentNotInstalled,b}p=w,f=s.currentModel,d="running"}let m=await wo(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}:{}},v=gt({record:h,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:K,machine:Qt.hostname()}),y=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:y,bundle:v,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 qt({agentId:r,cwd:t.cwd??S.sessionDir(e),plan:w,history:i,modelId:f,sessionId:e,logger:this.logger,timeoutMs:l});b&&b.synopsis?await this.mutateRecord(y,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:y,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 Qs(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(S.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await fo(S.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=Ye(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)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[s]:r},u=Buffer.byteLength(JSON.stringify(a),"utf8");if(u>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${u} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let c={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(c)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(s in i))return;delete i[s],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}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 Rr(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(u=>r-u.enqueuedAt<mo),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${mo/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 Ld(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 qd(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 f={id:d.id};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(d=>{let f={modelId:d.modelId};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModels;return es({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:vo(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(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function vo(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 zd(n){return n?{...n}:void 0}function go(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=Jd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function is(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!==I.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=I.AuthRequired,u.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},u}function ho(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function yo(n,e,t,s){if(n&&typeof n=="object"&&n.code===I.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 ${ho(s.cwd)} && ${[s.command,...s.args].map(ho).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 Jd(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 Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Qe(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Qe(e.options);return t.length>0?t:void 0}})??[]}function cs(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 us(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 Wd(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 wo(n){try{let e=await Te.readFile(S.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(S.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ye(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Lt?!1:e?!0:void 0}import{spawn as Qd}from"child_process";import*as Gt from"fs";import*as be from"fs/promises";import*as Yt from"path";import Vd 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 Kd=1e3,Gd=6e4,ls=3e3,Xe=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??Kd,this.restartCapMs=r.restartCapMs??Gd;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()},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 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).catch(s=>{t.failureReason=`spawn: ${s.message}`}),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{}},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 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"&&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 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)),a;try{await be.mkdir(i,{recursive:!0}),a=await Vd({file:Yt.join(i,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}})}catch(h){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${h.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
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,...f]=o;if(d===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
125
- `),a.end();return}let p=Y(d),l=[...f,...r.args].map(Y),m;try{m=Qd(p,l,{env:c,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
120
+ `:"")}import{z as D}from"zod";var jd=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),Bd=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:lt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:Zn.optional(),agentCommands:D.array(Yn).optional(),agentModes:D.array(Xn).optional(),interactive:D.boolean().optional(),originatingClient:es.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),Ud=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:Bd,history:D.array(jd),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.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 mo(n){return Ud.parse(n)}var go=900*1e3,Ld="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=Dd(Ld,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,c)=>{let u=this.get(a);if(u){await u.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,u)=>this.persistSynopsis(a,c,u),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,u)=>{if(u.targetAgentId)return;let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,u)=>{this.emitSwapPhase(a,u.targetAgentId,c)},onSynthesisArtifact:async(a,c,u,d)=>{await this.dispatchSynthesisSwap(a,c,u,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 c=o.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let 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 je(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=I.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=I.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:Be,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=ho(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===I.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 c=ls(a??{}),u=e.agentModes??ds(us(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(u?.map(g=>g.id))}`);let d=await Ue({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:u,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(d)} for sessionId=${e.hydraSessionId}`);let f=as(a??{}),p=ds(cs(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} 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 l=await De({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,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:l,currentMode:d,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:u,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 Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await De({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=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:u=>this.bootstrapAgent({...u,mcpServers:u.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(u,d)=>this.bootstrapAgentLoad(u,{...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(c.sessionId),scheduleCompaction:u=>this.scheduleCompaction(c.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:u=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await 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 l=new Error(`agent ${e} not found in registry`);throw l.code=I.AgentNotInstalled,l}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:Be,clientInfo:{name:"hydra",version:K}})}catch(l){throw await r.kill().catch(()=>{}),Ce(l,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(l){throw await r.kill().catch(()=>{}),l}await r.kill().catch(()=>{});let c=new Set;for(let l of this.sessions.values())c.add(`${l.agentId}::${l.upstreamSessionId}`);let u=await this.store.list().catch(()=>[]);for(let l of u)c.add(`${l.agentId}::${l.upstreamSessionId}`);let d=S.sessionsDir(),f=[],p=0;for(let l of a){let m=`${e}::${l.sessionId}`;if(c.has(m)){p+=1;continue}if(qd(l.cwd,d)){p+=1;continue}let g=await this.tombstones.read(e,l.sessionId).catch(()=>{});if(g){if(!Jr(g,l.updatedAt)){p+=1;continue}await this.tombstones.remove(e,l.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${l.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let h=`${ye}${Wt()}`,v=new Date().toISOString(),y=l.updatedAt??v,w={sessionId:h,lineageId:ft(),upstreamSessionId:l.sessionId,agentId:e,cwd:l.cwd,pendingHistorySync:!0,interactive:!0,createdAt:y,updatedAt:y};l.title!==void 0&&(w.title=l.title);let b=ts(w);await this.store.write(b),f.push({version:1,...b})}return{synced:f,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),c=Array.isArray(a.sessions)?a.sessions:[];for(let u of c){if(typeof u.sessionId!="string"||typeof u.cwd!="string")continue;let d={sessionId:u.sessionId,cwd:u.cwd};typeof u.title=="string"&&(d.title=u.title),typeof u.updatedAt=="string"&&(d.updatedAt=u.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=I.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:Be,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??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=as(a),d=cs(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==u){let m=ze(f,d),g=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,f,g)&&(u=f);else if(m.kind==="resolved")(m.modelId===u||await this.applySeedModel(r,c,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(u=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(u)}`);else{let h=d.map(v=>v.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let p=us(a),l=ls(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:i,initialModel:u,initialModels:d.length>0?d:void 0,initialModes:p.length>0?p:void 0,initialMode:l}}catch(o){throw await r.kill().catch(()=>{}),Ce(wo(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=I.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:Be,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=ht(i.authMethods);let c=ho(t.agentId,void 0),u=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),d=as(u),f=ds(cs(u)),p=us(u),l=ls(u);return{agent:o,upstreamSessionId:e,agentMeta:u._meta,agentCapabilities:a,initialModel:d,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:l}}catch(i){throw await o.kill().catch(()=>{}),Ce(wo(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 c=new Error(`agent ${e} not found in registry`);throw c.code=I.AgentNotInstalled,c}let o=await te(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}});a.authMethods=ht(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ce(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.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=Ye({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:bo(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=zd(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:Jd(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=We(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=I.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),c=Ye({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),u=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:u,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=Ye(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 f=o[d],p=i[d];s.add(f.sessionId);let l=Ye({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(l))continue;let m=p.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let c=(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)),u=await Promise.all(c.map(d=>yt(d.sessionId)));for(let d=0;d<c.length;d+=1){let f=c[d],p=u[d],l=Ye(f,p.hasContent);if(!r(l))continue;let m=p.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((d,f)=>d.updatedAt<f.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 u=ft(),d={...s,lineageId:u};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:u}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await vo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let c={};for(let u of ao(i)){let d=await Qs(e,u);d&&(c[u]=d.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:c}}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=I.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=I.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=I.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,c,u=t.mode??"synthesis",d,f,p,l=12e4;if(u==="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=I.InvalidParams,b}c=t.forkAt,a=i.slice(0,w+1)}else{let w=Qd(i);w?(c=w.messageId,a=i.slice(0,w.index+1)):(c="",a=i.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),c="",a=i;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=I.AgentNotInstalled,b}p=w,f=s.currentModel,d="running"}let m=await vo(e),g=u==="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}:{}},v=gt({record:h,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:K,machine:Qt.hostname()}),y=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:y,bundle:v,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...d!==void 0?{forkSynthesisState:d}:{}}),g&&(async()=>{try{let w=await te(p,[],{npmRegistry:this.npmRegistry}),b=await qt({agentId:r,cwd:t.cwd??S.sessionDir(e),plan:w,history:i,modelId:f,sessionId:e,logger:this.logger,timeoutMs:l});b&&b.synopsis?await this.mutateRecord(y,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:y,forkedFromSessionId:e,forkedAt:c}}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 Vs(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(S.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await po(S.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=Ye(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)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let u={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(u)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(s in i))return;delete i[s],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}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 Er(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(c=>r-c.enqueuedAt<go),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${go/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 c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),c.replayPersistedQueue(o)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function qd(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 zd(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 f={id:d.id};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModes,a=n.availableModels(),u=(a.length>0?a.map(d=>{let f={modelId:d.modelId};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):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:bo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:u,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function bo(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 Jd(n){return n?{...n}:void 0}function ho(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 c=e.fromObject(a);if(c!==void 0)return c}}let o=Wd(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!==I.AuthRequired)return n;let s=u=>!!u&&typeof u=="object"&&!Array.isArray(u),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",c=new Error(a);return c.code=I.AuthRequired,c.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function yo(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function wo(n,e,t,s){if(n&&typeof n=="object"&&n.code===I.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 ${yo(s.cwd)} && ${[s.command,...s.args].map(yo).join(" ")})`:"";if(!i&&!a)return n;let c=[o?r:`agent ${t} failed to start: ${r}`];i&&c.push(`stderr: ${i}`),a&&c.push(a);let u=new Error(c.join(`
122
+ `));if(n&&typeof n=="object"){let d=n;typeof d.code=="number"&&(u.code=d.code),d.data!==void 0&&(u.data=d.data)}return u}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,c=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},...c&&{_meta:c}})}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 Wd(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=Qe(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Qe(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 Qd(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 vo(n){try{let e=await Te.readFile(S.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(S.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ye(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Lt?!1:e?!0:void 0}import{spawn as Vd}from"child_process";import*as Gt from"fs";import*as be from"fs/promises";import*as Yt from"path";import Kd 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 Gd=1e3,Yd=6e4,fs=3e3,Xe=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??Gd,this.restartCapMs=r.restartCapMs??Yd;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).catch(s=>{t.failureReason=`spawn: ${s.message}`}),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)),a;try{await be.mkdir(i,{recursive:!0}),a=await Kd({file:Yt.join(i,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}})}catch(h){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${h.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
124
+ `);let c=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=c,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:c,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...f]=o;if(d===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
125
+ `),a.end();return}let p=Y(d),l=[...f,...r.args].map(Y),m;try{m=Vd(p,l,{env:u,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
126
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
127
  `,{encoding:"utf8",mode:384})}catch(h){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
128
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
129
  `)}),m.on("exit",(h,v)=>{try{Gt.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${v??"null"}
130
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 y=e.exitWaiters.splice(0);for(let b of y)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).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function fs(n){try{return process.kill(n,0),!0}catch{return!1}}function bt(n,e){return n.code=e,n}var Yd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:S.extensionsDir,logFile:S.extensionLogFile,pidFile:S.extensionPidFile}},Xt=class extends Xe{constructor(e,t,s={}){super(e,Yd,t,s)}};var Xd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:S.transformersDir,logFile:S.transformerLogFile,pidFile:S.transformerPidFile}},Zt=class extends Xe{connected=new Map;constructor(e,t,s={}){super(e,Xd,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var 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 ps from"fs/promises";async function bo(n){await ps.writeFile(S.pidFile(),JSON.stringify(n)+`
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).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ps(n){try{return process.kill(n,0),!0}catch{return!1}}function bt(n,e){return n.code=e,n}var Xd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:S.extensionsDir,logFile:S.extensionLogFile,pidFile:S.extensionPidFile}},Xt=class extends Xe{constructor(e,t,s={}){super(e,Xd,t,s)}};var Zd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:S.transformersDir,logFile:S.transformerLogFile,pidFile:S.transformerPidFile}},Zt=class extends Xe{connected=new Map;constructor(e,t,s={}){super(e,Zd,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var 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 Io(n){await ms.writeFile(S.pidFile(),JSON.stringify(n)+`
132
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 ms(n){It=n??(e=>process.stderr.write(e+`
134
- `))}async function Io(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(S.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 f=o.get(c)??new Set,p=tn.join(i,c),l;try{l=await St.readdir(p,{withFileTypes:!0})}catch(m){It(`hydra-acp: prune: failed to read ${p}: ${m.message}`);continue}for(let m of l){if(!m.isDirectory())continue;let g=m.name;if(g===d||f.has(g)||g.includes(".partial-"))continue;let h=tn.join(p,g);try{await St.rm(h,{recursive:!0,force:!0}),It(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(v){It(`hydra-acp: prune: failed to remove ${h}: ${v.message}`)}}}}function So(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 f of d.agents)await $n(f)==="yes"&&a.push(f.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:f}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${d.length}, skipped ${f}`)}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=(l,m)=>{n.logger&&n.logger[l](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(l=>(t("warn",`manager.list failed: ${l.message}`),[])),i=[];for(let l of o){if(l.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(l.interactive!==!1)continue}else if(l.interactive===!0)continue;let g=Date.parse(l.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:l.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((l,m)=>l.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),u=a[0]?.lastUsedMs,c=0,d=0;for(let{sessionId:l}of a)try{await n.manager.deleteRecord(l,"expired")&&(c+=1)}catch(m){d+=1,t("warn",`delete ${l} failed: ${m.message}`)}let f=i.length-a.length;if(n.verbose||c>0||d>0){let l=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${l} session(s) older than ${Zd(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:i.length,deleted:c,failed:d,deferred:f};return u!==void 0&&(p.oldestLastUsedMs=u),p}function ko(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 Zd(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 ec}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 Ao(n){let{tui:e,...t}=n,s=JSON.stringify(hs(t));return ec("sha256").update(s).digest("hex").slice(0,16)}import*as Mo from"path";import{createHash as tc,randomBytes as nc,timingSafeEqual as sc}from"crypto";var Ro="hydra_session_",rc=3600*24*30,Co=12,oc=32,ic=50;function ac(){return Mo.join(S.home(),"session-tokens.json")}function xo(n){return tc("sha256").update(n).digest("hex")}function Eo(n){return nc(n).toString("hex")}function dc(){return Eo(Co).slice(0,Co*2)}function cc(){return`${Ro}${Eo(oc)}`}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=ac(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(uc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=cc(),s=xo(t),r=dc(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:rc,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(Ro))return;let t=xo(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||!sc(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(()=>{})},ic))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>de(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 uc(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 Po="Bearer ",sn=class{constructor(e){this.token=e}token;async validate(e){return lc(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 To(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Po)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(Po.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function _o(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 lc(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 Is from"fs";import*as Ct from"os";import*as ei 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 fc}from"path";import pc 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 mc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ie(n){return pc(n).replace(mc,"")}function W(n){return ie(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Ho(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 Ic(t);case"agent_thought_chunk":case"agent_thought":return Sc(t);case"user_message_chunk":return kc(t);case"prompt_received":return Ac(t);case"tool_call":return Cc(t,e);case"tool_call_update":return Pc(t,e);case"plan":return $c(t);case"current_mode_update":return Fc(t);case"current_model_update":return Oc(t);case"turn_complete":return Hc(t);case"usage_update":return bc(t);case"available_commands_update":return wc(t);case"available_modes_update":return vc(t);case"session_info_update":return hc(t);case"config_option_update":return gc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function gc(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 hc(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 yc(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 wc(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:yc(e)}:null}function vc(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 bc(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 Ic(n){let e=At(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:kt(n)}}function Sc(n){let e=typeof n.text=="string"?ie(n.text):At(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:kt(n)}}function kc(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 Ac(n){let e=Nc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function No(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Fo(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=Fo(r.oldText),i=Fo(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 jo(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:ie(t)}function Cc(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(No(r)){let m=jo(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=Do(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=Uo(n);d!==void 0&&(u.detail=d);let f=ws(n);f!==void 0&&(u.detailFull=f);let p=Bo(n);p!==void 0&&(u.locations=p);let l=kt(n);return l!==void 0&&(u.workerTaskId=l),u}function Bo(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 Oo=64;function Uo(n){let e=ws(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?Rc(t,Oo):Ec(t,Oo)}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 ie(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 xc=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Mc(n){for(let e of xc)if(n.startsWith(e))return!0;return!1}function Do(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 Mc(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(fc.resolve(t.cwd,n)):n}function Rc(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Ec(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 Pc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Do(W(s),n,e):void 0,o=J(n,"status"),i=cn(n),a=Uo(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(No(c)){let m={kind:"exit-plan-mode",toolCallId:t},g=jo(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 f=ws(n);f!==void 0&&(d.detailFull=f);let p=Bo(n);if(p!==void 0&&(d.locations=p),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let m=Tc(n);m!==null&&(d.errorText=m),_c(n,m)&&(d.upstreamInterrupted=!0)}let l=kt(n);return l!==void 0&&(d.workerTaskId=l),d}function Tc(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 ie(s)}return null}function _c(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 $c(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 Fc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function Oc(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 Hc(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 ie(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ie(e.text):null}function Nc(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 Lo(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=Bc(i);if(c.length===0)continue;let d=c;if(u!==void 0){let f=e.get(u)??[],p=[];for(let l of c)f.some(m=>m.path===l.path&&m.oldText===l.oldText&&m.newText===l.newText)||p.push(l);if(p.length===0)continue;e.set(u,[...f,...p]),d=p}for(let f of d)jc(t,f)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function qo(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 jc(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 Bc(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,f=typeof c.new_string=="string"?c.new_string:void 0;d===void 0||f===void 0||e.push({path:i,oldText:d,newText:f})}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 zo(n){let e=Uc(n),t=Dc(e),s=[];Lc(s,n),qc(s,e,t);let r=s.join(`
133
+ `)};function gs(n){It=n??(e=>process.stderr.write(e+`
134
+ `))}async function So(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let o=e.activeAgentVersions(),i=tn.join(S.agentsDir(),t),a;try{a=await St.readdir(i,{withFileTypes:!0})}catch(c){let u=c;if(u.code==="ENOENT")return;It(`hydra-acp: prune: failed to read ${i}: ${u.message}`);return}for(let c of a){if(!c.isDirectory())continue;let u=c.name,d=r.get(u);if(d===void 0)continue;let f=o.get(u)??new Set,p=tn.join(i,u),l;try{l=await St.readdir(p,{withFileTypes:!0})}catch(m){It(`hydra-acp: prune: failed to read ${p}: ${m.message}`);continue}for(let m of l){if(!m.isDirectory())continue;let g=m.name;if(g===d||f.has(g)||g.includes(".partial-"))continue;let h=tn.join(p,g);try{await St.rm(h,{recursive:!0,force:!0}),It(`hydra-acp: pruned stale ${u} ${g} (${h})`)}catch(v){It(`hydra-acp: prune: failed to remove ${h}: ${v.message}`)}}}}function ko(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},o=async()=>{let a=[];try{let d=await n.registry.load();for(let f of d.agents)await Fn(f)==="yes"&&a.push(f.id)}catch(d){return r("warn",`registry load failed: ${d.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let u=a[c];try{let{synced:d,skipped:f}=await n.manager.syncFromAgent(u);r("info",`${u}: synced ${d.length}, skipped ${f}`)}catch(d){r("warn",`${u}: ${d.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(c=>{i(c)}).catch(c=>{r("warn",`tick crashed: ${c.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=(l,m)=>{n.logger&&n.logger[l](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(l=>(t("warn",`manager.list failed: ${l.message}`),[])),i=[];for(let l of o){if(l.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(l.interactive!==!1)continue}else if(l.interactive===!0)continue;let g=Date.parse(l.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:l.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((l,m)=>l.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),c=a[0]?.lastUsedMs,u=0,d=0;for(let{sessionId:l}of a)try{await n.manager.deleteRecord(l,"expired")&&(u+=1)}catch(m){d+=1,t("warn",`delete ${l} failed: ${m.message}`)}let f=i.length-a.length;if(n.verbose||u>0||d>0){let l=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${u} ${l} session(s) older than ${ec(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:i.length,deleted:u,failed:d,deferred:f};return c!==void 0&&(p.oldestLastUsedMs=c),p}function Ao(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 ec(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 tc}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 Co(n){let{tui:e,...t}=n,s=JSON.stringify(ys(t));return tc("sha256").update(s).digest("hex").slice(0,16)}import*as Ro from"path";import{createHash as nc,randomBytes as sc,timingSafeEqual as rc}from"crypto";var Eo="hydra_session_",oc=3600*24*30,xo=12,ic=32,ac=50;function dc(){return Ro.join(S.home(),"session-tokens.json")}function Mo(n){return nc("sha256").update(n).digest("hex")}function Po(n){return sc(n).toString("hex")}function cc(){return Po(xo).slice(0,xo*2)}function uc(){return`${Eo}${Po(ic)}`}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=dc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(lc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=uc(),s=Mo(t),r=cc(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:oc,a=new Date(o.getTime()+i*1e3),c={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Eo))return;let t=Mo(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||!rc(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(()=>{})},ac))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>de(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 lc(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 To="Bearer ",sn=class{constructor(e){this.token=e}token;async validate(e){return fc(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 _o(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(To)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(To.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function $o(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 fc(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 ti from"path";import*as ks from"readline";function ws(n){return Math.floor(n/4)}function Fo(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 pc}from"path";import mc 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 gc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ie(n){return mc(n).replace(gc,"")}function W(n){return ie(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function No(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 Sc(t);case"agent_thought_chunk":case"agent_thought":return kc(t);case"user_message_chunk":return Ac(t);case"prompt_received":return Cc(t);case"tool_call":return xc(t,e);case"tool_call_update":return Tc(t,e);case"plan":return Fc(t);case"current_mode_update":return Oc(t);case"current_model_update":return Hc(t);case"turn_complete":return Nc(t);case"usage_update":return Ic(t);case"available_commands_update":return vc(t);case"available_modes_update":return bc(t);case"session_info_update":return yc(t);case"config_option_update":return hc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function hc(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 yc(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 c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let u=a.pendingAgentSwap;typeof u=="string"?o=u:u===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 wc(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 vc(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:wc(e)}:null}function bc(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 Ic(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 Sc(n){let e=At(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:kt(n)}}function kc(n){let e=typeof n.text=="string"?ie(n.text):At(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:kt(n)}}function Ac(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 Cc(n){let e=jc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function jo(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Oo(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=Oo(r.oldText),i=Oo(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 Bo(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:ie(t)}function xc(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(jo(r)){let m=Bo(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=Lo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),c={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(c.status=i),a!==void 0&&(c.rawKind=a);let u=cn(n);u!==null&&(c.editDiff=u);let d=Do(n);d!==void 0&&(c.detail=d);let f=vs(n);f!==void 0&&(c.detailFull=f);let p=Uo(n);p!==void 0&&(c.locations=p);let l=kt(n);return l!==void 0&&(c.workerTaskId=l),c}function Uo(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 Ho=64;function Do(n){let e=vs(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?Ec(t,Ho):Pc(t,Ho)}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 ie(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 Mc=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Rc(n){for(let e of Mc)if(n.startsWith(e))return!0;return!1}function Lo(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 Rc(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(pc.resolve(t.cwd,n)):n}function Ec(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Pc(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 Tc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Lo(W(s),n,e):void 0,o=J(n,"status"),i=cn(n),a=Do(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let u=J(n,"name")??s;if(jo(u)){let m={kind:"exit-plan-mode",toolCallId:t},g=Bo(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 f=vs(n);f!==void 0&&(d.detailFull=f);let p=Uo(n);if(p!==void 0&&(d.locations=p),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let m=_c(n);m!==null&&(d.errorText=m),$c(n,m)&&(d.upstreamInterrupted=!0)}let l=kt(n);return l!==void 0&&(d.workerTaskId=l),d}function _c(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 ie(s)}return null}function $c(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 Fc(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 Oc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function Hc(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 Nc(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 ie(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ie(e.text):null}function jc(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 qo(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 c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,u=Uc(i);if(u.length===0)continue;let d=u;if(c!==void 0){let f=e.get(c)??[],p=[];for(let l of u)f.some(m=>m.path===l.path&&m.oldText===l.oldText&&m.newText===l.newText)||p.push(l);if(p.length===0)continue;e.set(c,[...f,...p]),d=p}for(let f of d)Bc(t,f)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function zo(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 Bc(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 Uc(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 c of a){if(!c||typeof c!="object")continue;let u=c,d=typeof u.old_string=="string"?u.old_string:void 0,f=typeof u.new_string=="string"?u.new_string:void 0;d===void 0||f===void 0||e.push({path:i,oldText:d,newText:f})}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 c=typeof i.oldText=="string"?i.oldText:"",u=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:c,newText:u})}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 Jo(n){let e=Dc(n),t=Lc(e),s=[];qc(s,n),zc(s,e,t);let r=s.join(`
135
135
  `);return r.endsWith(`
136
136
  `)||(r+=`
137
- `),r}function Uc(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=Ho(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Dc(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 Lc(n,e){let t=e.session,s=Hr(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 qc(n,e,t){if(!e.some(c=>zc(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
- `))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 f of d)n.push(`> _${_e(f)}_`);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(`- ${Wc(d.status)} ${Jc(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 f=d.status==="completed"?"[x]":"[ ]";n.push(`- ${f} ${_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 zc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Jc(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${_e(n.title)}${t}`}function Wc(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 Jo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Qc(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 f=d.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:u.push(d)}i?o="AND":a&&(o="OR");let c=u.map(d=>Vc(d)).filter(d=>d.term.length>0);return{operator:o,terms:c}}function Vc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Wo(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:Wo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Wo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Kc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Gc=5,Yc=200,Qo=30;async function Go(n,e,t={}){let s=Qc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Gc,o=t.maxSessions??Yc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),u=i?a.filter(f=>i.has(f.sessionId)):a,c=[],d=!1;for(let f of u){if(c.length>=o){d=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),l=Xc(p,s,r);if(l.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:l.totalMatches,snippets:l.snippets};f.title!==void 0&&(m.title=f.title),c.push(m)}return{query:e,truncated:d,results:c}}function Xc(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=Zc(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 Zc(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let u=eu(a).filter(c=>Kc(t,c.kind));for(let c of u){let d=c.text.toLowerCase(),f=d.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=d.indexOf(r,f+r.length);if(o+=p,i.length<s){let l=d.indexOf(r),m={kind:c.kind,text:ou(c.text,l,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function eu(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"?ie(s.text):un(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(su(s))return[];let o=un(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=ru(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return tu(s);default:return[]}}function tu(n){let e=Vo(n,"name"),t=Vo(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=Ko(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=Ko(o);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let i=nu(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function nu(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 su(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 ie(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ie(e.text):""}function ru(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 Vo(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Ko(n){try{return JSON.stringify(n)}catch{return""}}function ou(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-Qo),u=Math.min(s.length,i+o.length+Qo),c=a>0?"\u2026":"",d=u<s.length?"\u2026":"";return`${c}${s.slice(a,u)}${d}`}import{randomBytes as Xo}from"crypto";function Yo(n){let e=Xo(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(Yo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Yo({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=Xo(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 Zo(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Jo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ti(n,e,t,s={}){n.get("/v1/sessions",async c=>{let d=c.query,f=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.getOne(p);return l||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(c,d)=>{let f=c.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return d.code(400).send({error:"q is required"}),d;let l=Array.isArray(f.sessionIds)?f.sessionIds.filter(g=>typeof g=="string"&&g.length>0):void 0;return await Go(e,p,{sessionIds:l})}),n.post("/v1/sessions",async(c,d)=>{let f=c.body??{},p=Y(f.cwd??t.cwd),l=f.agentId??t.agentId,m=Ze(s),g=m!==void 0?[...f.mcpServers??[],...m.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:l,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 f=c.body??{},p=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,l=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,m=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let g=await gs({manager:e,maxAgeMs:p,maxDeletions:l,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 f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){l.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 f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)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=>ei.join(Ct.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return l.openStream(g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)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 l.streamWrite(g,h)}catch(v){return d.code(409).send({error:v.message}),d}}),n.patch("/v1/sessions/:id",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=c.body??{};if(l.priority!==void 0){let g=l.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(l.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 l.title!="string"||l.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,l.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){await l.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 f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=c.query?.tools,m=l==="references"?"references":so(l),g=await e.exportBundle(p,m==="references"?{tools:"references"}:{});if(!g){d.code(404).send({error:"session not found"});return}let h=gt({record:g.record,history:m==="summary"?ro(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:Zo(t)}),v=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${p}-${v}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){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(y=>y.trim()).filter(y=>y.length>0)):void 0,v=Lo(l.history);h&&(v=v.filter(y=>h.has(y.path))),g&&(v=v.map(y=>({...y,hunks:qo(y.hunks)}))),d.code(200).send(v)}),n.get("/v1/sessions/:id/tools/:hash",async(c,d)=>{let f=c.params,p=await e.resolveCanonicalId(f.id)??f.id,l=await e.loadToolBlob(p,f.hash);if(l===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(l)}),n.get("/v1/sessions/:id/transcript",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){d.code(404).send({error:"session not found"});return}let m=gt({record:l.record,history:l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,hydraVersion:K,machine:Ct.hostname(),hydraHost:Zo(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(zo(m))}),n.post("/v1/sessions/:id/fork",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=c.body??{},m={};if(l.forkAt!==void 0){if(typeof l.forkAt!="string"||l.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}m.forkAt=l.forkAt}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}m.cwd=Y(l.cwd)}if(l.agentId!==void 0){if(typeof l.agentId!="string"||l.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}m.agentId=l.agentId}if(l.title!==void 0){if(typeof l.title!="string"){d.code(400).send({error:"title must be a string"});return}m.title=l.title}if(l.mode!==void 0){if(l.mode!=="verbatim"&&l.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=l.mode}if(l.model!==void 0){if(typeof l.model!="string"||l.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}m.model=l.model}try{let g=await e.forkSession(p,m);d.code(201).send(g)}catch(g){let h=g;if(h.code===I.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===I.InvalidParams||h.code===I.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 f=c.body??{};if(f.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let p;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}p=f.cwd}let l;try{l=po(f.bundle)}catch(m){d.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(l,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});d.code(201).send(m)}catch(m){let g=m;if(g.code===I.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 f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p),m;if(l?m=l.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),v=!1,y,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=m??0,C=b.length,T=b.slice(A).reduce((P,j)=>P+JSON.stringify(j.params).length,0);y=ys(T);let _=l?.currentModel,U=b.at(-1).recordedAt,$=l?.currentUsage;v=$o({summarizedThroughEntry:A,totalEntries:C,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:v,...y!=null?{approxTokens:y}:{},...g!=null?{compactionState:g}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f;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 f=c.params.id,p=await e.resolveCanonicalId(f)??f;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(l){let m=l instanceof Error?l.message:String(l);d.code(409).send({error:m})}}),n.get("/v1/sessions/:id/history",async(c,d)=>{let f=c.params.id,p=c.query,l=p?.follow==="1"||p?.follow==="true",m=await e.resolveCanonicalId(f)??f,g=e.get(m),h,v,y=!1,w=1e4,b=[];if(g){l&&(v=g.onBroadcast(C=>{d.raw.writableEnded||(y?d.raw.write(JSON.stringify(C)+`
141
- `):(b.push(C),b.length>w&&b.shift()))})),c.raw.on("close",()=>{v?.(),d.raw.writableEnded||d.raw.end()});try{h=await g.getHistorySnapshot()}catch(C){throw v?.(),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
- `);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 T=x,_=typeof T.recordedAt=="number"?String(T.recordedAt):"";_&&A.has(_)||d.raw.write(JSON.stringify(x)+`
143
- `)}}return y=!0,v||d.raw.end(),d});function r(c,d,f){let p=typeof c=="string"?c.trim():"";if(p.length===0)return null;let l;try{l=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!l||typeof l!="object"||Array.isArray(l))return console.debug("events endpoint: skipping non-object JSONL line"),null;let m=l;if(typeof m.recordedAt!="number"||f!==void 0&&m.recordedAt<f||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 v=g.update.sessionUpdate;return typeof v!="string"||!d.has(v)?null:{recordedAt:m.recordedAt,entry:l}}function o(c,d,f){let l=d.params.update,m={sessionId:c,ts:new Date(d.recordedAt).toISOString(),kind:f,update:l};return l.messageId!==void 0&&l.messageId!==null&&(m.messageId=l.messageId),m}async function*i(c,d,f,p){for await(let l of d){let m=r(l,f,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,f,p){let l=Ss.createInterface({input:Is.createReadStream(d),crlfDelay:1/0}),m=i(c,l,f,p),g=await m.next(),h=g.done?null:g.value;return{sessionId:c,rl:l,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 f=c.query,p=f.kinds;if(!p||p.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let l=p.split(",").map(w=>w.trim());if(l.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of l)if(!ln.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let m=new Set(l),g;if(f.since!==void 0&&f.since.trim().length>0){let w=new Date(f.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}),v=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 y=[];for(let w of v)try{let b=S.historyFile(w.sessionId),A=await a(w.sessionId,b,m,g);A.exhausted||y.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}c.raw.on("close",()=>{for(let w of y)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;y.length>0;){let w=-1,b=1/0;for(let C=0;C<y.length;C++){let x=y[C];x.current!==null&&x.current.ts<b&&(b=x.current.ts,w=C)}if(w===-1)break;let A=y[w];if(d.raw.write(JSON.stringify(A.current.row)+`
144
- `),await u(A),A.exhausted){try{A.rl.close()}catch{}y.splice(w,1)}}}catch(w){for(let b of y)try{b.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(c,d)=>{let f=c.params.id,p=c.query,l=await e.resolveCanonicalId(f)??f;if(!e.get(l)&&!await e.hasRecord(l))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(!ln.has(C))return d.code(400).send({error:`kind "${C}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let v=new Set(h),y;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;y=C.getTime()}let w=S.historyFile(l),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 T;try{T=JSON.parse(x)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!T||typeof T!="object"||Array.isArray(T)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let _=T;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let U=_.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let $=U.update,P=$.sessionUpdate;if(typeof P!="string"||!v.has(P)||y!==void 0&&_.recordedAt<y)continue;let j={ts:new Date(_.recordedAt).toISOString(),kind:P,update:$};$.messageId!==void 0&&$.messageId!==null&&(j.messageId=$.messageId),d.raw.write(JSON.stringify(j)+`
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 f=c.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);return!l&&!await e.hasRecord(p)?(d.code(404).send({error:"session not found"}),d):l?{flags:l.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(c,d)=>{let f=c.query;if(!f.source||f.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let p=await e.list({includeNonInteractive:!0}),l=[];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 v of h)v.source===f.source&&l.push({...v,sessionId:m.sessionId})}return{flags:l}}),n.post("/v1/sessions/:id/attention/clear",async(c,d)=>{let f=c.params.id,p=await e.resolveCanonicalId(f)??f,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 v=e.get(p);if(v){if(g.length>0&&h.length>0)v.clearAttentionFlag(g,h);else{let C=Array.from(v.listAttentionFlags()).map(x=>`${x.source}::${x.reason}`);for(let x of C)v.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 y=e.store,w=await y.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 y.write({...w,attentionFlags:A}),d.code(204).send()})}function ni(n,e,t,s={}){n.get("/v1/agents",async()=>je(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===I.AgentNotInstalled){o.code(404).send({error:u.message});return}o.code(409).send({error:u.message})}})}function si(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var iu=/^[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=au(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 au(n){let e=n.name;if(typeof e!="string"||!iu.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 ri(n,e){fn(n,"extension",e)}function oi(n,e){fn(n,"transformer",e)}function ii(n,e){n.get("/v1/config",async()=>e)}import{z as tt}from"zod";import*as et from"fs/promises";import*as ai from"path";import{randomBytes as Sg,scrypt as du,timingSafeEqual as cu}from"crypto";import{promisify as uu}from"util";var lu=uu(du);function di(){return ai.join(S.home(),"password-hash")}var fu=128*1024*1024;async function ci(){try{return(await et.readFile(di(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ui(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await et.readFile(di(),"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 lu(n,i,a.length,{N:s,r,p:o,maxmem:fu});return u.length!==a.length?!1:cu(u,a)}var pu=tt.object({password:tt.string().min(1),label:tt.string().min(1).max(256).optional(),ttlSec:tt.number().int().positive().optional()}),mu=tt.object({id:tt.string().optional()}).optional();function li(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=gu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=pu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await ci())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await ui(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=mu.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 gu(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:I.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 pi}from"crypto";import*as mi from"os";import*as gi from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function bu(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 E(I.SessionNotFound,t??`session ${e} not found`);return s}async function pn(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=pi(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,f=n.mcpTokenRegistry;r.complete(c),c.onClose(()=>{f.unbind(d)})}return Eu(c,n),yi(c.sessionId,n),c}function hi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=_o({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 f of u.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);u.attached.clear()});let c=(f,p)=>{if(u.attached.get(f)?.readonly)throw E(I.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=ir.parse(f??{});p.clientInfo?.name&&(u.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let l=p.clientInfo?.version;return l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l)),Ru()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let l=p??{},m=Array.isArray(l.commands)?l.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let v={verb:h.verb};return typeof h.argsHint=="string"&&(v.argsHint=h.argsHint),typeof h.description=="string"&&(v.description=h.description),v}).filter(g=>g!==void 0):[];return f.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let m=l??{},g=typeof m.instructions=="string"?m.instructions:void 0,h=Array.isArray(m.tools)?m.tools.map(v=>{if(!v||typeof v!="object")return;let y=v;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let w={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(w.outputSchema=y.outputSchema),w}).filter(v=>v!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,g,h),{ok:!0,registered:h.length}});let p=l=>{let m=l??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw E(I.InvalidParams,"sessionId is required");return m.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(m,o.name,g.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async l=>{let m=p(l);if(!e.manager)throw E(I.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(m,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(g.value===void 0)throw E(I.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(I.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(m,o.name,g.key,g.value)}catch(h){throw E(I.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(m,o.name,g.key),{ok:!0}}),e.extensionMcpControls){let l=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async m=>{let g=m??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(I.InvalidParams,"refresh_session requires sessionId");return await l.notifyToolListChanged(g.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let l=p??{},m=Array.isArray(l.intercepts)?l.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,m),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,h=l.envelope,v=l.route;if(!m)throw E(-32602,"emit_message requires sessionId");if(!g&&v!=="client_broadcast")throw E(-32602,"emit_message requires method");let y=se(e.manager,m),w=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(w)return y.dischargeClaim(w,h),{ok:!0};if(v==="chain")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="queue"){if(g!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,h)}}if(v==="daemon")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(v)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0;if(!m)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,m).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async p=>Au(p,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let l=p??{},m=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,v=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=v&&v["hydra-acp"]&&typeof v["hydra-acp"]=="object"?v["hydra-acp"]:void 0,w=y&&typeof y.title=="string"?y.title:void 0,b=y&&typeof y.model=="string"?y.model:void 0;if(!g&&h){let x=e.manager.get(h);x&&(g=x.cwd)}if(!g)throw E(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:m,cwd:g,parentSessionId:h,interactive:A,transformChain:[],title:w,model:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"fork_session requires sessionId");let m=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.agentId=="string"?l.agentId:void 0,v=typeof l.mode=="string"&&(l.mode==="verbatim"||l.mode==="synthesis")?l.mode:void 0,y=typeof l.model=="string"&&l.model.length>0?l.model:void 0;return await e.manager.forkSession(l.sessionId,{...m!==void 0?{forkAt:m}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{},...v!==void 0?{mode:v}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/fork requires sessionId");let m=typeof l.cwd=="string"?l.cwd:void 0;return{sessionId:(await e.manager.forkSession(l.sessionId,{...m!==void 0?{cwd:m}:{},mode:"verbatim"})).sessionId}});let f=async(p,l)=>{let m=p??{};if(typeof m.sessionId!="string")throw E(I.InvalidParams,`${l} requires sessionId`);let g=await e.manager.resolveCanonicalId(m.sessionId)??m.sessionId,h=e.manager.get(g);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(g),await e.manager.hasRecord(g)&&await e.manager.deleteRecord(g),{id:g,existed:!0};let v=await e.manager.deleteRecord(g);return{id:g,existed:v}};a.onRequest("session/delete",async p=>(await f(p,"session/delete"),{})),a.onRequest("session/close",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/close requires sessionId");c(l.sessionId,"session/close");let m=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=e.manager.get(m);if(g)return await g.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(m))return{};throw E(I.SessionNotFound,`session ${m} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:l,existed:m}=await f(p,"hydra-acp/session/delete");if(!m)throw E(I.SessionNotFound,`session ${l} not found`);return{deleted:!0,sessionId:l}}),a.onRequest("hydra-acp/child_session/await",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",h=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!m)throw E(-32602,"await_child requires childSessionId");let v=se(e.manager,m,`child session ${m} not found`);return new Promise(y=>{let A=[],C=[],x=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(j),_?.(),U?.(),y(T?{entries:A,truncated:!0}:{entries:A}))};_=v.onBroadcast(z=>{let oe=bu(z);for(A.push(z),C.push(oe),x+=oe;A.length>0&&(A.length>1e3||x>1048576);)A.shift(),x-=C.shift()??0,T=!0;g==="turn_complete"&&z.params?.update?.sessionUpdate==="turn_complete"&&P()});let j=setTimeout(P,h);typeof j.unref=="function"&&j.unref(),U=v.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!m)throw E(-32602,"close_child_session requires childSessionId");let g=e.manager.get(m);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async p=>Cu(p,o.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>xu(p,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let l=p??{},m=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,h=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return m&&g&&e.manager.get(g)?.keepAliveClaim(m,h),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let p=f??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw E(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let l=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=await e.manager.loadToolBlob(l,p.hash);if(m===null)throw E(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>Iu(f,e)),a.onRequest("logout",async f=>Su(f,e)),a.onRequest("session/new",async f=>{let p=ar.parse(f),l=at(f?._meta),m=Array.isArray(l.transformers)&&l.transformers.every(P=>typeof P=="string")?l.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,v,y=p.mcpServers;if(l.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=pi(32).toString("hex"),v=e.mcpTokenRegistry.reserve(h);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};y=[...p.mcpServers??[],j]}let w,b,A=Ze(e);A!==void 0&&(y=[...y??[],...A.descriptors]);let C=bs({baselineMcpServers:p.mcpServers,stdinEnabled:l.mcpStdin===!0,deps:e}),x;try{x=await e.manager.create({cwd:p.cwd,agentId:l.agentId??e.defaultAgent,mcpServers:y,title:l.title,agentArgs:l.agentArgs,model:l.model,onInstallProgress:fi(a),transformChain:g,originatingClient:u.clientInfo,...l.interactive!==void 0?{interactive:l.interactive}:{},...l.env!==void 0?{forwardedEnv:l.env}:{},...C?{mintMcpServersForSwap:C}:{}})}catch(P){throw v!==void 0&&v.abandon(P instanceof Error?P:void 0),b!==void 0&&b.abandon(P instanceof Error?P:void 0),A!==void 0&&A.abandon(P instanceof Error?P:void 0),P}if(h!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,j=e.mcpTokenRegistry;v.complete(x),x.onClose(()=>{j.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,j=e.mcpTokenRegistry;b.complete(x),x.onClose(()=>{j.unbind(P)})}A!==void 0&&A.bindToSession(x),yi(x.sessionId,e);let T,_;try{T=Mt(a,x,u),{entries:_}=await x.attach(T,"full")}catch(P){throw await x.close({deleteRecord:!1}).catch(()=>{}),P}u.attached.set(x.sessionId,{sessionId:x.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=mn(x),$=gn(x);return{sessionId:x.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:x.buildConfigOptions(),_meta:hn(e.manager,x,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=cr.parse(f),l=p.clientInfo?.version;l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l));let m=at(p._meta),g=m.resume,h=m.readonly===!0,v=m.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(y);if(!w&&h){let $=await e.manager.loadFromDisk(y);if(!$)throw E(I.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(y),j=p.clientId??`cli_${As(8)}`;u.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${j} attachedCount=${u.attached.size} replayed=${P.length}`);for(let z of P)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:P.length,_meta:Mu($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(y),P=$;if(g&&(P={...$,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}:{}}),!P)throw E(I.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(I.SessionNotFound,`session ${p.sessionId} was deleted`);let j=P.originatingClient?P:{...P,originatingClient:u.clientInfo},z=v!==void 0?{...j,forwardedEnv:v}:j;w=await pn(e,{...z,onInstallProgress:fi(a)})}let A=Mt(a,w,u,p.clientInfo,p.clientId),C=m.replayMode==="drip",{entries:x,appliedPolicy:T}=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}),v!==void 0&&await e.manager.setForwardedEnv(w.sessionId,v).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${u.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${x.length} readonly=${h}${C?" replayMode=drip":""}`),C){let $=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,P=750;(async()=>{let j=null;for(let z of x){let oe=typeof z.recordedAt=="number"?z.recordedAt:null;if(j!==null&&oe!==null){let $e=Math.min(P,Math.max(0,(oe-j)/$));$e>0&&await new Promise(Rt=>setTimeout(Rt,$e))}oe!==null&&(j=oe);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let $=0;$<x.length&&!a.isClosed();$++){let P=x[$],j=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await j}w.replayPendingPermissions(A);let _=mn(w),U=gn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:x.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:hn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=ur.parse(f),l=u.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(p.sessionId);return m?.detach(l.clientId),u.attached.delete(p.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[it]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=lr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Lt).map(fr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(I.InternalError,"agent registry unavailable");return je(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let p=f??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw E(I.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 f=>{let p=pr.parse(f);c(p.sessionId,"session/prompt");let l=u.attached.get(p.sessionId);if(!l)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),E(I.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 E(I.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),m=await pn(e,g);let h=Mt(a,m,u,void 0,l.clientId);await m.attach(h,"none")}return m.prompt(l.clientId,p)});let d=f=>{let p;try{p=Ot.parse(f)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let l=u.attached.get(p.sessionId);if(!l)return;if(l.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let m=e.manager.get(p.sessionId);m&&m.cancel(l.clientId).catch(g=>{n.log.warn(`session/cancel for ${p.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async f=>{let p=Ot.parse(f);return c(p.sessionId,"session/cancel"),d(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=gr.parse(f);return c(p.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=Ot.parse(f);return c(p.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=hr.parse(f);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 f=>{let p=yr.parse(f);c(p.sessionId,"hydra-acp/prompt/amend");let l=u.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"not attached to session");return se(e.manager,p.sessionId).amendPrompt(l.clientId,p)}),a.onRequest("session/resume",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let w=await e.manager.loadFromDisk(m);if(!w)throw E(I.SessionNotFound,`session ${l} 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 v=mn(g),y=gn(g);return{sessionId:g.sessionId,...v?{modes:v}:{},...y?{models:y}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/load",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let b=await e.manager.loadFromDisk(m);if(!b)throw E(I.SessionNotFound,`session ${l} not found in memory or on disk`);g=await pn(e,b)}let h=Mt(a,g,u),{entries:v}=await g.attach(h,"pending_only");u.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let b of v){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}g.replayPendingPermissions(h);let y=mn(g),w=gn(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&c(p,"session/set_model");let l=ku(f,e.manager);if(l.kind==="error")throw n.log.warn(l.logMessage),E(l.code,l.message);if(l.kind==="no_op")return n.log.warn(l.logMessage),await a.notify("session/update",{sessionId:l.sessionId,update:{sessionUpdate:"current_model_update",currentModel:l.currentModel}}).catch(()=>{}),null;n.log.info(l.logMessage);let{modelId:m}=l,g=await l.session.forwardRequest("session/set_model",{...f,modelId:m});return l.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async f=>{let p=f,l=p?.sessionId;if(typeof l=="string"&&c(l,"session/set_mode"),!p||typeof p.sessionId!="string")throw E(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(I.InvalidParams,"session/set_mode requires string modeId");let m=se(e.manager,p.sessionId),g=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(p.modeId),g}),a.onRequest("session/set_config_option",async f=>{let p=f,l=v=>E(I.InvalidParams,v),m=p?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!p||typeof p.sessionId!="string")throw l("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw l("session/set_config_option requires string configId");if(typeof p.value!="string")throw l("session/set_config_option requires string value");let g=se(e.manager,p.sessionId),h=g.buildConfigOptions().find(v=>v.id===p.configId);if(!h)throw l(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(v=>v.value===p.value))throw l(`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 l(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let l=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=p.startsWith("session/"),g=p.startsWith("hydra-acp/");if(!m&&!g||f===null||typeof f!="object"||l.has(p))throw E(I.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(I.MethodNotFound,`Method not found: ${p}`);return c(h,p),se(e.manager,h).forwardRequest(p,f)})})}async function Iu(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(I.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 l=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let u=a.authMethods??[],c=u.find(l=>l.id===s);if(!c){let l=u.map(m=>m.id);throw E(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(m=>JSON.stringify(m)).join(", ")}]`)}let d=c._meta?.type,f=(()=>{let l=c._meta?.["terminal-auth"];if(l&&typeof l=="object"&&!Array.isArray(l))return l})();if((c.type??(d==="agent"||d==="terminal"?d:f!==void 0?"terminal":"agent"))==="terminal"){let l=(w,b)=>{if(!Array.isArray(w))throw E(I.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 E(I.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(f?.args!==void 0){let w=typeof f.command=="string"?f.command:void 0;g=w!==void 0&&gi.isAbsolute(w)?w:m.command,h=l(f.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?l(w.raw,w.label):[];g=m.command,h=[...m.args,...b]}let v={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(v[w]=b);Object.assign(v,m.env);let y=mi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g,args:h,env:v,cwd:y}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}async function Su(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,o=typeof s?.agentId=="string"?s.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function fi(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(wr,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 ku(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.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:I.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:I.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:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=ze(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:I.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 Au(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(I.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw E(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function Cu(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 E(I.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function xu(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 E(I.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function Mu(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 Ru(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",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},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function Eu(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 yi(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Mt(n,e,t,s,r){return{clientId:r??`cli_${As(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 Pu}from"crypto";import{McpServer as Tu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as _u}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 wi="Bearer ";function nt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(wi))return;let t=e.slice(wi.length).trim();return t.length>0?t:void 0}function $u(n){let e=new Tu({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 Fu=1e4;function vi(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=$u(a),d=new _u({sessionIdGenerator:()=>Pu()});await c.connect(d);let f={server:c,transport:d};return t.set(i,f),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,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Fu)}),m=await Promise.race([c.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0){a.code(503).send({error:"session not ready"});return}d=m}let f=await s(u,d);a.hijack(),await f.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 Ou}from"crypto";import{McpServer as Hu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Nu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function ju(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Bu(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 Uu(n){let e=new Hu({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:f}of Cs(i)){if(f==="tool_call"&&!r)continue;let p=Je([d]),l=p.toLowerCase().indexOf(t.toLowerCase());if(l<0)continue;let m=ju(f),g=Bu(p,l),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),f=Je(d);return{content:[{type:"text",text:f}],structuredContent:{text:f,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:l,entry:m,kind:g,update:h}of Cs(u)){if(g!=="tool_call"&&g!=="tool_call_update")continue;let v=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${l}`,y=d.get(v);y||(y={entryId:l,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,y),c.push(v)),typeof h.name=="string"&&h.name.length>0?y.toolName=h.name:(y.toolName==="(unnamed)"||g==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(y.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))y.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!y.locations.includes(A)&&y.locations.push(A)}typeof h.status=="string"&&(y.status=h.status),m.recordedAt!==void 0&&y.timestamp===void 0&&(y.timestamp=String(m.recordedAt))}let f=[];for(let l of c){let m=d.get(l);if(t!==void 0&&m.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),v=["file_path","filePath","path"],y=!1;for(let w of v){let b=m.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){y=!0;break}}if(!y){for(let w of m.locations)if(w.toLowerCase().includes(h)){y=!0;break}}if(!y)continue}let g={};for(let[h,v]of Object.entries(m.rawInput))typeof v=="string"?g[h]=v.length>500?v.slice(0,497)+"\u2026":v:(typeof v=="number"||typeof v=="boolean")&&(g[h]=v);if(m.locations.length>0&&g.locations===void 0&&(g.locations=m.locations),f.push({entryId:m.entryId,tool:m.toolName,args:g,status:m.status,timestamp:m.timestamp}),f.length>=r)break}let p=f.length>=r;return re({calls:f,truncated:p})}),e}var Du=1e4;function bi(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=Uu(a),d=new Nu({sessionIdGenerator:()=>Ou()});await c.connect(d);let f={server:c,transport:d};return t.set(i,f),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 f=await s(u,async()=>{if(c.session!==void 0)return c.session;let p,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Du)}),m=await Promise.race([c.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.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 Ku}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Gu}from"crypto";import{Server as Lu}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as qu,ListToolsRequestSchema as zu}from"@modelcontextprotocol/sdk/types.js";function Ii(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,o=new Lu({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(zu,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let u=await s.fetchSessionTools(a);if(u!==void 0)return{tools:u.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(qu,async(a,u)=>{let c=a.params.name,d=u._meta?.progressToken??u.requestId,f=Wu(d,u.sendNotification);try{let p=await r(),l=await Qu(e.connection,n,c,a.params.arguments??{},p);return Vu(l,c)}catch(p){return xs(p instanceof Error?p.message:String(p))}finally{f()}}),o}var Ju=15e3;function Wu(n,e,t=Ju){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 Vu(n,e){if(n===null||typeof n!="object")return xs(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:xs(`extension ${e} omitted content array`)}function xs(n){return{content:[{type:"text",text:n}],isError:!0}}var Yu=1e4;function Si(n,e,t){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function o(d){for(let f of s.values()){let p=f.get(d);p!==void 0&&(f.delete(d),r(p))}}async function i(d,f){for(let[p,l]of s){if(e.lookup(p)?.session?.sessionId!==d)continue;let g=l.get(f);if(g!==void 0)try{await g.server.sendToolListChanged()}catch{}}}t.onChange(d=>{o(d)});async function a(d,f){let p=s.get(d);p===void 0&&(p=new Map,s.set(d,p),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let A of b.values())await r(A)}}));let l=p.get(f);if(l!==void 0)return l.transport;let m=t.lookup(f);if(m===void 0)return;let y=Ii(f,m,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,C=new Promise(T=>{A=setTimeout(()=>T(void 0),Yu)}),x=await Promise.race([b.sessionReady.catch(()=>{}),C]);if(A!==void 0&&clearTimeout(A),x===void 0)throw new Error("session not ready");return x.sessionId},{peekSessionId:()=>e.lookup(d)?.session?.sessionId,fetchSessionTools:async b=>{let A=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!A||typeof A!="object")return;let C=A.tools;if(!Array.isArray(C))return;let x=[];for(let T of C){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),x.push(U)}return x}}),w=new Ku({sessionIdGenerator:()=>Gu()});return await y.connect(w),p.set(f,{server:y,transport:w}),w}async function u(d,f){let p=nt(d);if(p===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(p)===void 0){f.code(404).send({error:"unknown mcp token"});return}let m=d.params.name,g=await a(p,m);if(g===void 0){f.code(404).send({error:`unknown mcp server: ${m}`});return}f.hijack(),await g.handleRequest(d.raw,f.raw,d.body)}let c={config:{skipAuth:!0}};return n.post("/mcp/:name",c,async(d,f)=>{await u(d,f)}),n.get("/mcp/:name",c,async(d,f)=>{await u(d,f)}),n.delete("/mcp/:name",c,async(d,f)=>{await u(d,f)}),{notifyToolListChanged:i}}async function tl(n,e){rl(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(S.home(),{recursive:!0});let{stream:r,fileStream:o}=await nl(n.daemon.logLevel),i=Xu({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(Zu,{options:{handleProtocols:Ts}}),Rn(O=>{i.log.info(O)}),Tn(O=>{i.log.info(O)});let a=await nn.load(),u=new dn,c=new an,d=new on([new sn(e),new rn(a),c]),f=To({validator:d});i.addHook("onRequest",async(O,ce)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,ce)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let l=setInterval(()=>{u.sweepExpired()},300*1e3);l.unref();let m=new rt(n,{onFetched:()=>{Io(m,y)}});ms(O=>i.log.info(O));let g={info:O=>i.log.info(O),warn:O=>i.log.warn(O)},h=O=>he.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});Js(n.compressToolContent);let v=new en,y=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:v,defaultCwd:n.defaultCwd}),w=new Xt(js(n),void 0,{tokenRegistry:c}),b=new Zt(Bs(n),void 0,{tokenRegistry:c});si(i,K,Ao(n));let A=new yn,C=new wn,x,T=()=>{if(x!==void 0)return x;let O=i.server.address();return x=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,x};ti(i,y,{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:T}),ni(i,m,y,{npmRegistry:n.npmRegistry}),ri(i,w),oi(i,b),ii(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]}),li(i,{store:a,rateLimiter:u}),vi(i,A),bi(i,A);let _=Si(i,A,C);hi(i,{validator:d,manager:y,defaultAgent:n.defaultAgent,processRegistry:c,onExtensionVersion:(O,ce)=>w.reportVersion(O,ce),onTransformerVersion:(O,ce)=>b.reportVersion(O,ce),transformers:b,extensionCommands:v,mcpTokenRegistry:A,extensionMcp:C,extensionMcpControls:_,getDaemonOrigin:T,registry:m});let U=!!n.daemon.tls;await i.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=i.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,j,z=n.daemon.host,oe=P;if(U&&t&&s){j=sl({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:i.log});let O=j.address();O&&typeof O=="object"&&(oe=O.port)}await st.mkdir(S.home(),{recursive:!0}),await bo({pid:process.pid,host:z,port:oe,loopbackPort:P,startedAt:new Date().toISOString()});let $e={daemonUrl:`http://127.0.0.1:${P}`,daemonHost:"127.0.0.1",daemonPort:P,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${P}/acp`,hydraHome:S.home()};w.setContext($e),b.setContext($e),await w.start(),await b.start();try{await y.reconcilePermissionFlags()}catch(O){i.log.warn(`permission flag reconcile failed: ${O.message}`)}y.resurrectPendingQueues().catch(O=>{i.log.warn(`queue replay scan failed: ${O.message}`)}),y.resumePendingCompactions().catch(O=>{i.log.warn(`compaction resume scan failed: ${O.message}`)}),y.resumePendingAgentSwaps().catch(O=>{i.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Ms=Rt>0?So({registry:m,manager:y,intervalMs:Rt,logger:g}):void 0,Rs=n.daemon.sessionGcIntervalMinutes*60*1e3,Mi=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Es=Rs>0?ko({manager:y,intervalMs:Rs,maxAgeMs:Mi,logger:g}):void 0;return{app:i,manager:y,registry:m,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:C,processRegistry:c,shutdown:async()=>{Es&&Es(),Ms&&Ms(),clearInterval(p),clearInterval(l);let O=async(ce,Ri)=>{try{await Ri()}catch(vn){i.log.warn(`shutdown step ${ce} failed: ${vn instanceof Error?vn.message:String(vn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>y.closeAll()),await O("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>y.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),Rn(null),Tn(null),ms(null),j&&await O("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await O("app.close",()=>i.close());try{Ai.unlinkSync(S.pidFile())}catch{}await O("fileStream.flushSync",()=>o.flushSync())}}}async function nl(n){let e=await el({file:S.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=ki.destination(2);return{stream:ki.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function sl(n){let e=xi.createServer(n.tlsOptions,t=>{let s=Ci.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 rl(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,Ki as defaultConfig,_i as ensureServiceToken,Et as generateServiceToken,Ds as loadConfig,Ti as loadServiceToken,On as ndjsonStreamFromStdio,S as paths,te as planSpawn,tl as startDaemon,Vi as writeConfig,ks as wsToMessageStream};
137
+ `),r}function Dc(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=No(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Lc(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 qc(n,e){let t=e.session,s=Nr(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 c=[];if(a.used!==void 0){let u=a.size!==void 0?`${bs(a.size)}`:void 0;c.push(u?`${bs(a.used)} / ${u} tokens`:`${bs(a.used)} tokens`)}if(a.costAmount!==void 0){let u=a.costCurrency??"USD";c.push(`$${a.costAmount.toFixed(2)} ${u}`)}o.push(`- **Usage:** ${c.join(" \xB7 ")}`)}n.push(o.join(`
138
+ `)),n.push("")}function zc(n,e,t){if(!e.some(u=>Jc(u.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="")},c=()=>{i||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),i=!0)};for(let{event:u}of e)switch(u.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 u.text.split(`
139
+ `))n.push(`> ${_e(d)}`);n.push(""),n.push("**Assistant:**"),n.push(""),i=!0;break}case"agent-text":c(),o+=u.text;break;case"agent-thought":{c(),a();let d=u.text.split(`
140
+ `);for(let f of d)n.push(`> _${_e(f)}_`);n.push("");break}case"tool-call":{if(c(),a(),s.has(u.toolCallId))break;s.add(u.toolCallId);let d=t.get(u.toolCallId)??{title:u.title,status:u.status??"pending"};n.push(`- ${Qc(d.status)} ${Wc(d)}`),n.push("");break}case"tool-call-update":break;case"plan":{c(),a(),n.push("**Plan:**"),n.push("");for(let d of u.entries){let f=d.status==="completed"?"[x]":"[ ]";n.push(`- ${f} ${_e(d.content)}`)}n.push("");break}case"mode-changed":c(),a(),n.push(`_mode: ${_e(u.mode)}_`),n.push("");break;case"model-changed":c(),a(),n.push(`_model: ${_e(u.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Jc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Wc(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 bs(n){return n.toLocaleString("en-US")}function Wo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Vc(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,c=[];for(let d of s){let f=d.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:c.push(d)}i?o="AND":a&&(o="OR");let u=c.map(d=>Kc(d)).filter(d=>d.term.length>0);return{operator:o,terms:u}}function Kc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Qo(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:Qo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Qo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Gc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Yc=5,Xc=200,Vo=30;async function Yo(n,e,t={}){let s=Vc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Yc,o=t.maxSessions??Xc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),c=i?a.filter(f=>i.has(f.sessionId)):a,u=[],d=!1;for(let f of c){if(u.length>=o){d=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),l=Zc(p,s,r);if(l.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:l.totalMatches,snippets:l.snippets};f.title!==void 0&&(m.title=f.title),u.push(m)}return{query:e,truncated:d,results:u}}function Zc(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=eu(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 eu(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let c=tu(a).filter(u=>Gc(t,u.kind));for(let u of c){let d=u.text.toLowerCase(),f=d.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=d.indexOf(r,f+r.length);if(o+=p,i.length<s){let l=d.indexOf(r),m={kind:u.kind,text:iu(u.text,l,r.length),recordedAt:a.recordedAt};u.toolName!==void 0&&(m.toolName=u.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function tu(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"?ie(s.text):un(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(ru(s))return[];let o=un(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=ou(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return nu(s);default:return[]}}function nu(n){let e=Ko(n,"name"),t=Ko(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Go(r);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Go(o);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=su(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function su(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 ru(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 ie(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ie(e.text):""}function ou(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 Ko(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Go(n){try{return JSON.stringify(n)}catch{return""}}function iu(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-Vo),c=Math.min(s.length,i+o.length+Vo),u=a>0?"\u2026":"",d=c<s.length?"\u2026":"";return`${u}${s.slice(a,c)}${d}`}import{randomBytes as Zo}from"crypto";function Xo(n){let e=Zo(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(Xo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Xo({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=Zo(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 ei(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Wo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ni(n,e,t,s={}){n.get("/v1/sessions",async u=>{let d=u.query,f=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.getOne(p);return l||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(u,d)=>{let f=u.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return d.code(400).send({error:"q is required"}),d;let l=Array.isArray(f.sessionIds)?f.sessionIds.filter(g=>typeof g=="string"&&g.length>0):void 0;return await Yo(e,p,{sessionIds:l})}),n.post("/v1/sessions",async(u,d)=>{let f=u.body??{},p=Y(f.cwd??t.cwd),l=f.agentId??t.agentId,m=Ze(s),g=m!==void 0?[...f.mcpServers??[],...m.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:l,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(u,d)=>{let f=u.body??{},p=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,l=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,m=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let g=await hs({manager:e,maxAgeMs:p,maxDeletions:l,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(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){l.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(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return d.code(404).send({error:"session not found"}),d;let m=u.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=>ti.join(Ct.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return l.openStream(g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return d.code(404).send({error:"session not found"}),d;let m=u.body??{},g=typeof m.chunk=="string"?m.chunk:"",h=m.eof===!0;try{return l.streamWrite(g,h)}catch(v){return d.code(409).send({error:v.message}),d}}),n.patch("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{};if(l.priority!==void 0){let g=l.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(l.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 l.title!="string"||l.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,l.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){await l.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(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.query?.tools,m=l==="references"?"references":ro(l),g=await e.exportBundle(p,m==="references"?{tools:"references"}:{});if(!g){d.code(404).send({error:"session not found"});return}let h=gt({record:g.record,history:m==="summary"?oo(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:ei(t)}),v=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${p}-${v}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){d.code(404).send({error:"session not found"});return}let m=u.query??{},g=m.fold==="true"||m.fold==="1",h=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(y=>y.trim()).filter(y=>y.length>0)):void 0,v=qo(l.history);h&&(v=v.filter(y=>h.has(y.path))),g&&(v=v.map(y=>({...y,hunks:zo(y.hunks)}))),d.code(200).send(v)}),n.get("/v1/sessions/:id/tools/:hash",async(u,d)=>{let f=u.params,p=await e.resolveCanonicalId(f.id)??f.id,l=await e.loadToolBlob(p,f.hash);if(l===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(l)}),n.get("/v1/sessions/:id/transcript",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){d.code(404).send({error:"session not found"});return}let m=gt({record:l.record,history:l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,hydraVersion:K,machine:Ct.hostname(),hydraHost:ei(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(Jo(m))}),n.post("/v1/sessions/:id/fork",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{},m={};if(l.forkAt!==void 0){if(typeof l.forkAt!="string"||l.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}m.forkAt=l.forkAt}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}m.cwd=Y(l.cwd)}if(l.agentId!==void 0){if(typeof l.agentId!="string"||l.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}m.agentId=l.agentId}if(l.title!==void 0){if(typeof l.title!="string"){d.code(400).send({error:"title must be a string"});return}m.title=l.title}if(l.mode!==void 0){if(l.mode!=="verbatim"&&l.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=l.mode}if(l.model!==void 0){if(typeof l.model!="string"||l.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}m.model=l.model}try{let g=await e.forkSession(p,m);d.code(201).send(g)}catch(g){let h=g;if(h.code===I.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===I.InvalidParams||h.code===I.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),n.post("/v1/sessions/import",async(u,d)=>{let f=u.body??{};if(f.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let p;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}p=f.cwd}let l;try{l=mo(f.bundle)}catch(m){d.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(l,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});d.code(201).send(m)}catch(m){let g=m;if(g.code===I.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(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p),m;if(l?m=l.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),v=!1,y,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=m??0,x=b.length,T=b.slice(A).reduce((P,j)=>P+JSON.stringify(j.params).length,0);y=ws(T);let _=l?.currentModel,U=b.at(-1).recordedAt,$=l?.currentUsage;v=Fo({summarizedThroughEntry:A,totalEntries:x,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:v,...y!=null?{approxTokens:y}:{},...g!=null?{compactionState:g}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;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(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;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(l){let m=l instanceof Error?l.message:String(l);d.code(409).send({error:m})}}),n.get("/v1/sessions/:id/history",async(u,d)=>{let f=u.params.id,p=u.query,l=p?.follow==="1"||p?.follow==="true",m=await e.resolveCanonicalId(f)??f,g=e.get(m),h,v,y=!1,w=1e4,b=[];if(g){l&&(v=g.onBroadcast(x=>{d.raw.writableEnded||(y?d.raw.write(JSON.stringify(x)+`
141
+ `):(b.push(x),b.length>w&&b.shift()))})),u.raw.on("close",()=>{v?.(),d.raw.writableEnded||d.raw.end()});try{h=await g.getHistorySnapshot()}catch(x){throw v?.(),x}}else{let x=await e.getHistory(m);if(x===void 0)return d.code(404).send({error:"session not found"}),d;h=x}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 x of h??[]){d.raw.write(JSON.stringify(x)+`
142
+ `);let C=x;typeof C.recordedAt=="number"&&A.add(String(C.recordedAt))}for(;b.length>0;){let x=b.splice(0,b.length);for(let C of x){let T=C,_=typeof T.recordedAt=="number"?String(T.recordedAt):"";_&&A.has(_)||d.raw.write(JSON.stringify(C)+`
143
+ `)}}return y=!0,v||d.raw.end(),d});function r(u,d,f){let p=typeof u=="string"?u.trim():"";if(p.length===0)return null;let l;try{l=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!l||typeof l!="object"||Array.isArray(l))return console.debug("events endpoint: skipping non-object JSONL line"),null;let m=l;if(typeof m.recordedAt!="number"||f!==void 0&&m.recordedAt<f||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 v=g.update.sessionUpdate;return typeof v!="string"||!d.has(v)?null:{recordedAt:m.recordedAt,entry:l}}function o(u,d,f){let l=d.params.update,m={sessionId:u,ts:new Date(d.recordedAt).toISOString(),kind:f,update:l};return l.messageId!==void 0&&l.messageId!==null&&(m.messageId=l.messageId),m}async function*i(u,d,f,p){for await(let l of d){let m=r(l,f,p);if(m){let g=m.entry.params.update.sessionUpdate;yield{ts:m.recordedAt,row:o(u,m.entry,g)}}}}async function a(u,d,f,p){let l=ks.createInterface({input:Ss.createReadStream(d),crlfDelay:1/0}),m=i(u,l,f,p),g=await m.next(),h=g.done?null:g.value;return{sessionId:u,rl:l,gen:m,current:h,exhausted:h===null}}async function c(u){let d=await u.gen.next();d.done?(u.exhausted=!0,u.current=null):u.current=d.value}n.get("/v1/sessions/events",async(u,d)=>{let f=u.query,p=f.kinds;if(!p||p.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let l=p.split(",").map(w=>w.trim());if(l.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of l)if(!ln.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let m=new Set(l),g;if(f.since!==void 0&&f.since.trim().length>0){let w=new Date(f.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}),v=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 y=[];for(let w of v)try{let b=S.historyFile(w.sessionId),A=await a(w.sessionId,b,m,g);A.exhausted||y.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}u.raw.on("close",()=>{for(let w of y)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;y.length>0;){let w=-1,b=1/0;for(let x=0;x<y.length;x++){let C=y[x];C.current!==null&&C.current.ts<b&&(b=C.current.ts,w=x)}if(w===-1)break;let A=y[w];if(d.raw.write(JSON.stringify(A.current.row)+`
144
+ `),await c(A),A.exhausted){try{A.rl.close()}catch{}y.splice(w,1)}}}catch(w){for(let b of y)try{b.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(u,d)=>{let f=u.params.id,p=u.query,l=await e.resolveCanonicalId(f)??f;if(!e.get(l)&&!await e.hasRecord(l))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(x=>x.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let x of h)if(!ln.has(x))return d.code(400).send({error:`kind "${x}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let v=new Set(h),y;if(p.since!==void 0&&p.since.trim().length>0){let x=new Date(p.since);if(isNaN(x.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;y=x.getTime()}let w=S.historyFile(l),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 x of A){let C=typeof x=="string"?x.trim():"";if(C.length===0)continue;let T;try{T=JSON.parse(C)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!T||typeof T!="object"||Array.isArray(T)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let _=T;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let U=_.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let $=U.update,P=$.sessionUpdate;if(typeof P!="string"||!v.has(P)||y!==void 0&&_.recordedAt<y)continue;let j={ts:new Date(_.recordedAt).toISOString(),kind:P,update:$};$.messageId!==void 0&&$.messageId!==null&&(j.messageId=$.messageId),d.raw.write(JSON.stringify(j)+`
145
+ `)}}catch(x){if(x.code==="ENOENT")return d.raw.end(),d;throw x}return d.raw.end(),d}),n.get("/v1/sessions/:id/attention",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);return!l&&!await e.hasRecord(p)?(d.code(404).send({error:"session not found"}),d):l?{flags:l.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(u,d)=>{let f=u.query;if(!f.source||f.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let p=await e.list({includeNonInteractive:!0}),l=[];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 v of h)v.source===f.source&&l.push({...v,sessionId:m.sessionId})}return{flags:l}}),n.post("/v1/sessions/:id/attention/clear",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,m=u.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 v=e.get(p);if(v){if(g.length>0&&h.length>0)v.clearAttentionFlag(g,h);else{let x=Array.from(v.listAttentionFlags()).map(C=>`${C.source}::${C.reason}`);for(let C of x)v.clearAttentionFlag(C.split("::")[0],C.split("::").slice(1).join("::"))}d.code(204).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}let y=e.store,w=await y.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 x=`${g}::${h}`;A=b.filter(C=>`${C.source}::${C.reason}`!==x)}else A=[];if(A.length===b.length&&A.every((x,C)=>x.source===b[C].source&&x.reason===b[C].reason)){d.code(204).send();return}await y.write({...w,attentionFlags:A}),d.code(204).send()})}function si(n,e,t,s={}){n.get("/v1/agents",async()=>je(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 c=await te(a,[],{npmRegistry:s.npmRegistry}),u=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:c.version,distribution:u,installed:!0,command:c.command})}catch(c){o.code(500).send({error:c.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:c}=await t.syncFromAgent(i);return{synced:a.map(u=>({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,agentId:u.agentId,cwd:u.cwd,title:u.title,updatedAt:u.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===I.AgentNotInstalled){o.code(404).send({error:c.message});return}o.code(409).send({error:c.message})}})}function ri(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var au=/^[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,c=t.get(a);if(!c){i.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(o,i)=>{let a=o.body??{},c=du(a);if("error"in c){i.code(400).send({error:c.error});return}try{let u=t.register(c.config);i.code(201).send(u)}catch(u){xt(i,u)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(c){xt(i,c)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let c=await t.startByName(a);i.code(200).send(c)}catch(c){xt(i,c)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let c=await t.stopByName(a);i.code(200).send(c)}catch(c){xt(i,c)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let c=await t.restartByName(a);i.code(200).send(c)}catch(c){xt(i,c)}})}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 du(n){let e=n.name;if(typeof e!="string"||!au.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 oi(n,e){fn(n,"extension",e)}function ii(n,e){fn(n,"transformer",e)}function ai(n,e){n.get("/v1/config",async()=>e)}import{z as tt}from"zod";import*as et from"fs/promises";import*as di from"path";import{randomBytes as kg,scrypt as cu,timingSafeEqual as uu}from"crypto";import{promisify as lu}from"util";var fu=lu(cu);function ci(){return di.join(S.home(),"password-hash")}var pu=128*1024*1024;async function ui(){try{return(await et.readFile(ci(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function li(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await et.readFile(ci(),"utf8")).trim()}catch(u){if(u.code==="ENOENT")return!1;throw u}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 c=await fu(n,i,a.length,{N:s,r,p:o,maxmem:pu});return c.length!==a.length?!1:uu(c,a)}var mu=tt.object({password:tt.string().min(1),label:tt.string().min(1).max(256).optional(),ttlSec:tt.number().int().positive().optional()}),gu=tt.object({id:tt.string().optional()}).optional();function fi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=hu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=mu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await ui())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await li(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=gu.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 hu(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 c=JSON.parse(a);for(let u of e)u(c)}catch(c){for(let u of e)u({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${c.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,c)=>{n.send(i,u=>{if(u){c(u);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(c),o())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as mi}from"crypto";import*as gi from"os";import*as hi from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Iu(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 c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let u=c.content;typeof u.text=="string"&&(r+=u.text.length)}}return r}function se(n,e,t){let s=n.get(e);if(!s)throw E(I.SessionNotFound,t??`session ${e} not found`);return s}async function pn(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=mi(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]:[]],c=Is({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),u;try{u=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}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(u),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let d=s,f=n.mcpTokenRegistry;r.complete(u),u.onClose(()=>{f.unbind(d)})}return Pu(u,n),wi(u.sessionId,n),u}function yi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=$o({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),c={clientId:`hydra_client_${Cs(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let u=(f,p)=>{if(c.attached.get(f)?.readonly)throw E(I.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=ar.parse(f??{});p.clientInfo?.name&&(c.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let l=p.clientInfo?.version;return l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l)),Eu()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let l=p??{},m=Array.isArray(l.commands)?l.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let v={verb:h.verb};return typeof h.argsHint=="string"&&(v.argsHint=h.argsHint),typeof h.description=="string"&&(v.description=h.description),v}).filter(g=>g!==void 0):[];return f.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let m=l??{},g=typeof m.instructions=="string"?m.instructions:void 0,h=Array.isArray(m.tools)?m.tools.map(v=>{if(!v||typeof v!="object")return;let y=v;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let w={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(w.outputSchema=y.outputSchema),w}).filter(v=>v!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,g,h),{ok:!0,registered:h.length}});let p=l=>{let m=l??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw E(I.InvalidParams,"sessionId is required");return m.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(m,o.name,g.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async l=>{let m=p(l);if(!e.manager)throw E(I.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(m,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(g.value===void 0)throw E(I.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(I.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(m,o.name,g.key,g.value)}catch(h){throw E(I.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(m,o.name,g.key),{ok:!0}}),e.extensionMcpControls){let l=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async m=>{let g=m??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(I.InvalidParams,"refresh_session requires sessionId");return await l.notifyToolListChanged(g.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let l=p??{},m=Array.isArray(l.intercepts)?l.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,m),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,h=l.envelope,v=l.route;if(!m)throw E(-32602,"emit_message requires sessionId");if(!g&&v!=="client_broadcast")throw E(-32602,"emit_message requires method");let y=se(e.manager,m),w=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(w)return y.dischargeClaim(w,h),{ok:!0};if(v==="chain")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="queue"){if(g!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,h)}}if(v==="daemon")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(v)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0;if(!m)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,m).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async p=>Cu(p,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let l=p??{},m=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,v=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=v&&v["hydra-acp"]&&typeof v["hydra-acp"]=="object"?v["hydra-acp"]:void 0,w=y&&typeof y.title=="string"?y.title:void 0,b=y&&typeof y.model=="string"?y.model:void 0;if(!g&&h){let C=e.manager.get(h);C&&(g=C.cwd)}if(!g)throw E(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:m,cwd:g,parentSessionId:h,interactive:A,transformChain:[],title:w,model:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"fork_session requires sessionId");let m=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.agentId=="string"?l.agentId:void 0,v=typeof l.mode=="string"&&(l.mode==="verbatim"||l.mode==="synthesis")?l.mode:void 0,y=typeof l.model=="string"&&l.model.length>0?l.model:void 0;return await e.manager.forkSession(l.sessionId,{...m!==void 0?{forkAt:m}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{},...v!==void 0?{mode:v}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/fork requires sessionId");let m=typeof l.cwd=="string"?l.cwd:void 0;return{sessionId:(await e.manager.forkSession(l.sessionId,{...m!==void 0?{cwd:m}:{},mode:"verbatim"})).sessionId}});let f=async(p,l)=>{let m=p??{};if(typeof m.sessionId!="string")throw E(I.InvalidParams,`${l} requires sessionId`);let g=await e.manager.resolveCanonicalId(m.sessionId)??m.sessionId,h=e.manager.get(g);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(g),await e.manager.hasRecord(g)&&await e.manager.deleteRecord(g),{id:g,existed:!0};let v=await e.manager.deleteRecord(g);return{id:g,existed:v}};a.onRequest("session/delete",async p=>(await f(p,"session/delete"),{})),a.onRequest("session/close",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/close requires sessionId");u(l.sessionId,"session/close");let m=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=e.manager.get(m);if(g)return await g.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(m))return{};throw E(I.SessionNotFound,`session ${m} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:l,existed:m}=await f(p,"hydra-acp/session/delete");if(!m)throw E(I.SessionNotFound,`session ${l} not found`);return{deleted:!0,sessionId:l}}),a.onRequest("hydra-acp/child_session/await",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",h=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!m)throw E(-32602,"await_child requires childSessionId");let v=se(e.manager,m,`child session ${m} not found`);return new Promise(y=>{let A=[],x=[],C=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(j),_?.(),U?.(),y(T?{entries:A,truncated:!0}:{entries:A}))};_=v.onBroadcast(z=>{let oe=Iu(z);for(A.push(z),x.push(oe),C+=oe;A.length>0&&(A.length>1e3||C>1048576);)A.shift(),C-=x.shift()??0,T=!0;g==="turn_complete"&&z.params?.update?.sessionUpdate==="turn_complete"&&P()});let j=setTimeout(P,h);typeof j.unref=="function"&&j.unref(),U=v.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!m)throw E(-32602,"close_child_session requires childSessionId");let g=e.manager.get(m);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async p=>xu(p,o.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>Mu(p,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let l=p??{},m=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,h=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return m&&g&&e.manager.get(g)?.keepAliveClaim(m,h),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let p=f??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw E(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let l=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=await e.manager.loadToolBlob(l,p.hash);if(m===null)throw E(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>Su(f,e)),a.onRequest("logout",async f=>ku(f,e)),a.onRequest("session/new",async f=>{let p=dr.parse(f),l=at(f?._meta),m=Array.isArray(l.transformers)&&l.transformers.every(P=>typeof P=="string")?l.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,v,y=p.mcpServers;if(l.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=mi(32).toString("hex"),v=e.mcpTokenRegistry.reserve(h);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};y=[...p.mcpServers??[],j]}let w,b,A=Ze(e);A!==void 0&&(y=[...y??[],...A.descriptors]);let x=Is({baselineMcpServers:p.mcpServers,stdinEnabled:l.mcpStdin===!0,deps:e}),C;try{C=await e.manager.create({cwd:p.cwd,agentId:l.agentId??e.defaultAgent,mcpServers:y,title:l.title,agentArgs:l.agentArgs,model:l.model,onInstallProgress:pi(a),transformChain:g,originatingClient:c.clientInfo,...l.interactive!==void 0?{interactive:l.interactive}:{},...l.env!==void 0?{forwardedEnv:l.env}:{},...x?{mintMcpServersForSwap:x}:{}})}catch(P){throw v!==void 0&&v.abandon(P instanceof Error?P:void 0),b!==void 0&&b.abandon(P instanceof Error?P:void 0),A!==void 0&&A.abandon(P instanceof Error?P:void 0),P}if(h!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,j=e.mcpTokenRegistry;v.complete(C),C.onClose(()=>{j.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,j=e.mcpTokenRegistry;b.complete(C),C.onClose(()=>{j.unbind(P)})}A!==void 0&&A.bindToSession(C),wi(C.sessionId,e);let T,_;try{yn(c,C,C.sessionId),T=Mt(a,C,c),{entries:_}=await C.attach(T,"full")}catch(P){throw await C.close({deleteRecord:!1}).catch(()=>{}),P}c.attached.set(C.sessionId,{sessionId:C.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=mn(C),$=gn(C);return{sessionId:C.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:C.buildConfigOptions(),_meta:hn(e.manager,C,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=ur.parse(f),l=p.clientInfo?.version;l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l));let m=at(p._meta),g=m.resume,h=m.readonly===!0,v=m.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(y);if(!w&&h){let $=await e.manager.loadFromDisk(y);if(!$)throw E(I.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(y),j=p.clientId??`cli_${Cs(8)}`;c.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${j} attachedCount=${c.attached.size} replayed=${P.length}`);for(let z of P)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:P.length,_meta:Ru($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(y),P=$;if(g&&(P={...$,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}:{}}),!P)throw E(I.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(I.SessionNotFound,`session ${p.sessionId} was deleted`);let j=P.originatingClient?P:{...P,originatingClient:c.clientInfo},z=v!==void 0?{...j,forwardedEnv:v}:j;w=await pn(e,{...z,onInstallProgress:pi(a)})}yn(c,w,w.sessionId);let A=Mt(a,w,c,p.clientInfo,p.clientId),x=m.replayMode==="drip",{entries:C,appliedPolicy:T}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:x,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),v!==void 0&&await e.manager.setForwardedEnv(w.sessionId,v).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${C.length} readonly=${h}${x?" replayMode=drip":""}`),x){let $=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,P=750;(async()=>{let j=null;for(let z of C){let oe=typeof z.recordedAt=="number"?z.recordedAt:null;if(j!==null&&oe!==null){let $e=Math.min(P,Math.max(0,(oe-j)/$));$e>0&&await new Promise(Rt=>setTimeout(Rt,$e))}oe!==null&&(j=oe);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let $=0;$<C.length&&!a.isClosed();$++){let P=C[$],j=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await j}w.replayPendingPermissions(A);let _=mn(w),U=gn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:C.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:hn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=lr.parse(f),l=c.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(p.sessionId);return m?.detach(l.clientId),c.attached.delete(p.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[it]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=fr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Lt).map(pr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(I.InternalError,"agent registry unavailable");return je(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let p=f??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw E(I.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 f=>{let p=mr.parse(f);u(p.sessionId,"session/prompt");let l=c.attached.get(p.sessionId);if(!l)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),E(I.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 E(I.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),m=await pn(e,g);let h=Mt(a,m,c,void 0,l.clientId);await m.attach(h,"none")}return m.prompt(l.clientId,p)});let d=f=>{let p;try{p=Ot.parse(f)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let l=c.attached.get(p.sessionId);if(!l)return;if(l.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let m=e.manager.get(p.sessionId);m&&m.cancel(l.clientId).catch(g=>{n.log.warn(`session/cancel for ${p.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async f=>{let p=Ot.parse(f);return u(p.sessionId,"session/cancel"),d(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=hr.parse(f);return u(p.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=Ot.parse(f);return u(p.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=yr.parse(f);return u(p.sessionId,"hydra-acp/prompt/update"),se(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let p=wr.parse(f);u(p.sessionId,"hydra-acp/prompt/amend");let l=c.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"not attached to session");return se(e.manager,p.sessionId).amendPrompt(l.clientId,p)}),a.onRequest("session/resume",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let w=await e.manager.loadFromDisk(m);if(!w)throw E(I.SessionNotFound,`session ${l} not found in memory or on disk`);g=await pn(e,w)}yn(c,g,g.sessionId);let h=Mt(a,g,c);await g.attach(h,"pending_only"),c.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1}),g.replayPendingPermissions(h);let v=mn(g),y=gn(g);return{sessionId:g.sessionId,...v?{modes:v}:{},...y?{models:y}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/load",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let b=await e.manager.loadFromDisk(m);if(!b)throw E(I.SessionNotFound,`session ${l} not found in memory or on disk`);g=await pn(e,b)}yn(c,g,g.sessionId);let h=Mt(a,g,c),{entries:v}=await g.attach(h,"pending_only");c.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let b of v){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}g.replayPendingPermissions(h);let y=mn(g),w=gn(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&u(p,"session/set_model");let l=Au(f,e.manager);if(l.kind==="error")throw n.log.warn(l.logMessage),E(l.code,l.message);if(l.kind==="no_op")return n.log.warn(l.logMessage),await a.notify("session/update",{sessionId:l.sessionId,update:{sessionUpdate:"current_model_update",currentModel:l.currentModel}}).catch(()=>{}),null;n.log.info(l.logMessage);let{modelId:m}=l,g=await l.session.forwardRequest("session/set_model",{...f,modelId:m});return l.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async f=>{let p=f,l=p?.sessionId;if(typeof l=="string"&&u(l,"session/set_mode"),!p||typeof p.sessionId!="string")throw E(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(I.InvalidParams,"session/set_mode requires string modeId");let m=se(e.manager,p.sessionId),g=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(p.modeId),g}),a.onRequest("session/set_config_option",async f=>{let p=f,l=v=>E(I.InvalidParams,v),m=p?.sessionId;if(typeof m=="string"&&u(m,"session/set_config_option"),!p||typeof p.sessionId!="string")throw l("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw l("session/set_config_option requires string configId");if(typeof p.value!="string")throw l("session/set_config_option requires string value");let g=se(e.manager,p.sessionId),h=g.buildConfigOptions().find(v=>v.id===p.configId);if(!h)throw l(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(v=>v.value===p.value))throw l(`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 l(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let l=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=p.startsWith("session/"),g=p.startsWith("hydra-acp/");if(!m&&!g||f===null||typeof f!="object"||l.has(p))throw E(I.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(I.MethodNotFound,`Method not found: ${p}`);return u(h,p),se(e.manager,h).forwardRequest(p,f)})})}async function Su(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(I.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 l=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let c=a.authMethods??[],u=c.find(l=>l.id===s);if(!u){let l=c.map(m=>m.id);throw E(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(m=>JSON.stringify(m)).join(", ")}]`)}let d=u._meta?.type,f=(()=>{let l=u._meta?.["terminal-auth"];if(l&&typeof l=="object"&&!Array.isArray(l))return l})();if((u.type??(d==="agent"||d==="terminal"?d:f!==void 0?"terminal":"agent"))==="terminal"){let l=(w,b)=>{if(!Array.isArray(w))throw E(I.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 E(I.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(f?.args!==void 0){let w=typeof f.command=="string"?f.command:void 0;g=w!==void 0&&hi.isAbsolute(w)?w:m.command,h=l(f.args,'_meta["terminal-auth"].args')}else{let w=u.args!==void 0?{raw:u.args,label:"args"}:u._meta?.args!==void 0?{raw:u._meta.args,label:"_meta.args"}:void 0,b=w!==void 0?l(w.raw,w.label):[];g=m.command,h=[...m.args,...b]}let v={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(v[w]=b);Object.assign(v,m.env);let y=gi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g,args:h,env:v,cwd:y}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}async function ku(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,o=typeof s?.agentId=="string"?s.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function pi(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(vr,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 Au(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.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:I.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:I.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:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=ze(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(c=>c.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:I.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 Cu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(I.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw E(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function xu(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 E(I.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function Mu(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 E(I.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function Ru(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 Eu(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:ot(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function Pu(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 wi(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Mt(n,e,t,s,r){return{clientId:r??`cli_${Cs(8)}`,connection:n,clientInfo:s}}function yn(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var wn=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 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 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 vi="Bearer ";function nt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(vi))return;let t=e.slice(vi.length).trim();return t.length>0?t:void 0}function Fu(n){let e=new _u({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 Ou=1e4;function bi(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let u=Fu(a),d=new $u({sessionIdGenerator:()=>Tu()});await u.connect(d);let f={server:u,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await u.close()}catch{}}),d}async function r(i,a){let c=nt(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(c);if(u===void 0){a.code(404).send({error:"unknown stdin token"});return}let d;if(u.session!==void 0)d=u.session;else{let p,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Ou)}),m=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0){a.code(503).send({error:"session not ready"});return}d=m}let f=await s(c,d);a.hijack(),await f.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 Hu}from"crypto";import{McpServer as Nu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as ju}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function Bu(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Uu(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 Du(n){let e=new Nu({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:u,entry:d,kind:f}of xs(i)){if(f==="tool_call"&&!r)continue;let p=Je([d]),l=p.toLowerCase().indexOf(t.toLowerCase());if(l<0)continue;let m=Bu(f),g=Uu(p,l),h=typeof d.recordedAt=="number"?String(d.recordedAt):void 0;if(a.push({entryId:u,speaker:m,snippet:g,timestamp:h}),a.length>=s)break}let c=a.length>=s&&a.length<i.length;return re({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry: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),c=Math.min(s,i.length-1),u=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:u}};let d=i.slice(a,c+1),f=Je(d);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:d.length,truncated:u}}}),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 c=await o.getHistorySnapshot(),u=[],d=new Map;for(let{entryId:l,entry:m,kind:g,update:h}of xs(c)){if(g!=="tool_call"&&g!=="tool_call_update")continue;let v=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${l}`,y=d.get(v);y||(y={entryId:l,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,y),u.push(v)),typeof h.name=="string"&&h.name.length>0?y.toolName=h.name:(y.toolName==="(unnamed)"||g==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(y.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))y.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!y.locations.includes(A)&&y.locations.push(A)}typeof h.status=="string"&&(y.status=h.status),m.recordedAt!==void 0&&y.timestamp===void 0&&(y.timestamp=String(m.recordedAt))}let f=[];for(let l of u){let m=d.get(l);if(t!==void 0&&m.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),v=["file_path","filePath","path"],y=!1;for(let w of v){let b=m.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){y=!0;break}}if(!y){for(let w of m.locations)if(w.toLowerCase().includes(h)){y=!0;break}}if(!y)continue}let g={};for(let[h,v]of Object.entries(m.rawInput))typeof v=="string"?g[h]=v.length>500?v.slice(0,497)+"\u2026":v:(typeof v=="number"||typeof v=="boolean")&&(g[h]=v);if(m.locations.length>0&&g.locations===void 0&&(g.locations=m.locations),f.push({entryId:m.entryId,tool:m.toolName,args:g,status:m.status,timestamp:m.timestamp}),f.length>=r)break}let p=f.length>=r;return re({calls:f,truncated:p})}),e}var Lu=1e4;function Ii(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let u=Du(a),d=new ju({sessionIdGenerator:()=>Hu()});await u.connect(d);let f={server:u,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await u.close()}catch{}}),d}async function r(i,a){let c=nt(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(c);if(u===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(c,async()=>{if(u.session!==void 0)return u.session;let p,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Lu)}),m=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.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 vn=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 Gu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Yu}from"crypto";import{Server as qu}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as zu,ListToolsRequestSchema as Ju}from"@modelcontextprotocol/sdk/types.js";function Si(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,o=new qu({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(Ju,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(zu,async(a,c)=>{let u=a.params.name,d=c._meta?.progressToken??c.requestId,f=Qu(d,c.sendNotification);try{let p=await r(),l=await Vu(e.connection,n,u,a.params.arguments??{},p);return Ku(l,u)}catch(p){return Ms(p instanceof Error?p.message:String(p))}finally{f()}}),o}var Wu=15e3;function Qu(n,e,t=Wu){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 Vu(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function Ku(n,e){if(n===null||typeof n!="object")return Ms(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Ms(`extension ${e} omitted content array`)}function Ms(n){return{content:[{type:"text",text:n}],isError:!0}}var Xu=1e4;function ki(n,e,t){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function o(d){for(let f of s.values()){let p=f.get(d);p!==void 0&&(f.delete(d),r(p))}}async function i(d,f){for(let[p,l]of s){if(e.lookup(p)?.session?.sessionId!==d)continue;let g=l.get(f);if(g!==void 0)try{await g.server.sendToolListChanged()}catch{}}}t.onChange(d=>{o(d)});async function a(d,f){let p=s.get(d);p===void 0&&(p=new Map,s.set(d,p),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let A of b.values())await r(A)}}));let l=p.get(f);if(l!==void 0)return l.transport;let m=t.lookup(f);if(m===void 0)return;let y=Si(f,m,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,x=new Promise(T=>{A=setTimeout(()=>T(void 0),Xu)}),C=await Promise.race([b.sessionReady.catch(()=>{}),x]);if(A!==void 0&&clearTimeout(A),C===void 0)throw new Error("session not ready");return C.sessionId},{peekSessionId:()=>e.lookup(d)?.session?.sessionId,fetchSessionTools:async b=>{let A=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!A||typeof A!="object")return;let x=A.tools;if(!Array.isArray(x))return;let C=[];for(let T of x){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),C.push(U)}return C}}),w=new Gu({sessionIdGenerator:()=>Yu()});return await y.connect(w),p.set(f,{server:y,transport:w}),w}async function c(d,f){let p=nt(d);if(p===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(p)===void 0){f.code(404).send({error:"unknown mcp token"});return}let m=d.params.name,g=await a(p,m);if(g===void 0){f.code(404).send({error:`unknown mcp server: ${m}`});return}f.hijack(),await g.handleRequest(d.raw,f.raw,d.body)}let u={config:{skipAuth:!0}};return n.post("/mcp/:name",u,async(d,f)=>{await c(d,f)}),n.get("/mcp/:name",u,async(d,f)=>{await c(d,f)}),n.delete("/mcp/:name",u,async(d,f)=>{await c(d,f)}),{notifyToolListChanged:i}}async function nl(n,e){ol(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(S.home(),{recursive:!0});let{stream:r,fileStream:o}=await sl(n.daemon.logLevel),i=Zu({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(el,{options:{handleProtocols:_s}}),En(O=>{i.log.info(O)}),_n(O=>{i.log.info(O)});let a=await nn.load(),c=new dn,u=new an,d=new on([new sn(e),new rn(a),u]),f=_o({validator:d});i.addHook("onRequest",async(O,ce)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,ce)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let l=setInterval(()=>{c.sweepExpired()},300*1e3);l.unref();let m=new rt(n,{onFetched:()=>{So(m,y)}});gs(O=>i.log.info(O));let g={info:O=>i.log.info(O),warn:O=>i.log.warn(O)},h=O=>he.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});Ws(n.compressToolContent);let v=new en,y=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:v,defaultCwd:n.defaultCwd}),w=new Xt(Bs(n),void 0,{tokenRegistry:u}),b=new Zt(Us(n),void 0,{tokenRegistry:u});ri(i,K,Co(n));let A=new wn,x=new vn,C,T=()=>{if(C!==void 0)return C;let O=i.server.address();return C=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,C};ni(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:x,mcpTokenRegistry:A,getDaemonOrigin:T}),si(i,m,y,{npmRegistry:n.npmRegistry}),oi(i,w),ii(i,b),ai(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]}),fi(i,{store:a,rateLimiter:c}),bi(i,A),Ii(i,A);let _=ki(i,A,x);yi(i,{validator:d,manager:y,defaultAgent:n.defaultAgent,processRegistry:u,onExtensionVersion:(O,ce)=>w.reportVersion(O,ce),onTransformerVersion:(O,ce)=>b.reportVersion(O,ce),transformers:b,extensionCommands:v,mcpTokenRegistry:A,extensionMcp:x,extensionMcpControls:_,getDaemonOrigin:T,registry:m});let U=!!n.daemon.tls;await i.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=i.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,j,z=n.daemon.host,oe=P;if(U&&t&&s){j=rl({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:i.log});let O=j.address();O&&typeof O=="object"&&(oe=O.port)}await st.mkdir(S.home(),{recursive:!0}),await Io({pid:process.pid,host:z,port:oe,loopbackPort:P,startedAt:new Date().toISOString()});let $e={daemonUrl:`http://127.0.0.1:${P}`,daemonHost:"127.0.0.1",daemonPort:P,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${P}/acp`,hydraHome:S.home()};w.setContext($e),b.setContext($e),await w.start(),await b.start();try{await y.reconcilePermissionFlags()}catch(O){i.log.warn(`permission flag reconcile failed: ${O.message}`)}y.resurrectPendingQueues().catch(O=>{i.log.warn(`queue replay scan failed: ${O.message}`)}),y.resumePendingCompactions().catch(O=>{i.log.warn(`compaction resume scan failed: ${O.message}`)}),y.resumePendingAgentSwaps().catch(O=>{i.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Rs=Rt>0?ko({registry:m,manager:y,intervalMs:Rt,logger:g}):void 0,Es=n.daemon.sessionGcIntervalMinutes*60*1e3,Ri=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ps=Es>0?Ao({manager:y,intervalMs:Es,maxAgeMs:Ri,logger:g}):void 0;return{app:i,manager:y,registry:m,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:x,processRegistry:u,shutdown:async()=>{Ps&&Ps(),Rs&&Rs(),clearInterval(p),clearInterval(l);let O=async(ce,Ei)=>{try{await Ei()}catch(bn){i.log.warn(`shutdown step ${ce} failed: ${bn instanceof Error?bn.message:String(bn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>y.closeAll()),await O("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>y.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),En(null),_n(null),gs(null),j&&await O("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await O("app.close",()=>i.close());try{Ci.unlinkSync(S.pidFile())}catch{}await O("fileStream.flushSync",()=>o.flushSync())}}}async function sl(n){let e=await tl({file:S.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=Ai.destination(2);return{stream:Ai.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function rl(n){let e=Mi.createServer(n.tlsOptions,t=>{let s=xi.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 ol(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,Gi as defaultConfig,$i as ensureServiceToken,Et as generateServiceToken,Ls as loadConfig,_i as loadServiceToken,Hn as ndjsonStreamFromStdio,S as paths,te as planSpawn,nl as startDaemon,Ki as writeConfig,As as wsToMessageStream};