@hydra-acp/cli 0.1.72 → 0.1.74

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,25 +1,25 @@
1
- import*as ki from"fs";import*as ye from"fs/promises";import $c from"fastify";import Oc from"@fastify/websocket";var qn="acp.v1";function Jn(n,e){return n.has(qn)?qn:!1}import Si from"pino";import Fc from"pino-roll";import*as Vn from"fs/promises";import{homedir as Kt}from"os";import{z as v}from"zod";import*as E from"path";import*as Gt from"os";var xi="HYDRA_ACP_HOME";function Ce(n){let e=Gt.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function T(){let n=process.env[xi];if(n&&n.length>0)return E.resolve(n);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return E.join(Gt.homedir(),".hydra-acp")}var w={home:T,config:()=>E.join(T(),"config.json"),authToken:()=>E.join(T(),"auth-token"),remotes:()=>E.join(T(),"remotes.json"),pidFile:()=>E.join(T(),"daemon.pid"),logFile:()=>E.join(T(),"daemon.log"),currentLogFile:()=>E.join(T(),"current.log"),registryCache:()=>E.join(T(),"registry.json"),agentsDir:()=>E.join(T(),"agents"),agentLogFile:n=>E.join(T(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>E.join(T(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>E.join(T(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>E.join(T(),"sessions"),sessionDir:n=>E.join(T(),"sessions",n),sessionFile:n=>E.join(T(),"sessions",n,"meta.json"),historyFile:n=>E.join(T(),"sessions",n,"history.jsonl"),toolsDir:n=>E.join(T(),"sessions",n,"tools"),toolBlobFile:(n,e)=>E.join(T(),"sessions",n,"tools",e),queueFile:n=>E.join(T(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>E.join(T(),"sessions",".tombstones"),tombstoneAgentDir:n=>E.join(T(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>E.join(T(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>E.join(T(),"extensions"),extensionLogFile:n=>E.join(T(),"extensions",`${n}.log`),extensionPidFile:n=>E.join(T(),"extensions",`${n}.pid`),transformersDir:()=>E.join(T(),"transformers"),transformerLogFile:n=>E.join(T(),"transformers",`${n}.log`),transformerPidFile:n=>E.join(T(),"transformers",`${n}.pid`),transformerState:(n,e)=>E.join(T(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>E.join(T(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>E.join(T(),"prompt-history"),tuiLogFile:()=>E.join(T(),"tui.log"),shimWireLogFile:()=>E.join(T(),"shim-wire.log")};import*as Me from"fs/promises";function lt(){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 zn(){try{let e=(await Me.readFile(w.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ci(){let n=await zn();if(!n)throw new Error(`No service token found at ${w.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Yt(n){await Me.mkdir(w.home(),{recursive:!0}),await Me.writeFile(w.authToken(),n+`
2
- `,{encoding:"utf8",mode:384})}async function Mi(){let n=await zn();if(n)return n;let e=lt();return await Yt(e),process.stderr.write(`hydra-acp: initialized ${w.authToken()} with a fresh service token.
3
- `),e}import*as se from"fs/promises";import*as Wn from"fs";import{randomBytes as Ri}from"crypto";async function Z(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
- `;await Ei(n,r,t)}async function Ei(n,e,t={}){let s=Pi(n);await se.mkdir(s,{recursive:!0});let r=`${n}.tmp-${process.pid}-${Ti()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await se.writeFile(r,e,i),await se.rename(r,n)}catch(i){throw await se.unlink(r).catch(()=>{}),i}if(t.mode!==void 0)try{Wn.chmodSync(n,t.mode)}catch{}}async function re(n){let e;try{e=await se.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 Pi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Ti(){return Ri(4).toString("hex")}var Gn="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",_i=v.object({cert:v.string(),key:v.string()}),Yn=55514,$i=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(Yn),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:_i.optional(),sessionIdleTimeoutSeconds:v.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:v.number().int().positive().default(1e4),agentStderrTailBytes:v.number().int().positive().default(4096),publicHost:v.string().optional(),agentSyncIntervalMinutes:v.number().nonnegative().default(60),sessionGcIntervalMinutes:v.number().nonnegative().default(60),sessionGcMaxAgeDays:v.number().positive().default(2)}),Oi=v.object({url:v.string().url().default(Gn),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),Fi=v.object({name:v.string().optional(),description:v.string().optional(),command:v.string().optional(),args:v.array(v.string()).optional(),env:v.record(v.string()).optional()}),Ni=v.object({packageSpec:v.string().optional()}),Hi=v.object({repaintThrottleMs:v.number().int().nonnegative().default(1e3),maxScrollbackLines:v.number().int().positive().default(1e4),mouse:v.boolean().default(!1),inAppSelection:v.boolean().optional(),selectionClipboard:v.enum(["primary","clipboard","both"]).default("both"),logMaxBytes:v.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:v.number().int().positive().default(32),progressIndicator:v.boolean().default(!0),defaultEnterAction:v.enum(["enqueue","amend"]).default("amend"),showThoughts:v.boolean().default(!0),ambiguousWidth:v.enum(["narrow","wide"]).default("wide"),toolContent:v.enum(["inline","references"]).default("references"),diffContextLines:v.number().int().min(0).default(3),promptHistoryMaxEntries:v.number().int().positive().default(2e3),maxToolItems:v.number().int().nonnegative().default(5),maxPlanItems:v.number().int().nonnegative().default(5),showFileUpdates:v.enum(["none","edit","diff"]).default("edit"),sessionColumns:v.array(v.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Qn=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),ji=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),Bi=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),Kn=v.object({daemon:$i.default({}),registry:Oi.default({url:Gn,ttlHours:24,pinned:!1}),agents:v.record(v.string(),Fi).default({}),agentOverrides:v.record(v.string(),Ni).default({}),defaultAgent:v.string().default("opencode"),defaultModels:v.record(v.string(),v.string()).default({}),synopsisAgent:v.string().optional(),synopsisModel:v.string().optional(),synopsisOnClose:v.boolean().default(!1),defaultCwd:v.string().default("~"),compressToolContent:v.boolean().default(!0),sessionListColdLimit:v.number().int().nonnegative().default(20),extensions:v.record(Qn,ji).default({}),transformers:v.record(Qn,Bi).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Hi.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!1,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"wide",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function Xn(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Zn(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function es(){return await re(w.config())??{}}async function Ui(){let n=await es(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Vn.access(w.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${w.authToken()} and ${w.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Yt(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await Z(w.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${w.config()} to ${w.authToken()}.
5
- `)}async function ts(){return await Ui(),Kn.parse(await es())}async function Di(n){await Z(w.config(),n,{mode:384})}function Li(){return Kn.parse({})}function qe(n){return n==="~"||n==="$HOME"?Kt():n.startsWith("~/")?Kt()+n.slice(1):n.startsWith("$HOME/")?Kt()+n.slice(5):n}import*as J from"fs/promises";import{createHash as qi}from"crypto";import{gzip as Ji,gunzip as zi}from"zlib";import{promisify as ns}from"util";var ss=ns(Ji),Wi=ns(zi),rs=/^[A-Za-z0-9_-]+$/,Qi=/^[a-f0-9]{64}$/,Xt=!0;function is(n){Xt=n}function ft(n,e){return rs.test(n)?e===void 0||Qi.test(e):!1}function pt(n,e){return`${w.toolBlobFile(n,e)}.gz`}async function Zt(n,e){if(!ft(n))return null;let t=qi("sha256").update(e,"utf8").digest("hex"),s=pt(n,t),r=w.toolBlobFile(n,t);for(let a of[s,r])try{return await J.access(a),t}catch{}await J.mkdir(w.toolsDir(n),{recursive:!0});let i=Xt?s:r,o=Xt?await ss(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await J.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function mt(n,e){if(!ft(n,e))return null;try{let t=await J.readFile(pt(n,e));return(await Wi(t)).toString("utf8")}catch{}try{return await J.readFile(w.toolBlobFile(n,e),"utf8")}catch{return null}}async function os(n,e){if(!ft(n,e))return null;try{return await J.readFile(pt(n,e))}catch{}try{let t=await J.readFile(w.toolBlobFile(n,e));return await ss(t)}catch{return null}}async function as(n,e,t){if(!ft(n,e))return;let s=pt(n,e);try{await J.access(s);return}catch{}await J.mkdir(w.toolsDir(n),{recursive:!0}),await J.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function ds(n){rs.test(n)&&await J.rm(w.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as vs from"fs/promises";import*as gt from"path";import{z as M}from"zod";import*as us from"fs";import*as W from"fs/promises";import*as me from"path";import{spawn as ls}from"child_process";import{Readable as Vi}from"stream";function ie(){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 nn(n,e=ie()){if(e)return n[e]}var Re=n=>{process.stderr.write(n+`
6
- `)};function sn(n){Re=n??(e=>process.stderr.write(e+`
7
- `))}async function fs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${ie()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=ie();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentInstallDir(n.agentId,e,n.version),s=me.resolve(t,n.target.cmd);if(await tn(s))return s;if(await Gi({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await tn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await W.chmod(s,493).catch(()=>{}),s}async function Gi(n){await W.mkdir(me.dirname(n.installDir),{recursive:!0});let e=await W.mkdtemp(`${n.installDir}.partial-`);try{Re(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await Yi({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Re(`hydra-acp: extracting ${n.agentId}`),Ee(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await Xi(t,e),await W.unlink(t).catch(()=>{});try{await W.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await tn(n.installDir)){await W.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Ee(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Re(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Ee(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await W.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Ee(n,e){if(n)try{n(e)}catch{}}async function Yi(n){let e=Ki(n.url),t=me.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=us.createWriteStream(t),o=Vi.fromWeb(s.body);Ee(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),c=0,f=2e3,u=150;return o.on("data",l=>{a+=l.length;let p=Date.now();p-c>=u&&(c=p,Ee(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=f&&(d=p,Re(cs(n.agentId,a,r)))}),await new Promise((l,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>l()),o.pipe(i)}),Re(cs(n.agentId,a,r,!0)),Ee(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function cs(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function Ki(n){let e=new URL(n);return me.posix.basename(e.pathname)||"archive"}async function Xi(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await en("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await Zi("unzip")){await en("unzip",["-q",n,"-d",e]);return}await en("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function en(n,e){return new Promise((t,s)=>{let r=ls(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function Zi(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=ls(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function tn(n){try{return await W.access(n),!0}catch{return!1}}import*as K from"fs/promises";import*as oe from"path";import{spawn as eo}from"child_process";var on=n=>{process.stderr.write(n+`
8
- `)};function an(n){on=n??(e=>process.stderr.write(e+`
9
- `))}async function ms(n){let e=ie();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentNpmInstallDir(n.agentId,e,n.version),s=io(n.packageSpec),r=oo(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=oe.join(t,"node_modules",".bin",n.bin);if(await Ie(o))return o;if(await Ie(t)){let u=await ps(i);if(u)return u.binPath}await to({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await ps(i);if(a)return a.binPath;let d=await hs(t,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],f=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/)${f}`)}async function to(n){await K.mkdir(oe.dirname(n.installDir),{recursive:!0});let e=await K.mkdtemp(`${n.installDir}.partial-`);try{on(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),rn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ro({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await K.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Ie(n.installDir)){await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),rn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}on(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),rn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function rn(n,e){if(n)try{n(e)}catch{}}var no=5,so=25;function ro(n){return gs(n,0)}async function gs(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=eo("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,d)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,f=o.trim();s(new Error(f?`npm install ${n.packageSpec} failed (${c})
10
- stderr: ${f}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<no)return await new Promise(r=>setTimeout(r,so*(e+1))),gs(n,e+1);throw t}}function io(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 oo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function hs(n,e){let t=oe.join(n,"node_modules",e,"package.json");try{let s=await K.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 ps(n){let e=oe.join(n.installDir,"node_modules",".bin"),t=oe.join(e,n.hint);if(await Ie(t))return{binName:n.hint,binPath:t};let s=await hs(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=oe.join(e,i);if(await Ie(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=oe.join(e,i);if(await Ie(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=oe.join(e,n.basename);if(await Ie(r))return{binName:n.basename,binPath:r}}}async function Ie(n){try{return await K.access(n),!0}catch{return!1}}var ao=M.object({package:M.string(),bin:M.string().optional(),args:M.array(M.string()).optional(),env:M.record(M.string()).optional()}),Pe=M.object({archive:M.string().url().optional(),cmd:M.string().optional(),args:M.array(M.string()).optional(),env:M.record(M.string()).optional()}),co=M.object({"darwin-aarch64":Pe.optional(),"darwin-x86_64":Pe.optional(),"linux-aarch64":Pe.optional(),"linux-x86_64":Pe.optional(),"windows-x86_64":Pe.optional(),"windows-aarch64":Pe.optional()}),uo=M.object({package:M.string(),args:M.array(M.string()).optional(),env:M.record(M.string()).optional()}),lo=M.object({command:M.string(),args:M.array(M.string()).optional(),env:M.record(M.string()).optional()}),fo=M.object({npx:ao.optional(),binary:co.optional(),uvx:uo.optional(),exec:lo.optional()}),po=M.object({id:M.string(),name:M.string(),version:M.string().optional(),description:M.string().optional(),authors:M.array(M.string()).optional(),license:M.string().optional(),icon:M.string().optional(),repository:M.string().optional(),website:M.string().optional(),distribution:fo}),ys=M.object({version:M.string(),agents:M.array(po),extensions:M.array(M.unknown()).optional()}),Je=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(o=>o.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>dn(o)===e);return i?this.applyOverride(i):void 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:t.command??e,args:t.args,env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:mo(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=ys.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await re(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=ys.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await Z(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function mo(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 dn(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 Te(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await cn(o),source:s.has(o.id)?"local":"registry"})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function cn(n){let e=ie();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=nn(n.distribution.binary,e);if(s?.cmd){let r=gt.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await ws(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??dn(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=gt.join(i,"node_modules",".bin",r);if(await ws(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function ws(n){try{return await vs.access(n),!0}catch{return!1}}async function ue(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??dn(n)??r.package,a=t.onInstallProgress;return{command:await ms({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=nn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ie()??"this platform"}.`);let i=t.onInstallProgress,o=await fs({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as wo}from"child_process";import*as wt from"fs";import*as $s from"path";var I={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as O}from"zod";var Is=O.object({protocolVersion:O.number().optional(),clientCapabilities:O.record(O.unknown()).optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional()}),go=O.enum(["full","pending_only","none","after_message"]),bs=O.object({cwd:O.string(),mcpServers:O.array(O.unknown()).optional(),_meta:O.record(O.unknown()).optional()}),Ss=O.object({upstreamSessionId:O.string(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),agentArgs:O.array(O.string()).optional()}),ks=O.object({sessionId:O.string(),historyPolicy:go.default("full"),afterMessageId:O.string().optional(),clientId:O.string().optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional(),_meta:O.record(O.unknown()).optional()});import{z as R}from"zod";var As=R.object({sessionId:R.string()}),xs=R.object({cwd:R.string().optional(),cursor:R.string().optional()}),un=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional()}),ku=R.object({sessionId:R.string(),upstreamSessionId:R.string().optional(),cwd:R.string(),title:R.string().optional(),agentId:R.string().optional(),currentModel:R.string().optional(),currentUsage:un.optional(),importedFromMachine:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),originatingClient:R.object({name:R.string(),version:R.string().optional()}).optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),updatedAt:R.string(),attachedClients:R.number().int().nonnegative(),status:R.enum(["live","cold"]).default("live"),busy:R.boolean().default(!1),awaitingInput:R.boolean().default(!1),_meta:R.record(R.unknown()).optional()}),ho=R.object({sessionId:R.string(),cwd:R.string(),title:R.string().optional(),updatedAt:R.string().optional(),_meta:R.record(R.unknown()).optional()}),Au=R.object({sessions:R.array(ho),nextCursor:R.string().optional()});function ht(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),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)),t}function Cs(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ze(n._meta,ht(n))};return n.title!==void 0&&(e.title=n.title),e}var We="hydra-acp";function Qe(n){if(!n)return{};let e=n[We];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=Ss.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=un.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="live"||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.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}:{}}}return t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),s}function ze(n,e){return{...n??{},[We]:e}}import{z as b}from"zod";var Ms=b.object({sessionId:b.string(),prompt:b.array(b.unknown()),_meta:b.record(b.unknown()).optional()}),yt=b.object({sessionId:b.string()}),Rs=b.object({clientId:b.string(),name:b.string().optional(),version:b.string().optional()}),Pu=b.object({sessionId:b.string(),messageId:b.string(),originator:Rs,prompt:b.array(b.unknown()),position:b.number().int().nonnegative(),queueDepth:b.number().int().positive(),enqueuedAt:b.number()}),Tu=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),_u=b.object({sessionId:b.string(),messageId:b.string(),reason:b.enum(["started","cancelled","abandoned"])}),Es=b.object({sessionId:b.string(),messageId:b.string()}),$u=b.object({cancelled:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Ps=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Ou=b.object({updated:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Ts=b.object({sessionId:b.string(),targetMessageId:b.string(),prompt:b.array(b.unknown()),replaceQueue:b.boolean().optional(),onTargetCompleted:b.enum(["reject","send_anyway"]).optional()}),Fu=b.object({amended:b.boolean(),reason:b.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:b.string().optional()}),Nu=b.object({sessionId:b.string(),cancelledMessageId:b.string(),newMessageId:b.string(),prompt:b.array(b.unknown()),originator:Rs,amendedAt:b.number()});import{z as ge}from"zod";var Bu=ge.object({agentId:ge.string(),version:ge.string(),source:ge.enum(["binary","npm"]),phase:ge.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ge.number().optional(),totalBytes:ge.number().optional(),packageSpec:ge.string().optional()}),_s="hydra-acp/agents/install_progress";function ln(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
1
+ import*as Mi from"fs";import*as ve from"fs/promises";import Bc from"fastify";import Uc from"@fastify/websocket";var Qn="acp.v1";function Vn(n,e){return n.has(Qn)?Qn:!1}import Ci from"pino";import Dc from"pino-roll";import*as Xn from"fs/promises";import{homedir as en}from"os";import{z as v}from"zod";import*as P from"path";import*as Xt from"os";var Ei="HYDRA_ACP_HOME";function Me(n){let e=Xt.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function _(){let n=process.env[Ei];if(n&&n.length>0)return P.resolve(n);if(process.env.VITEST)throw new Error("HYDRA_ACP_HOME is unset under VITEST; vitest.setup.ts must run first");return P.join(Xt.homedir(),".hydra-acp")}var w={home:_,config:()=>P.join(_(),"config.json"),authToken:()=>P.join(_(),"auth-token"),remotes:()=>P.join(_(),"remotes.json"),pidFile:()=>P.join(_(),"daemon.pid"),logFile:()=>P.join(_(),"daemon.log"),currentLogFile:()=>P.join(_(),"current.log"),registryCache:()=>P.join(_(),"registry.json"),agentsDir:()=>P.join(_(),"agents"),agentLogFile:n=>P.join(_(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>P.join(_(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>P.join(_(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>P.join(_(),"sessions"),sessionDir:n=>P.join(_(),"sessions",n),sessionFile:n=>P.join(_(),"sessions",n,"meta.json"),historyFile:n=>P.join(_(),"sessions",n,"history.jsonl"),toolsDir:n=>P.join(_(),"sessions",n,"tools"),toolBlobFile:(n,e)=>P.join(_(),"sessions",n,"tools",e),queueFile:n=>P.join(_(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>P.join(_(),"sessions",".tombstones"),tombstoneAgentDir:n=>P.join(_(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>P.join(_(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>P.join(_(),"extensions"),extensionLogFile:n=>P.join(_(),"extensions",`${n}.log`),extensionPidFile:n=>P.join(_(),"extensions",`${n}.pid`),transformersDir:()=>P.join(_(),"transformers"),transformerLogFile:n=>P.join(_(),"transformers",`${n}.log`),transformerPidFile:n=>P.join(_(),"transformers",`${n}.pid`),transformerState:(n,e)=>P.join(_(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>P.join(_(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>P.join(_(),"prompt-history"),tuiLogFile:()=>P.join(_(),"tui.log"),shimWireLogFile:()=>P.join(_(),"shim-wire.log")};import*as Re from"fs/promises";function ft(){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 Gn(){try{let e=(await Re.readFile(w.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Pi(){let n=await Gn();if(!n)throw new Error(`No service token found at ${w.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Zt(n){await Re.mkdir(w.home(),{recursive:!0}),await Re.writeFile(w.authToken(),n+`
2
+ `,{encoding:"utf8",mode:384})}async function Ti(){let n=await Gn();if(n)return n;let e=ft();return await Zt(e),process.stderr.write(`hydra-acp: initialized ${w.authToken()} with a fresh service token.
3
+ `),e}import*as se from"fs/promises";import*as Yn from"fs";import{randomBytes as _i}from"crypto";async function Z(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
+ `;await $i(n,r,t)}async function $i(n,e,t={}){let s=Oi(n);await se.mkdir(s,{recursive:!0});let r=`${n}.tmp-${process.pid}-${Fi()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await se.writeFile(r,e,i),await se.rename(r,n)}catch(i){throw await se.unlink(r).catch(()=>{}),i}if(t.mode!==void 0)try{Yn.chmodSync(n,t.mode)}catch{}}async function re(n){let e;try{e=await se.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 Oi(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Fi(){return _i(4).toString("hex")}var Zn="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Ni=v.object({cert:v.string(),key:v.string()}),es=55514,Hi=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(es),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:Ni.optional(),sessionIdleTimeoutSeconds:v.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:v.number().int().positive().default(1e4),agentStderrTailBytes:v.number().int().positive().default(4096),publicHost:v.string().optional(),agentSyncIntervalMinutes:v.number().nonnegative().default(60),sessionGcIntervalMinutes:v.number().nonnegative().default(60),sessionGcMaxAgeDays:v.number().positive().default(2)}),ji=v.object({url:v.string().url().default(Zn),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),Bi=v.object({name:v.string().optional(),description:v.string().optional(),command:v.string().optional(),args:v.array(v.string()).optional(),env:v.record(v.string()).optional()}),Ui=v.object({packageSpec:v.string().optional()}),Di=v.object({repaintThrottleMs:v.number().int().nonnegative().default(1e3),maxScrollbackLines:v.number().int().positive().default(1e4),mouse:v.boolean().default(!1),inAppSelection:v.boolean().optional(),selectionClipboard:v.enum(["primary","clipboard","both"]).default("both"),logMaxBytes:v.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:v.number().int().positive().default(32),progressIndicator:v.boolean().default(!0),defaultEnterAction:v.enum(["enqueue","amend"]).default("amend"),showThoughts:v.boolean().default(!0),ambiguousWidth:v.enum(["narrow","wide"]).default("wide"),toolContent:v.enum(["inline","references"]).default("references"),diffContextLines:v.number().int().min(0).default(3),promptHistoryMaxEntries:v.number().int().positive().default(2e3),maxToolItems:v.number().int().nonnegative().default(5),maxPlanItems:v.number().int().nonnegative().default(5),showFileUpdates:v.enum(["none","edit","diff"]).default("edit"),sessionColumns:v.array(v.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional()}),Kn=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Li=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),qi=v.object({command:v.array(v.string()).default([]),args:v.array(v.string()).default([]),env:v.record(v.string()).default({}),enabled:v.boolean().default(!0)}),ts=v.object({daemon:Hi.default({}),registry:ji.default({url:Zn,ttlHours:24,pinned:!1}),agents:v.record(v.string(),Bi).default({}),agentOverrides:v.record(v.string(),Ui).default({}),defaultAgent:v.string().default("opencode"),defaultModels:v.record(v.string(),v.string()).default({}),synopsisAgent:v.string().optional(),synopsisModel:v.string().optional(),synopsisOnClose:v.boolean().default(!1),defaultCwd:v.string().default("~"),compressToolContent:v.boolean().default(!0),sessionListColdLimit:v.number().int().nonnegative().default(20),extensions:v.record(Kn,Li).default({}),transformers:v.record(Kn,qi).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Di.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!1,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"wide",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function ns(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function ss(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function rs(){return await re(w.config())??{}}async function Ji(){let n=await rs(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Xn.access(w.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${w.authToken()} and ${w.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Zt(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await Z(w.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${w.config()} to ${w.authToken()}.
5
+ `)}async function is(){return await Ji(),ts.parse(await rs())}async function zi(n){await Z(w.config(),n,{mode:384})}function Wi(){return ts.parse({})}function Ee(n){return n==="~"||n==="$HOME"?en():n.startsWith("~/")?en()+n.slice(1):n.startsWith("$HOME/")?en()+n.slice(5):n}import*as J from"fs/promises";import{createHash as Qi}from"crypto";import{gzip as Vi,gunzip as Gi}from"zlib";import{promisify as os}from"util";var as=os(Vi),Yi=os(Gi),ds=/^[A-Za-z0-9_-]+$/,Ki=/^[a-f0-9]{64}$/,tn=!0;function cs(n){tn=n}function pt(n,e){return ds.test(n)?e===void 0||Ki.test(e):!1}function mt(n,e){return`${w.toolBlobFile(n,e)}.gz`}async function nn(n,e){if(!pt(n))return null;let t=Qi("sha256").update(e,"utf8").digest("hex"),s=mt(n,t),r=w.toolBlobFile(n,t);for(let a of[s,r])try{return await J.access(a),t}catch{}await J.mkdir(w.toolsDir(n),{recursive:!0});let i=tn?s:r,o=tn?await as(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await J.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function gt(n,e){if(!pt(n,e))return null;try{let t=await J.readFile(mt(n,e));return(await Yi(t)).toString("utf8")}catch{}try{return await J.readFile(w.toolBlobFile(n,e),"utf8")}catch{return null}}async function us(n,e){if(!pt(n,e))return null;try{return await J.readFile(mt(n,e))}catch{}try{let t=await J.readFile(w.toolBlobFile(n,e));return await as(t)}catch{return null}}async function ls(n,e,t){if(!pt(n,e))return;let s=mt(n,e);try{await J.access(s);return}catch{}await J.mkdir(w.toolsDir(n),{recursive:!0}),await J.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function fs(n){ds.test(n)&&await J.rm(w.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as As from"fs/promises";import*as ht from"path";import{z as x}from"zod";import*as ms from"fs";import*as W from"fs/promises";import*as ge from"path";import{spawn as gs}from"child_process";import{Readable as Xi}from"stream";function ie(){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 on(n,e=ie()){if(e)return n[e]}var Pe=n=>{process.stderr.write(n+`
6
+ `)};function an(n){Pe=n??(e=>process.stderr.write(e+`
7
+ `))}async function hs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${ie()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=ie();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentInstallDir(n.agentId,e,n.version),s=ge.resolve(t,n.target.cmd);if(await rn(s))return s;if(await Zi({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await rn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await W.chmod(s,493).catch(()=>{}),s}async function Zi(n){await W.mkdir(ge.dirname(n.installDir),{recursive:!0});let e=await W.mkdtemp(`${n.installDir}.partial-`);try{Pe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await eo({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Pe(`hydra-acp: extracting ${n.agentId}`),Te(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await no(t,e),await W.unlink(t).catch(()=>{});try{await W.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await rn(n.installDir)){await W.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Te(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Pe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Te(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await W.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Te(n,e){if(n)try{n(e)}catch{}}async function eo(n){let e=to(n.url),t=ge.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),i=ms.createWriteStream(t),o=Xi.fromWeb(s.body);Te(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),c=0,f=2e3,u=150;return o.on("data",l=>{a+=l.length;let p=Date.now();p-c>=u&&(c=p,Te(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=f&&(d=p,Pe(ps(n.agentId,a,r)))}),await new Promise((l,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>l()),o.pipe(i)}),Pe(ps(n.agentId,a,r,!0)),Te(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function ps(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let o=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${o} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function to(n){let e=new URL(n);return ge.posix.basename(e.pathname)||"archive"}async function no(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await sn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await so("unzip")){await sn("unzip",["-q",n,"-d",e]);return}await sn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function sn(n,e){return new Promise((t,s)=>{let r=gs(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(i,o)=>{if(i===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${i!==null?`code ${i}`:`signal ${o}`}`))})})}async function so(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=gs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function rn(n){try{return await W.access(n),!0}catch{return!1}}import*as K from"fs/promises";import*as oe from"path";import{spawn as ro}from"child_process";var cn=n=>{process.stderr.write(n+`
8
+ `)};function un(n){cn=n??(e=>process.stderr.write(e+`
9
+ `))}async function ws(n){let e=ie();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=w.agentNpmInstallDir(n.agentId,e,n.version),s=uo(n.packageSpec),r=lo(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=oe.join(t,"node_modules",".bin",n.bin);if(await be(o))return o;if(await be(t)){let u=await ys(i);if(u)return u.binPath}await io({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await ys(i);if(a)return a.binPath;let d=await Is(t,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],f=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/)${f}`)}async function io(n){await K.mkdir(oe.dirname(n.installDir),{recursive:!0});let e=await K.mkdtemp(`${n.installDir}.partial-`);try{cn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),dn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await co({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await K.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await be(n.installDir)){await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),dn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}cn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),dn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await K.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function dn(n,e){if(n)try{n(e)}catch{}}var oo=5,ao=25;function co(n){return vs(n,0)}async function vs(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=ro("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let o="";i.stdout?.on("data",a=>{}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{o=(o+a).slice(-4096)}),i.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),i.on("exit",(a,d)=>{if(a===0){t();return}let c=a!==null?`exit code ${a}`:`signal ${d??"unknown"}`,f=o.trim();s(new Error(f?`npm install ${n.packageSpec} failed (${c})
10
+ stderr: ${f}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<oo)return await new Promise(r=>setTimeout(r,ao*(e+1))),vs(n,e+1);throw t}}function uo(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 lo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function Is(n,e){let t=oe.join(n,"node_modules",e,"package.json");try{let s=await K.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function ys(n){let e=oe.join(n.installDir,"node_modules",".bin"),t=oe.join(e,n.hint);if(await be(t))return{binName:n.hint,binPath:t};let s=await Is(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=oe.join(e,i);if(await be(o))return{binName:i,binPath:o}}else if(r.length>1){for(let i of[n.hint,n.basename])if(r.includes(i)){let o=oe.join(e,i);if(await be(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=oe.join(e,n.basename);if(await be(r))return{binName:n.basename,binPath:r}}}async function be(n){try{return await K.access(n),!0}catch{return!1}}var fo=x.object({package:x.string(),bin:x.string().optional(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),_e=x.object({archive:x.string().url().optional(),cmd:x.string().optional(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),po=x.object({"darwin-aarch64":_e.optional(),"darwin-x86_64":_e.optional(),"linux-aarch64":_e.optional(),"linux-x86_64":_e.optional(),"windows-x86_64":_e.optional(),"windows-aarch64":_e.optional()}),mo=x.object({package:x.string(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),go=x.object({command:x.string(),args:x.array(x.string()).optional(),env:x.record(x.string()).optional()}),ho=x.object({command:x.string().optional(),url:x.string().optional(),description:x.string().optional()}),yo=x.object({npx:fo.optional(),binary:po.optional(),uvx:mo.optional(),exec:go.optional()}),wo=x.object({id:x.string(),name:x.string(),version:x.string().optional(),description:x.string().optional(),authors:x.array(x.string()).optional(),license:x.string().optional(),icon:x.string().optional(),repository:x.string().optional(),website:x.string().optional(),distribution:yo,onboarding:ho.optional()}),bs=x.object({version:x.string(),agents:x.array(wo),extensions:x.array(x.unknown()).optional()}),ze=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(o=>o.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(o=>o.id===e);if(r)return this.applyOverride(r);let i=s.agents.find(o=>ln(o)===e);return i?this.applyOverride(i):void 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:t.command??e,args:t.args,env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:vo(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=bs.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},i=this.options.onFetched;return i&&Promise.resolve().then(()=>i(s)).catch(()=>{}),r}async readDiskCache(){let e=await re(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=bs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await Z(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function vo(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 ln(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 $e(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(o){if(e.length===0)throw o;t={version:"local-only",agents:[]}}let s=new Set(e.map(o=>o.id)),r=[...e,...t.agents.filter(o=>!s.has(o.id))],i=await Promise.all(r.map(async o=>({id:o.id,name:o.name,version:o.version,description:o.description,distributions:Object.keys(o.distribution),installed:await fn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function fn(n){let e=ie();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=on(n.distribution.binary,e);if(s?.cmd){let r=ht.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await Ss(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??ln(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=ht.join(i,"node_modules",".bin",r);if(await Ss(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Ss(n){try{return await As.access(n),!0}catch{return!1}}async function ae(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,i=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...i],env:r.env??{},version:s};let o=r.bin??ln(n)??r.package,a=t.onInstallProgress;return{command:await ws({agentId:n.id,version:s,packageSpec:r.package,bin:o,registry:t.npmRegistry,onProgress:a?c=>a({source:"npm",...c}):void 0}),args:i,env:r.env??{},version:s}}if(n.distribution.binary){let r=on(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ie()??"this platform"}.`);let i=t.onInstallProgress,o=await hs({agentId:n.id,version:s,target:r,onProgress:i?d=>i({source:"binary",...d}):void 0}),a=e.length>0?e:r.args??[];return{command:o,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,i=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...i],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,i=e.length>0?e:r.args??[];return{command:r.command,args:i,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Ao}from"child_process";import*as vt from"fs";import*as Hs 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 F}from"zod";var ks=F.object({protocolVersion:F.number().optional(),clientCapabilities:F.record(F.unknown()).optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional()}),Io=F.enum(["full","pending_only","none","after_message"]),xs=F.object({cwd:F.string(),mcpServers:F.array(F.unknown()).optional(),_meta:F.record(F.unknown()).optional()}),Cs=F.object({upstreamSessionId:F.string(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),agentArgs:F.array(F.string()).optional()}),Ms=F.object({sessionId:F.string(),historyPolicy:Io.default("full"),afterMessageId:F.string().optional(),clientId:F.string().optional(),clientInfo:F.object({name:F.string(),version:F.string().optional()}).optional(),_meta:F.record(F.unknown()).optional()});import{z as R}from"zod";var Rs=R.object({sessionId:R.string()}),Es=R.object({cwd:R.string().optional(),cursor:R.string().optional()}),pn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional()}),Ru=R.object({sessionId:R.string(),upstreamSessionId:R.string().optional(),cwd:R.string(),title:R.string().optional(),agentId:R.string().optional(),currentModel:R.string().optional(),currentUsage:pn.optional(),importedFromMachine:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),originatingClient:R.object({name:R.string(),version:R.string().optional()}).optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),updatedAt:R.string(),attachedClients:R.number().int().nonnegative(),status:R.enum(["live","cold"]).default("live"),busy:R.boolean().default(!1),awaitingInput:R.boolean().default(!1),_meta:R.record(R.unknown()).optional()}),bo=R.object({sessionId:R.string(),cwd:R.string(),title:R.string().optional(),updatedAt:R.string().optional(),_meta:R.record(R.unknown()).optional()}),Eu=R.object({sessions:R.array(bo),nextCursor:R.string().optional()});function yt(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),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)),t}function Ps(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:We(n._meta,yt(n))};return n.title!==void 0&&(e.title=n.title),e}var Qe="hydra-acp";function Ve(n){if(!n)return{};let e=n[Qe];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=Cs.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=pn.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let i of t.availableCommands){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.name!="string")continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,i={};typeof r.queueing=="boolean"&&(i.queueing=r.queueing),typeof r.cancelling=="boolean"&&(i.cancelling=r.cancelling),typeof r.updating=="boolean"&&(i.updating=r.updating),typeof r.amending=="boolean"&&(i.amending=r.amending),typeof r.pipelining=="boolean"&&(i.pipelining=r.pipelining),s.prompt=i}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,i={};typeof r.list=="boolean"&&(i.list=r.list),typeof r.installProgress=="boolean"&&(i.installProgress=r.installProgress),s.agents=i}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let i of t.queue){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i,a=o.originator;if(typeof o.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(o.prompt)||typeof o.position!="number"||typeof o.enqueuedAt!="number")continue;let d={clientId:a.clientId};typeof a.name=="string"&&(d.name=a.name),typeof a.version=="string"&&(d.version=a.version),r.push({messageId:o.messageId,originator:d,prompt:o.prompt,position:o.position,enqueuedAt:o.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let i of t.availableModes){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.id!="string")continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let i of t.availableModels){if(!i||typeof i!="object"||Array.isArray(i))continue;let o=i;if(typeof o.modelId!="string")continue;let a={modelId:o.modelId};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="live"||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.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}:{}}}return t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),s}function We(n,e){return{...n??{},[Qe]:e}}import{z as b}from"zod";var Ts=b.object({sessionId:b.string(),prompt:b.array(b.unknown()),_meta:b.record(b.unknown()).optional()}),wt=b.object({sessionId:b.string()}),_s=b.object({clientId:b.string(),name:b.string().optional(),version:b.string().optional()}),Fu=b.object({sessionId:b.string(),messageId:b.string(),originator:_s,prompt:b.array(b.unknown()),position:b.number().int().nonnegative(),queueDepth:b.number().int().positive(),enqueuedAt:b.number()}),Nu=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Hu=b.object({sessionId:b.string(),messageId:b.string(),reason:b.enum(["started","cancelled","abandoned"])}),$s=b.object({sessionId:b.string(),messageId:b.string()}),ju=b.object({cancelled:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Os=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Bu=b.object({updated:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Fs=b.object({sessionId:b.string(),targetMessageId:b.string(),prompt:b.array(b.unknown()),replaceQueue:b.boolean().optional(),onTargetCompleted:b.enum(["reject","send_anyway"]).optional()}),Uu=b.object({amended:b.boolean(),reason:b.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:b.string().optional()}),Du=b.object({sessionId:b.string(),cancelledMessageId:b.string(),newMessageId:b.string(),prompt:b.array(b.unknown()),originator:_s,amendedAt:b.number()});import{z as he}from"zod";var Ju=he.object({agentId:he.string(),version:he.string(),source:he.enum(["binary","npm"]),phase:he.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:he.number().optional(),totalBytes:he.number().optional(),packageSpec:he.string().optional()}),Ns="hydra-acp/agents/install_progress";function mn(n,e){let t="",s=[],r=[],i=!1,o=a=>{if(!i){i=!0;for(let d of r)d(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let d=t.indexOf(`
11
11
  `);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let f=JSON.parse(c);for(let u of s)u(f)}catch(f){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse ndjson line: ${f.message}`}})}d=t.indexOf(`
12
12
  `)}}),n.on("end",()=>o()),n.on("error",a=>o(a)),e.on("error",a=>o(a)),{async send(a){if(i)throw new Error("stream is closed");let d=JSON.stringify(a)+`
13
- `;await new Promise((c,f)=>{e.write(d,u=>{if(u){f(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as yo}from"nanoid";var fn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},be=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 fn;let s=yo(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code: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 vo=4096,le=class n{agentId;version;cwd;connection;child;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??vo,this.killEscalationMs=e.killEscalationMs??Io,this.logger=e.logger,this.fileLog=bo(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=ln(t.stdout,t.stdin);this.connection=new be(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
13
+ `;await new Promise((c,f)=>{e.write(d,u=>{if(u){f(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as So}from"nanoid";var gn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Se=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 gn;let s=So(),r={jsonrpc:"2.0",id:s,method:e,params:t},i=new Promise((o,a)=>{this.pending.set(s,{resolve:d=>o(d),reject:a}),this.stream.send(r).catch(d=>{this.pending.delete(s),a(d)})});return{id:s,response:i}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code: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 ko=4096,fe=class n{agentId;version;cwd;connection;authMethods;child;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??ko,this.killEscalationMs=e.killEscalationMs??xo,this.logger=e.logger,this.fileLog=Co(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=mn(t.stdout,t.stdin);this.connection=new Se(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let i of r.split(/\r?\n/))i.length>0&&this.logger.info(`[${e.agentId}] ${i}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let i=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
15
15
  `),this.connection.fail(new Error(i))}),t.on("exit",(r,i)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${i} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
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=${i}`);else{let o=`agent ${e.agentId} exited before responding (code=${r} signal=${i})`;this.connection.fail(new Error(this.formatFailure(o))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${i}`)}for(let o of this.exitHandlers)o(r,i)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
17
- stderr: ${t}`:e}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=wo(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}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Ao(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)})}},Io=2e3;function bo(n){try{let e=w.agentLogFile(n);wt.mkdirSync($s.dirname(e),{recursive:!0});let t=wt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Ae from"fs/promises";import*as Rt from"os";import*as nt from"path";import{customAlphabet as $a}from"nanoid";import{customAlphabet as Ls}from"nanoid";import*as Fs from"fs/promises";var So=64*1024*1024,ko=1*1024*1024,_e=64*1024,Ao=6e4,xo=100,Co=1e3,Mo=64*1024,Ro=256*1024,Os=20;function Eo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var vt=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??So,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(ko,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,_e));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),f={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(f.gap=i),this.closed&&r+d>=this.writeCursor&&(f.eof=!0),f}tail(e){let t=Math.max(0,Math.min(e,_e)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,_e)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Ao));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Eo(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??xo,Co)),l=Math.max(1,Math.min(e.maxBytes??Mo,Ro)),p=Math.max(0,Math.min(e.contextBefore??0,Os)),m=Math.max(0,Math.min(e.contextAfter??0,Os)),g=[],h=[],y=[],S=0,C=!1,A=0,F=0,U=(k,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:k,line:P}),D.remaining--,S+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==f&&g.length<u){let D={cursor:k,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let we of D.before)S+=we.line.length}S+=P.length,g.push(D),m>0&&y.push({match:D,remaining:m})}if(p>0)for(h.push({cursor:k,line:P});h.length>p;)h.shift();let q=g.length>=u&&y.length===0,Y=S>=l;return q||Y};for(let k=0;k<o.length;k++){if(o[k]!==10)continue;let P=o.subarray(A,k).toString("utf8"),j=r+A;if(A=k+1,F=A,U(j,P)){C=!0;break}}if(!C&&A<o.length&&this.closed){let k=o.subarray(A).toString("utf8"),P=r+A;U(P,k)&&(C=!0),F=o.length}let G=Math.min(r+F,this.writeCursor),L={matches:g,truncated:C,nextCursor:G,scannedBytes:F};return i>0&&(L.gap=i),this.closed&&G>=this.writeCursor&&(L.eof=!0),L}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Fs.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var It=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"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."}],il=new Map(It.map(n=>[n.verb,n]));function Ns(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function $e(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.some(r=>r.modelId===n))return{kind:"exact",modelId:n};let t=Ns(n),s=e.map(r=>r.modelId).filter(r=>Ns(r)===t);return s.length===1?{kind:"resolved",modelId:s[0],requested:n}:s.length>1?{kind:"ambiguous",requested:n,candidates:s}:{kind:"unknown",requested:n}}function Hs(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 d=n[a];if(d===void 0)continue;let c=pn(d);if(c?.sessionUpdate!=="tool_call_update")continue;let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&(e.set(f,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(f,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(f);u?u.push(...c.content):t.set(f,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=pn(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let f=c.sessionUpdate;if(f==="agent_message_chunk"||f==="agent_thought_chunk"||f==="user_message_chunk"){i&&i.kind===f?To(r,i.outIndex,Po(c.content)):(r.push(d),i={outIndex:r.length-1,kind:f});continue}if(i=null,f==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let l=u!==void 0&&t.has(u)?_o(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!$o(l)&&(l=Oo(l,s.get(u))),r.push(l);continue}if(f==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(f==="prompt_received"||f==="turn_complete")&&(o=null),r.push(d)}return r}function pn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Po(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function To(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function _o(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function $o(n){let t=pn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Oo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ae from"fs/promises";async function Ve(n,e){let t=w.queueFile(n);if(e.length===0){await ae.unlink(t).catch(()=>{});return}await ae.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
19
+ `),this.logger?.warn(`agent ${this.agentId} pid=${this.child.pid} did not exit after ${e}; sending SIGKILL`),this.signalProcessGroup("SIGKILL"),await this.waitForExit(this.killEscalationMs)))}signalProcessGroup(e){let t=this.child.pid;if(t!==void 0)try{process.kill(-t,e)}catch{try{this.child.kill(e)}catch{}}}waitForExit(e){return this.exited?Promise.resolve():new Promise(t=>{let s=setTimeout(()=>{this.child.off("exit",r),t()},e),r=()=>{clearTimeout(s),t()};this.child.once("exit",r)})}},xo=2e3;function Co(n){try{let e=w.agentLogFile(n);vt.mkdirSync(Hs.dirname(e),{recursive:!0});let t=vt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as xe from"fs/promises";import*as Pt from"os";import*as st from"path";import{customAlphabet as ja}from"nanoid";import{customAlphabet as Ws}from"nanoid";import*as Bs from"fs/promises";var Mo=64*1024*1024,Ro=1*1024*1024,Oe=64*1024,Eo=6e4,Po=100,To=1e3,_o=64*1024,$o=256*1024,js=20;function Oo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var It=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??Mo,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Ro,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,Oe));if(s===0){let u={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(u.eof=!0),u}let r=e,i=0,o=this.oldestAvailable;r<o&&(i=o-r,r=o);let a=this.writeCursor-r;if(a<=0){let u={bytes:Buffer.alloc(0),nextCursor:r};return i>0&&(u.gap=i),this.closed&&(u.eof=!0),u}let d=Math.min(a,s),f={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(f.gap=i),this.closed&&r+d>=this.writeCursor&&(f.eof=!0),f}tail(e){let t=Math.max(0,Math.min(e,Oe)),s=this.oldestAvailable,r=this.writeCursor-t,i=Math.max(s,r),o=r<s;return{bytes:this.sliceFromRing(i,this.writeCursor-i),startCursor:i,endCursor:this.writeCursor,truncated:o}}head(e){let t=Math.max(0,Math.min(e,Oe)),s=this.oldestAvailable,r=s>0,i=s,o=Math.min(this.writeCursor,i+t);return{bytes:this.sliceFromRing(i,o-i),startCursor:i,endCursor:o,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Eo));return s===0?Promise.resolve("timeout"):new Promise(r=>{let i={resolve:o=>{i.timer!==void 0&&(clearTimeout(i.timer),i.timer=void 0),r(o)},timer:setTimeout(()=>{let o=this.waiters.indexOf(i);o>=0&&this.waiters.splice(o,1),i.timer=void 0,r("timeout")},s)};this.waiters.push(i)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,i=0;s!==void 0&&s<t&&(i=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let o=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,d=e.caseInsensitive===!0?"i":"",c=a?new RegExp(e.pattern,d):new RegExp(Oo(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Po,To)),l=Math.max(1,Math.min(e.maxBytes??_o,$o)),p=Math.max(0,Math.min(e.contextBefore??0,js)),m=Math.max(0,Math.min(e.contextAfter??0,js)),g=[],h=[],y=[],S=0,M=!1,k=0,N=0,U=(A,T)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:A,line:T}),D.remaining--,S+=T.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(T)!==f&&g.length<u){let D={cursor:A,line:T};if(p>0&&h.length>0){D.before=h.slice();for(let Ie of D.before)S+=Ie.line.length}S+=T.length,g.push(D),m>0&&y.push({match:D,remaining:m})}if(p>0)for(h.push({cursor:A,line:T});h.length>p;)h.shift();let q=g.length>=u&&y.length===0,Y=S>=l;return q||Y};for(let A=0;A<o.length;A++){if(o[A]!==10)continue;let T=o.subarray(k,A).toString("utf8"),j=r+k;if(k=A+1,N=k,U(j,T)){M=!0;break}}if(!M&&k<o.length&&this.closed){let A=o.subarray(k).toString("utf8"),T=r+k;U(T,A)&&(M=!0),N=o.length}let G=Math.min(r+N,this.writeCursor),L={matches:g,truncated:M,nextCursor:G,scannedBytes:N};return i>0&&(L.gap=i),this.closed&&G>=this.writeCursor&&(L.eof=!0),L}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let i=t-this.currentCapacityBytes;e.copy(this.storage,0,i,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,i=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+i),i<t&&this.storage.copy(s,i,0,t-i),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let i=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Bs.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var bt=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent>",description:"Swap the agent backing this session, preserving context"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"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."}],ul=new Map(bt.map(n=>[n.verb,n]));function Us(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function Fe(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.some(r=>r.modelId===n))return{kind:"exact",modelId:n};let t=Us(n),s=e.map(r=>r.modelId).filter(r=>Us(r)===t);return s.length===1?{kind:"resolved",modelId:s[0],requested:n}:s.length>1?{kind:"ambiguous",requested:n,candidates:s}:{kind:"unknown",requested:n}}function Ds(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 d=n[a];if(d===void 0)continue;let c=hn(d);if(c?.sessionUpdate!=="tool_call_update")continue;let f=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(f!==void 0&&(e.set(f,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(f,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(f);u?u.push(...c.content):t.set(f,[...c.content])}}let r=[],i=null,o=null;for(let a=0;a<n.length;a++){let d=n[a];if(d===void 0)continue;let c=hn(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let f=c.sessionUpdate;if(f==="agent_message_chunk"||f==="agent_thought_chunk"||f==="user_message_chunk"){i&&i.kind===f?No(r,i.outIndex,Fo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:f});continue}if(i=null,f==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let l=u!==void 0&&t.has(u)?Ho(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!jo(l)&&(l=Bo(l,s.get(u))),r.push(l);continue}if(f==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(f==="prompt_received"||f==="turn_complete")&&(o=null),r.push(d)}return r}function hn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Fo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function No(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},i=r.update??{},o=i.content??{},a=typeof o.text=="string"?o.text:"";n[e]={...s,params:{...r,update:{...i,content:{...o,text:a+t}}}}}function Ho(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function jo(n){let t=hn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Bo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as de from"fs/promises";async function Ge(n,e){let t=w.queueFile(n);if(e.length===0){await de.unlink(t).catch(()=>{});return}await de.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
20
20
  `)+`
21
- `;await ae.writeFile(t,s,"utf8")}async function js(n){let e=w.queueFile(n),t;try{t=await ae.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
22
- `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function Bs(n){let e=w.queueFile(n);await ae.unlink(e).catch(()=>{})}import*as Ws from"fs/promises";var qs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Js=Ls(qs,16),Us=Ls(qs,16),fe="hydra_session_";function Oe(){return`m_${Js()}`}function zs(n){return n.startsWith(fe)?n.slice(fe.length):n}var Fo=1e3,mn=300*1e3,No=64,Se=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;currentModel;currentMode;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},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){this.sessionId=e.sessionId??`${fe}${Js()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.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.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Fo,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){qo(this.internalPromptCapture,t);return}this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>this.handlePermissionRequest(t)),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){let r=e,i=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(t.has(c.name)||!c.intercepts.has("response:session/update"))continue;let f=`t_${Us()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return;if(l==="processing"){let p=d,m=i,g=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:c.name}),this.runResponseChain(m,new Set([...g,c.name]),p+1).then(()=>h()).catch(()=>h()))},mn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:g,side:"response"})});return}t.add(c.name)}let o=Jo(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Lo(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let 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.inFlightPermissions.size>0}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)}}attach(e,t,s={}){if(this.closed)throw X(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw X(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=o=>t.raw?o:Hs(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?hn(r,t.afterMessageId):-1;return o<0?{entries:[...i,...s(r)],appliedPolicy:"full"}:{entries:[...i,...s(r.slice(o+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let t of this.inFlightPermissions)t.addClient(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 X(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw X(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=Oe();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Qe((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Fe(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)}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Oe()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>No;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw X(new Error("client not attached"),I.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(f=>f.messageId===r&&f.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),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,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=Oe(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];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}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=Oe(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw X(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,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let f=`t_${Us()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:f,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return i==="notification"?void 0:u?.payload??gn(e);if(l==="processing"){let p=a,m=o,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:d.name}),this.forwardRequest(e,m,new Set([...g,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:gn(e))))},mn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:m,chainIdx:p,originatedBy:g,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,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):mn,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:gn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}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(!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=Fe((e??{}).prompt),r=yn(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=Ne(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=Ne(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.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(o.id==="mode"){let a=Ge(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.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 o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=Ne(o.options);if(d.length>0){let c=Ge(o.options),f=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),u=o.name,l=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:m,options:f})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let t={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=t;for(let s of this.usageHandlers)try{s(t)}catch{}}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(Bo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(Uo(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(",")}]`),Do(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)return;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()}applyModeChange(e){let t=e.trim();if(!t)return;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()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:t,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${t} ${s.verb}`:`hydra ${t}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),t.startsWith("hydra-acp-")){let a=t.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,f={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(f.description=s.description),e.push(f)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(It.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=I.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=It.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:l}of this.extensionCommands.list())u.has(l)||(c.push(l),u.add(l))}let f=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw f.code=I.InvalidParams,f}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(m=>m.verb===o)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},f=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 u,l=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",d),g=await Promise.race([m,f]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return l=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=g}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!l&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
21
+ `;await de.writeFile(t,s,"utf8")}async function Ls(n){let e=w.queueFile(n),t;try{t=await de.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
22
+ `))if(r.trim())try{let i=JSON.parse(r);i&&typeof i.messageId=="string"&&Array.isArray(i.prompt)&&typeof i.enqueuedAt=="number"&&s.push(i)}catch{}return s}async function qs(n){let e=w.queueFile(n);await de.unlink(e).catch(()=>{})}import*as Ys from"fs/promises";var Qs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Vs=Ws(Qs,16),Js=Ws(Qs,16),pe="hydra_session_";function Ne(){return`m_${Vs()}`}function Gs(n){return n.startsWith(pe)?n.slice(pe.length):n}var Uo=1e3,yn=300*1e3,Do=64,Ae=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;currentModel;currentMode;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;inFlightPermissions=new Set;internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimer;idleEventTimeoutMs;lastRecordedAt;spawnReplacementAgent;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},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){this.sessionId=e.sessionId??`${pe}${Vs()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.spawnReplacementAgent=e.spawnReplacementAgent,this.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.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Uo,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){Vo(this.internalPromptCapture,t);return}this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>this.handlePermissionRequest(t)),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){let r=e,i=this.injectCumulativeCost(e);for(let d=s;d<this.transformChain.length;d++){let c=this.transformChain[d];if(t.has(c.name)||!c.intercepts.has("response:session/update"))continue;let f=`t_${Js()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:f,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return;if(l==="processing"){let p=d,m=i,g=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:c.name}),this.runResponseChain(m,new Set([...g,c.name]),p+1).then(()=>h()).catch(()=>h()))},yn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:m,chainIdx:p,originatedBy:g,side:"response"})});return}t.add(c.name)}let o=Go(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=Qo(i);if(a!==null){this.setAgentAdvertisedModes(a);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(r)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let 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.inFlightPermissions.size>0}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)}}attach(e,t,s={}){if(this.closed)throw X(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw X(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=o=>t.raw?o:Ds(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?vn(r,t.afterMessageId):-1;return o<0?{entries:[...i,...s(r)],appliedPolicy:"full"}:{entries:[...i,...s(r.slice(o+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(r)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let i={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(i.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(i.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let i=this.currentUsage,o={sessionUpdate:"usage_update"};if(typeof i.used=="number"&&(o.used=i.used),typeof i.size=="number"&&(o.size=i.size),typeof i.costAmount=="number"||typeof i.costCurrency=="string"){let a={};typeof i.costAmount=="number"&&(a.amount=i.costAmount),typeof i.costCurrency=="string"&&(a.currency=i.costCurrency),o.cost=a}Object.keys(o).length>1&&e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}return e}replayPendingPermissions(e){for(let t of this.inFlightPermissions)t.addClient(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 X(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw X(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=Ne();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ve((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let o of this.interactiveHandlers)try{o(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=He(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)}broadcastTurnComplete(e,t,s,r){let i=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,o={sessionUpdate:"turn_complete",messageId:Ne()};i!==void 0&&(o.stopReason=i);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(o._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&i!==void 0&&this.recordTerminal(s,i),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:o},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>Do;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),i={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(i._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",i)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw X(new Error("client not attached"),I.SessionNotFound);let{targetMessageId:r,prompt:i,replaceQueue:o,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,i,r,o);let d=this.promptQueue.find(f=>f.messageId===r&&f.kind==="user");if(d&&d.kind==="user"&&!d.cancelled)return d.prompt=i,this.broadcastQueueUpdated(r,i),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,i)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let i=Ne(),o={clientId:e.clientId};if(e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version),r){let d=[];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}d.push(c)}this.promptQueue=d}let a={kind:"user",messageId:i,originator:o,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:i},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:i}}enqueueAmendmentAsFollowUp(e,t){let s=Ne(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let i={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(i),this.persistRewrite(),this.broadcastQueueAdded(i),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw X(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,i="request"){let o=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let d=this.transformChain[a];if(s.has(d.name))continue;let c=`request:${e}`;if(!d.intercepts.has(c))continue;let f=`t_${Js()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:f,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let l=u?.action??"continue";if(l==="stop")return i==="notification"?void 0:u?.payload??wn(e);if(l==="processing"){let p=a,m=o,g=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(f)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:f,transformerName:d.name}),this.forwardRequest(e,m,new Set([...g,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:wn(e))))},yn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:m,chainIdx:p,originatedBy:g,side:"request",tailKind:i})})}s.add(d.name)}if(i==="notification"){await this.agent.connection.notify(e,o);return}return this.agent.connection.request(e,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):yn,i=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else{let o=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,o).then(s.resolve).catch(()=>s.resolve(o==="notification"?void 0:wn(s.method)))}},r);return typeof i.unref=="function"&&i.unref(),s.timer=i,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),i=r>=0?r+1:0,o=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,o,i);return}return this.forwardRequest(t,s,o,i)}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(!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=He((e??{}).prompt),r=In(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=je(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let i=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(i===void 0)return!0;let o=i.trim();if(!o||o===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(o)}`),this.currentModel=o;for(let a of this.modelHandlers)try{a(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(o.id==="model"){let a=je(o.options);a.length>0&&this.setAgentAdvertisedModels(a);let d=o.currentValue;if(typeof d=="string"){let c=d.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(o.id==="mode"){let a=Ye(o.options);a.length>0&&this.setAgentAdvertisedModes(a);let d=o.currentValue;if(typeof d=="string"){let c=d.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 o.id=="string"&&o.id.trim()){let a=o.id.trim(),d=je(o.options);if(d.length>0){let c=Ye(o.options),f=c.length>0?c.map(h=>({value:h.id,name:h.name??h.id})):d.map(h=>({value:h.modelId,name:h.name??h.modelId})),u=o.name,l=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,m=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:m,options:f})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;if(!e)return;this.cumulativeCost+=e;let t={...this._currentUsage??{},cumulativeCost:this.cumulativeCost,costAmount:void 0};this._currentUsage=t;for(let s of this.usageHandlers)try{s(t)}catch{}}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(Jo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(zo(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(",")}]`),Wo(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)return;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()}applyModeChange(e){let t=e.trim();if(!t)return;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()}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(o=>({value:o.modelId,name:o.name??o.modelId,...o.description!==void 0?{description:o.description}:{}})),i=this.currentModel&&r.some(o=>o.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:i,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(o=>({value:o.id,name:o.name??o.id,...o.description!==void 0?{description:o.description}:{}})),i=this.currentMode&&r.some(o=>o.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:i,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let o=this.buildConfigOptions().find(a=>a.id==="agent");return o?{...t,update:{...s,configOptions:[...r,o]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}];if(this.extensionCommands)for(let{name:t,command:s}of this.extensionCommands.list()){let r=s.verb?`hydra ${t} ${s.verb}`:`hydra ${t}`,o={name:s.argsHint?`${r} ${s.argsHint}`:r};if(s.description&&(o.description=s.description),e.push(o),t.startsWith("hydra-acp-")){let a=t.slice(10);if(a.length>0){let d=s.verb?`hydra ${a} ${s.verb}`:`hydra ${a}`,f={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(f.description=s.description),e.push(f)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),i=r?.[1]??"",o=(r?.[2]??"").trim();if(i==="")return{stopReason:"end_turn"};let a=t!==void 0;if(bt.some(u=>u.verb===i))switch(i){case"title":return a?this.runTitleCommandInline(o):this.runTitleCommand(o);case"agent":return a?this.runAgentCommandInline(o):this.runAgentCommand(o);case"config":return this.handleConfigCommand(`/config ${o}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();default:{let u=new Error(`no dispatcher for /hydra verb ${i}`);throw u.code=I.InternalError,u}}if(this.extensionCommands?.has(i))return a?this.runExtensionCommandInline(i,o,t):this.runExtensionCommand(i,o);let d=`hydra-acp-${i}`;if(this.extensionCommands?.has(d))return a?this.runExtensionCommandInline(d,o,t):this.runExtensionCommand(d,o);let c=bt.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:l}of this.extensionCommands.list())u.has(l)||(c.push(l),u.add(l))}let f=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw f.code=I.InvalidParams,f}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(m=>m.verb===o)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${m||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},f=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 u,l=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",d),g=await Promise.race([m,f]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return l=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=g}catch(m){return this.emitExtensionReply(`${e} ${o}: ${m.message}`)}finally{s!==void 0&&!l&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
23
23
  ${e}
24
24
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let i=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),o=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",d=r.title?` ${r.title}`:"";return`\`${i}\` ${r.cwd}${o}${a}${d}`});e=`Sessions (${t.length}):
25
25
  ${s.join(`
@@ -32,7 +32,7 @@ ${s}
32
32
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let i=this.agentAdvertisedModels,o=this.currentModel,a;if(i.length===0)a=o?`Current model: ${o}`:"_(no models advertised yet)_";else{let d=o?i.some(f=>f.modelId===o):!0,c=i.map(f=>{let u=f.modelId===o?"\u25B6 ":" ",l=f.name&&f.name!==f.modelId?` ${f.name}`:"";return`${u}${f.modelId}${l}`});!d&&o&&c.unshift(`\u25B6 ${o}`),a=c.join(`
33
33
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
34
34
  ${a}
35
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=$e(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(a=>a.modelId).join(`
35
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=Fe(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(a=>a.modelId).join(`
36
36
  `),o=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:`"${t}" is not an available model`;return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
37
37
  ${o}.
38
38
  Available models:
@@ -42,7 +42,7 @@ Available models:
42
42
  ${o}
43
43
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(i=>i.id).join(", ");throw X(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 a=this.buildConfigOptions();if(a.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
44
44
  _(no config options advertised yet)_
45
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>Ds(c));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
45
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let d=a.map(c=>zs(c));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
46
46
  ${d.join(`
47
47
 
48
48
  `)}
@@ -52,17 +52,17 @@ ${d.join(`
52
52
  Available options:
53
53
  ${a}
54
54
  `},_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:`
55
- ${Ds(o)}
55
+ ${zs(o)}
56
56
  `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};if(!o.options.some(a=>a.value===r)){let a=o.options.map(d=>d.value).join(`
57
57
  `);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
58
58
  "${r}" is not a valid value for "${s}".
59
59
  Valid values:
60
60
  ${a}
61
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:r}),{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:[]};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)throw X(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw X(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw X(new Error("agent switching not configured for this session"),I.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(a)}catch{}return{stopReason:"end_turn"}}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw X(new Error("agent restart not configured for this session"),I.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw X(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.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let m=Fe(u.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let g=u.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(p==="tool_call"||p==="tool_call_update"){let m=u.status,g=u.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let i=[],o;for(let c of s)o&&o.speaker===c.speaker?o.text+=c.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:c.speaker,text:c.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=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,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
62
- `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new vt(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??_e,_e)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Bs(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>Ws.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let 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.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,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(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!jo(e,r),o=i?zo(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw X(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=Wo(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:l};this.inFlightPermissions.add(c);let f=this.sessionId,u=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function l(p){if(a)return;let m=p.connection.request("session/request_permission",s);d.push({client:p}),m.then(g=>{u(()=>{let h=Qo({toolCallId:r,result:g,resolver:p});for(let y of d)y.client.clientId!==p.clientId&&y.client.connection.notify("session/update",{sessionId:f,update:h}).catch(()=>{});i(g)})}).catch(g=>{u(()=>o(g))})}for(let p of t)l(p)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Oe(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ve(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}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Fe(e.prompt).replace(/\s+$/,""),s=!t.includes(`
63
- `)&&t.startsWith("/")?t.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(t):s==="/model"?i=await this.handleModelCommand(t):i=await this.handleSlashCommand(t,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function X(n,e){return n.code=e,n}var Ho=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function jo(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Ho.has(s)}function Bo(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 Uo(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 Do(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 Ne(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Ge(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Lo(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function qo(n,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&n.chunks.push(r.text)}function Jo(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function zo(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:Oe()}}}function hn(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 Wo(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 Qo(n){let e=Vo(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=Go(n.resolver),t}function Vo(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function Go(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 Fe(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function gn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Ds(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
61
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:r}),{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:[]};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)throw X(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw X(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw X(new Error("agent switching not configured for this session"),I.InternalError);let t=this.spawnReplacementAgent,s=this.agentId,r=await this.buildSwitchTranscript(s),i=await t({agentId:e,cwd:this.cwd,agentArgs:this.agentArgs});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let d of this.agentChangeHandlers)try{d(a)}catch{}return{stopReason:"end_turn"}}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw X(new Error("agent restart not configured for this session"),I.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw X(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.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let c of r){if(c.method!=="session/update")continue;let u=(c.params??{}).update;if(!u||u._meta?.["hydra-acp"]?.synthetic)continue;let p=u.sessionUpdate;if(p==="prompt_received"){let m=He(u.prompt);m&&s.push({speaker:"user",text:m})}else if(p==="agent_message_chunk"){let g=u.content?.text;g&&s.push({speaker:`agent: ${e}`,text:g})}else if(p==="tool_call"||p==="tool_call_update"){let m=u.status,g=u.title;(m==="completed"||m==="failed")&&s.push({speaker:"tool",text:`${g??"?"} ${m}`})}}if(s.length===0)return"";let i=[],o;for(let c of s)o&&o.speaker===c.speaker?o.text+=c.text:(o&&i.push(`<${o.speaker}>: ${o.text.trim()}`),o={speaker:c.speaker,text:c.text});o&&i.push(`<${o.speaker}>: ${o.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,d=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,d,"","--- begin transcript ---",...i,"--- end transcript ---"].join(`
62
+ `)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t}}}}),this.broadcastConfigOptions()}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let i=new It(r);this.streamBuffer=i,this.streamFilePath=s;let o={capacityBytes:i.capacity};return s!==void 0&&(o.filePath=s),e.fileCapBytes!==void 0&&(o.fileCapBytes=e.fileCapBytes),o}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),i=Math.max(0,Math.min(t??Oe,Oe)),o=r.read(e,i);if(o.bytes.length===0&&o.eof!==!0&&s!==void 0&&s>0){let d=await r.waitForData(o.nextCursor,s);(d==="data"||d==="eof")&&(o=r.read(o.nextCursor,i))}let a={bytes:o.bytes.toString("base64"),nextCursor:o.nextCursor};return o.gap!==void 0&&(a.gap=o.gap),o.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let r of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(r,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let t=this.promptQueue;this.promptQueue=[];for(let r of t){r.cancelled=!0,r.kind==="user"&&this.broadcastQueueRemoved(r.messageId,"abandoned");try{r.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{});let s=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>qs(s).catch(()=>{}));for(let r of this.clients.values())r.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let r=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,r.close(),i!==void 0&&r.drainFileWrites().then(()=>Ys.unlink(i).catch(()=>{}))}for(let r of this.closeHandlers)r(e)}get lastActivityAt(){return this.lastRecordedAt}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.inFlightPermissions.size>0||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let 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.cancelIdleEventTimer()}scheduleIdleEvent(){this.closed||this.idleEventTimeoutMs<=0||this.transformChain.length===0||(this.idleEventTimer&&clearTimeout(this.idleEventTimer),this.idleEventTimer=setTimeout(()=>{this.idleEventTimer=void 0,this.notifyChain("session.idle",{})},this.idleEventTimeoutMs),typeof this.idleEventTimer.unref=="function"&&this.idleEventTimer.unref())}cancelIdleEventTimer(){this.idleEventTimer&&(clearTimeout(this.idleEventTimer),this.idleEventTimer=void 0)}notifyChain(e,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(t.sessionId===this.upstreamSessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),i=!qo(e,r),o=i?Yo(e,r):r;if(i){let a={method:e,params:o,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let d=this.historyStore;d.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,d.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let d of this.broadcastHandlers)try{d(a)}catch{}this.scheduleIdleCheck(),this.scheduleIdleEvent()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,o).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw X(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=Ko(s);return new Promise((i,o)=>{let a=!1,d=[],c={addClient:l};this.inFlightPermissions.add(c);let f=this.sessionId,u=p=>{a||(a=!0,this.inFlightPermissions.delete(c),p())};function l(p){if(a)return;let m=p.connection.request("session/request_permission",s);d.push({client:p}),m.then(g=>{u(()=>{let h=Xo({toolCallId:r,result:g,resolver:p});for(let y of d)y.client.clientId!==p.clientId&&y.client.connection.notify("session/update",{sessionId:f,update:h}).catch(()=>{});i(g)})}).catch(g=>{u(()=>o(g))})}for(let p of t)l(p)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ne(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],i={clientId:e.clientId};e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version);let o=this.parseQueuePosition(t);return new Promise((a,d)=>{let c={kind:"user",messageId:s,originator:i,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:d},f=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:f}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ge(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}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=He(e.prompt).replace(/\s+$/,""),s=!t.includes(`
63
+ `)&&t.startsWith("/")?t.split(/\s+/)[0]:"";if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"){let i;return s==="/sessions"?i=await this.handleSessionsCommand():s==="/help"?i=await this.handleHelpCommand():s==="/mode"?i=await this.handleModeCommand(t):s==="/model"?i=await this.handleModelCommand(t):i=await this.handleSlashCommand(t,e.messageId),this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}let r;try{r=await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:e.prompt})}catch(i){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}return this.closed||this.broadcastTurnComplete(e.clientId,r,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),r}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function X(n,e){return n.code=e,n}var Lo=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function qo(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Lo.has(s)}function Jo(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 zo(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 Wo(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 je(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={modelId:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Ye(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let i={id:r};typeof s.name=="string"&&s.name.length>0&&(i.name=s.name),typeof s.description=="string"&&s.description.length>0&&(i.description=s.description),e.push(i)}return e}function Qo(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.id!="string"||o.id.length===0)continue;let a={id:o.id};typeof o.name=="string"&&(a.name=o.name),typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function Vo(n,e){let s=(e??{}).update??{};if(s.sessionUpdate!=="agent_message_chunk")return;let r=s.content??{};typeof r.text=="string"&&n.chunks.push(r.text)}function Go(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(typeof o.name!="string"||o.name.length===0)continue;let a={name:o.name};typeof o.description=="string"&&(a.description=o.description),r.push(a)}return r}function Yo(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:Ne()}}}function vn(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 Ko(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 Xo(n){let e=Zo(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=ea(n.resolver),t}function Zo(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let i=e.reason;return typeof i=="string"&&(s.reason=i),s}function ea(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 He(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function wn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function zs(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let i=r.value===n.currentValue?"\u25B6":"\xB7",o=r.name&&r.name!==r.value,a=o?r.value.padEnd(t):r.value;return o?` ${i} ${a} ${r.name}`:` ${i} ${a}`});return`${e}
64
64
  ${s.join(`
65
- `)}`}function yn(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 He from"fs/promises";import*as bl from"path";import{customAlphabet as Xo}from"nanoid";import{z as x}from"zod";import{z as ee}from"zod";var Ye=ee.object({goal:ee.string().optional(),outcome:ee.string().optional(),files_touched:ee.array(ee.string()).optional(),tools_used:ee.array(ee.string()).optional(),rejected_approaches:ee.array(ee.string()).optional(),open_threads:ee.array(ee.string()).optional()}),Yo=200,wn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
65
+ `)}`}function In(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 Be from"fs/promises";import*as Cl from"path";import{customAlphabet as sa}from"nanoid";import{z as C}from"zod";import{z as ee}from"zod";var Ke=ee.object({goal:ee.string().optional(),outcome:ee.string().optional(),files_touched:ee.array(ee.string()).optional(),tools_used:ee.array(ee.string()).optional(),rejected_approaches:ee.array(ee.string()).optional(),open_threads:ee.array(ee.string()).optional()}),ta=200,bn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
66
66
  {
67
67
  "title": "short summary, max 80 chars",
68
68
  "synopsis": {
@@ -72,41 +72,41 @@ ${s.join(`
72
72
  "open_threads": ["work started but not finished"]
73
73
  }
74
74
  }
75
- Use empty arrays/strings where a field doesn't apply.`;function Vs(n){let e=n.trim();if(e.length===0)return;let t=Qs(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(t=Qs(e.slice(i,o+1)),t===void 0))return}if(t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,Yo))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Ye.safeParse(s.synopsis);i.success&&Ko(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Qs(n){try{return JSON.parse(n)}catch{return}}function Ko(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}var Zo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ea=Xo(Zo,16),ta="hydra_lineage_";function Ke(){return`${ta}${ea()}`}var In=x.object({name:x.string(),description:x.string().optional()}),bn=x.object({id:x.string(),name:x.string().optional(),description:x.string().optional()}),na=x.object({modelId:x.string(),name:x.string().optional(),description:x.string().optional()}),Sn=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional(),cumulativeCost:x.number().optional()}),kn=x.object({name:x.string(),version:x.string().optional()}),sa=x.object({version:x.literal(1),sessionId:x.string(),lineageId:x.string().optional(),upstreamSessionId:x.string(),importedFromSessionId:x.string().optional(),importedFromUpstreamSessionId:x.string().optional(),importedFromMachine:x.string().optional(),agentId:x.string(),cwd:x.string(),title:x.string().optional(),synopsis:Ye.optional(),summarizedThroughEntry:x.number().int().nonnegative().optional(),agentArgs:x.array(x.string()).optional(),currentModel:x.string().optional(),currentMode:x.string().optional(),currentUsage:Sn.optional(),agentCommands:x.array(In).optional(),agentModes:x.array(bn).optional(),agentModels:x.array(na).optional(),pendingHistorySync:x.boolean().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:kn.optional(),interactive:x.boolean().optional(),priority:x.number().int().nonnegative().optional(),createdAt:x.string(),updatedAt:x.string()}),vn=/^[A-Za-z0-9_-]+$/;function ra(n){if(!vn.test(n))throw new Error(`unsafe session id: ${n}`)}var bt=class{async write(e){ra(e.sessionId);let t={version:1,...e};await Z(w.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!vn.test(e))return;let t=await re(w.sessionFile(e));if(t!==void 0)try{return sa.parse(t)}catch{return}}async delete(e){if(vn.test(e)){try{await He.unlink(w.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await He.rmdir(w.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 He.readdir(w.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 An(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,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as pe from"fs/promises";import{z as de}from"zod";var ia=de.object({version:de.literal(1),agentId:de.string(),upstreamSessionId:de.string(),deletedAt:de.string(),upstreamUpdatedAt:de.string().optional(),cwd:de.string().optional(),title:de.string().optional(),reason:de.enum(["user","expired"]).optional(),interactive:de.boolean().optional()}),St=class{async add(e){let t={version:1,...e};await Z(w.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await pe.access(w.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=w.tombstoneFile(e,t),r=await re(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 ia.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await pe.unlink(w.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await pe.rmdir(w.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 pe.readdir(w.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await pe.readdir(w.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Gs(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as ir from"fs/promises";import{fileURLToPath as oa}from"url";import*as Xe from"path";import*as kt from"fs";function aa(){try{let n=Xe.dirname(oa(import.meta.url));for(let e=0;e<8;e+=1){let t=Xe.join(n,"package.json");if(kt.existsSync(t)){let r=JSON.parse(kt.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=Xe.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var V=aa(),At="hydra-acp-cat";var Ys=`[older history truncated]
76
- `,da=["file_path","path","command","pattern","query"];function Ks(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received"){i();let f=fa(d.prompt).trim();f.length>0&&s.push(`User: ${f}`)}else if(c==="agent_message_chunk"){let f=pa(d.content);f.length>0&&(r+=f)}else c==="tool_call"?(i(),s.push(ca(d))):c==="turn_complete"&&i()}return i(),ga(s.join(`
77
- `),t)}function ca(n){let e=ua(n),t=la(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function ua(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function la(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of da){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${ma(r,200)}`)}return t}function fa(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 pa(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function ma(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function ga(n,e){if(n.length<=e)return n;let t=n.split(`
78
- `);for(;t.length>0;){let s=Ys+t.join(`
79
- `);if(s.length<=e)return s;t.shift()}return Ys}var ha=12e4;async function Zs(n){let e=n.timeoutMs??ha,t,s,r=!1;try{let i=(async()=>{t=le.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let o=await t.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:V}}),a=await t.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`);return}if(n.modelId){let m=wa(a);if(m.size===0||m.has(n.modelId))try{await t.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 c=[];t.connection.onNotification("session/update",m=>{let g=ya(m);g.length>0&&c.push(g)});let f=Ks(n.history,{maxChars:n.maxTranscriptChars}),u=f.length>0?`${f}
75
+ Use empty arrays/strings where a field doesn't apply.`;function Xs(n){let e=n.trim();if(e.length===0)return;let t=Ks(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(t=Ks(e.slice(i,o+1)),t===void 0))return}if(t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let i=s.title.trim();i.length>0&&(r.title=i.slice(0,ta))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Ke.safeParse(s.synopsis);i.success&&na(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function Ks(n){try{return JSON.parse(n)}catch{return}}function na(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}var ra="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ia=sa(ra,16),oa="hydra_lineage_";function Xe(){return`${oa}${ia()}`}var An=C.object({name:C.string(),description:C.string().optional()}),kn=C.object({id:C.string(),name:C.string().optional(),description:C.string().optional()}),aa=C.object({modelId:C.string(),name:C.string().optional(),description:C.string().optional()}),xn=C.object({used:C.number().optional(),size:C.number().optional(),costAmount:C.number().optional(),costCurrency:C.string().optional(),cumulativeCost:C.number().optional()}),Cn=C.object({name:C.string(),version:C.string().optional()}),da=C.object({version:C.literal(1),sessionId:C.string(),lineageId:C.string().optional(),upstreamSessionId:C.string(),importedFromSessionId:C.string().optional(),importedFromUpstreamSessionId:C.string().optional(),importedFromMachine:C.string().optional(),agentId:C.string(),cwd:C.string(),title:C.string().optional(),synopsis:Ke.optional(),summarizedThroughEntry:C.number().int().nonnegative().optional(),agentArgs:C.array(C.string()).optional(),currentModel:C.string().optional(),currentMode:C.string().optional(),currentUsage:xn.optional(),agentCommands:C.array(An).optional(),agentModes:C.array(kn).optional(),agentModels:C.array(aa).optional(),pendingHistorySync:C.boolean().optional(),parentSessionId:C.string().optional(),forkedFromSessionId:C.string().optional(),forkedFromMessageId:C.string().optional(),originatingClient:Cn.optional(),interactive:C.boolean().optional(),priority:C.number().int().nonnegative().optional(),createdAt:C.string(),updatedAt:C.string()}),Sn=/^[A-Za-z0-9_-]+$/;function ca(n){if(!Sn.test(n))throw new Error(`unsafe session id: ${n}`)}var St=class{async write(e){ca(e.sessionId);let t={version:1,...e};await Z(w.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Sn.test(e))return;let t=await re(w.sessionFile(e));if(t!==void 0)try{return da.parse(t)}catch{return}}async delete(e){if(Sn.test(e)){try{await Be.unlink(w.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Be.rmdir(w.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 Be.readdir(w.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 Mn(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,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as me from"fs/promises";import{z as ce}from"zod";var ua=ce.object({version:ce.literal(1),agentId:ce.string(),upstreamSessionId:ce.string(),deletedAt:ce.string(),upstreamUpdatedAt:ce.string().optional(),cwd:ce.string().optional(),title:ce.string().optional(),reason:ce.enum(["user","expired"]).optional(),interactive:ce.boolean().optional()}),At=class{async add(e){let t={version:1,...e};await Z(w.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await me.access(w.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=w.tombstoneFile(e,t),r=await re(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 ua.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await me.unlink(w.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await me.rmdir(w.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 me.readdir(w.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(i))}return s}async listForAgent(e){let t;try{t=await me.readdir(w.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let i;try{i=decodeURIComponent(r)}catch{continue}let o=await this.read(e,i);o&&s.push(o)}return s}};function Zs(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as cr from"fs/promises";import{fileURLToPath as la}from"url";import*as Ze from"path";import*as kt from"fs";function fa(){try{let n=Ze.dirname(la(import.meta.url));for(let e=0;e<8;e+=1){let t=Ze.join(n,"package.json");if(kt.existsSync(t)){let r=JSON.parse(kt.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=Ze.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var Q=fa(),xt="hydra-acp-cat";var er=`[older history truncated]
76
+ `,pa=["file_path","path","command","pattern","query"];function tr(n,e={}){let t=e.maxChars??4e5,s=[],r="",i=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let o of n){if(o.method!=="session/update")continue;let d=o.params?.update;if(!d||typeof d.sessionUpdate!="string")continue;let c=d.sessionUpdate;if(c==="prompt_received"){i();let f=ya(d.prompt).trim();f.length>0&&s.push(`User: ${f}`)}else if(c==="agent_message_chunk"){let f=wa(d.content);f.length>0&&(r+=f)}else c==="tool_call"?(i(),s.push(ma(d))):c==="turn_complete"&&i()}return i(),Ia(s.join(`
77
+ `),t)}function ma(n){let e=ga(n),t=ha(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function ga(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function ha(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of pa){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${va(r,200)}`)}return t}function ya(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 wa(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function va(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Ia(n,e){if(n.length<=e)return n;let t=n.split(`
78
+ `);for(;t.length>0;){let s=er+t.join(`
79
+ `);if(s.length<=e)return s;t.shift()}return er}var ba=12e4;async function sr(n){let e=n.timeoutMs??ba,t,s,r=!1;try{let i=(async()=>{t=fe.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let o=await t.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:Q}}),a=await t.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=a.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`);return}if(n.modelId){let m=Aa(a);if(m.size===0||m.has(n.modelId))try{await t.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 c=[];t.connection.onNotification("session/update",m=>{let g=Sa(m);g.length>0&&c.push(g)});let f=tr(n.history,{maxChars:n.maxTranscriptChars}),u=f.length>0?`${f}
80
80
 
81
- ${wn}`:wn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let l=c.join(""),p=Vs(l);return p||n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse as snapshot JSON (replyLen=${l.length} preview=${JSON.stringify(l.slice(0,200))})`),p})();return await new Promise((o,a)=>{s=setTimeout(()=>{r=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${e}ms`),o(void 0)},e),s.unref?.(),i.then(d=>{s&&clearTimeout(s),r||o(d)},d=>{s&&clearTimeout(s),r||a(d)})})}catch(i){n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${i.message}`);return}finally{s&&clearTimeout(s),t&&await t.kill().catch(()=>{})}}function ya(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 wa(n){let e=new Set;Xs(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Xs(e,t.availableModels),e}function Xs(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 va(n){let e=new Map;for(let t of rr(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 nr(n){return va(n).map(e=>e.name)}function Ia(n){let e=new Map;for(let t of rr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function sr(n){return Ia(n).map(e=>e.path)}function rr(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:er(i),paths:new Set},e.set(d,c)):c.toolName=er(i);for(let f of tr(i.rawInput,i.locations))c.paths.add(f);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of tr(i.rawInput,i.locations))a.paths.add(d)}return e}function er(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function tr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var ba=2,xt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??ba}opts;queued=new Set;inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.queued.has(e)||this.inflight.has(e)||(this.queued.add(e),this.drain())}size(){return{queued:this.queued.size,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued.clear(),await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&this.queued.size>0;){let e=this.queued.values().next().value;if(!e)return;this.queued.delete(e);let t=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,t)}}async runOne(e){try{let t=await this.opts.store.read(e);if(!t){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=t.summarizedThroughEntry;if(r!==void 0&&s.length<=r){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${s.length})`);return}let i=this.opts.synopsisAgent??t.agentId,o=await this.opts.registry.getAgent(i);if(!o){this.opts.logger?.warn(`synopsis: agent ${i} not in registry for session ${e}; skipping`);return}let a=await ue(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await ir.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let f=await Zs({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!f){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}f.title&&await this.opts.persistTitle(e,f.title);let u=Sa(f.synopsis,s);u&&ka(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${Aa(u)}`)):f.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(t){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${t.message}`)}}};function Sa(n,e){let t=sr(e),s=nr(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 ka(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 Aa(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 Q from"fs/promises";function or(n){return n==="summary"?"summary":"inline"}var xn=256;function ar(n,e){return e!=="summary"?n:n.map(xa)}function xa(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(dr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=Cn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function Ca(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function dr(n){if(Ca(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=Cn(e.text)),typeof e.content=="string"?t.content=Cn(e.content):e.content&&typeof e.content=="object"&&(t.content=dr(e.content)),t}function Cn(n){if(typeof n=="string"&&n.length>xn){let e=n.length-xn;return`${n.slice(0,xn)}\u2026[+${e} chars omitted from summary export]`}return n}var Ma=2048;function cr(n){let e=new Set,t=s=>{if(ur(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 ur(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Ra(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 En(n,e){if(!Ra(n))return n;let t=n.params,s=t.update,r=await Mn(s,e);return{...n,params:{...t,update:r}}}async function Mn(n,e){if(typeof n=="string"){if(n.length<=Ma)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 Mn(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Mn(r,e);return t}return n}async function lr(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Rn(t,e);return s===t?n:{...n,params:s}}async function Rn(n,e){if(ur(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Rn(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await Rn(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var Ze=/^[A-Za-z0-9_-]+$/,Ea=1e3,Ct=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Ea}async append(e,t){if(Ze.test(e))return this.enqueue(e,async()=>{await Q.mkdir(w.sessionDir(e),{recursive:!0});let s=await En(t,i=>Zt(e,i)),r=JSON.stringify(s)+`
82
- `;await Q.appendFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(Ze.test(e))return this.enqueue(e,async()=>{await Q.mkdir(w.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await En(i,o=>Zt(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
81
+ ${bn}`:bn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let l=c.join(""),p=Xs(l);return p||n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse as snapshot JSON (replyLen=${l.length} preview=${JSON.stringify(l.slice(0,200))})`),p})();return await new Promise((o,a)=>{s=setTimeout(()=>{r=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${e}ms`),o(void 0)},e),s.unref?.(),i.then(d=>{s&&clearTimeout(s),r||o(d)},d=>{s&&clearTimeout(s),r||a(d)})})}catch(i){n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${i.message}`);return}finally{s&&clearTimeout(s),t&&await t.kill().catch(()=>{})}}function Sa(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 Aa(n){let e=new Set;nr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&nr(e,t.availableModels),e}function nr(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 ka(n){let e=new Map;for(let t of dr(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 or(n){return ka(n).map(e=>e.name)}function xa(n){let e=new Map;for(let t of dr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([o,a])=>({name:o,count:a})).sort((o,a)=>a.count-o.count||o.name.localeCompare(a.name)),i=r.reduce((o,a)=>o+a.count,0);return{path:t,count:i,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function ar(n){return xa(n).map(e=>e.path)}function dr(n){let e=new Map,t=0;for(let s of n){let i=s.params?.update;if(!i)continue;let o=i.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")continue;if(o==="tool_call"){let d=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:`__synth_${t++}`,c=e.get(d);c===void 0?(c={toolName:rr(i),paths:new Set},e.set(d,c)):c.toolName=rr(i);for(let f of ir(i.rawInput,i.locations))c.paths.add(f);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of ir(i.rawInput,i.locations))a.paths.add(d)}return e}function rr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function ir(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let i of r)if(i&&typeof i=="object"){let o=i.file_path;typeof o=="string"&&t.add(o)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Ca=2,Ct=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Ca}opts;queued=new Set;inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.queued.has(e)||this.inflight.has(e)||(this.queued.add(e),this.drain())}size(){return{queued:this.queued.size,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;this.queued.size>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(i=>{setTimeout(i,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(i=>{setTimeout(i,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued.clear(),await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&this.queued.size>0;){let e=this.queued.values().next().value;if(!e)return;this.queued.delete(e);let t=this.runOne(e).finally(()=>{this.inflight.delete(e),this.drain()});this.inflight.set(e,t)}}async runOne(e){try{let t=await this.opts.store.read(e);if(!t){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let s=await this.opts.histories.load(e),r=t.summarizedThroughEntry;if(r!==void 0&&s.length<=r){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${s.length})`);return}let i=this.opts.synopsisAgent??t.agentId,o=await this.opts.registry.getAgent(i);if(!o){this.opts.logger?.warn(`synopsis: agent ${i} not in registry for session ${e}; skipping`);return}let a=await ae(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await cr.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${i} historyLen=${s.length} model=${JSON.stringify(d??"(default)")} cwd=${c}`);let f=await sr({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!f){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}f.title&&await this.opts.persistTitle(e,f.title);let u=Ma(f.synopsis,s);u&&Ra(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${Ea(u)}`)):f.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(t){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${t.message}`)}}};function Ma(n,e){let t=ar(e),s=or(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 Ra(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 Ea(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 V from"fs/promises";function ur(n){return n==="summary"?"summary":"inline"}var Rn=256;function lr(n,e){return e!=="summary"?n:n.map(Pa)}function Pa(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let i={...r};Array.isArray(r.content)&&(i.content=r.content.map(fr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=En(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function Ta(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function fr(n){if(Ta(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=En(e.text)),typeof e.content=="string"?t.content=En(e.content):e.content&&typeof e.content=="object"&&(t.content=fr(e.content)),t}function En(n){if(typeof n=="string"&&n.length>Rn){let e=n.length-Rn;return`${n.slice(0,Rn)}\u2026[+${e} chars omitted from summary export]`}return n}var _a=2048;function pr(n){let e=new Set,t=s=>{if(mr(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 mr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function $a(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 _n(n,e){if(!$a(n))return n;let t=n.params,s=t.update,r=await Pn(s,e);return{...n,params:{...t,update:r}}}async function Pn(n,e){if(typeof n=="string"){if(n.length<=_a)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 Pn(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Pn(r,e);return t}return n}async function gr(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Tn(t,e);return s===t?n:{...n,params:s}}async function Tn(n,e){if(mr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Tn(r,e);i!==r&&(t=!0),s.push(i)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,i]of Object.entries(n)){let o=await Tn(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var et=/^[A-Za-z0-9_-]+$/,Oa=1e3,Mt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Oa}async append(e,t){if(et.test(e))return this.enqueue(e,async()=>{await V.mkdir(w.sessionDir(e),{recursive:!0});let s=await _n(t,i=>nn(e,i)),r=JSON.stringify(s)+`
82
+ `;await V.appendFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(et.test(e))return this.enqueue(e,async()=>{await V.mkdir(w.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await _n(i,o=>nn(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
83
83
  `)+`
84
- `;await Q.writeFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(Ze.test(e))return this.enqueue(e,async()=>{let s;try{s=await Q.readFile(w.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
85
- `).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await Q.writeFile(w.historyFile(e),i.join(`
84
+ `;await V.writeFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(et.test(e))return this.enqueue(e,async()=>{let s;try{s=await V.readFile(w.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
85
+ `).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await V.writeFile(w.historyFile(e),i.join(`
86
86
  `)+`
87
- `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!Ze.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Q.readFile(w.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
88
- `)){if(u.length===0)continue;let l;try{l=JSON.parse(u)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let p=l;typeof p.method=="string"&&typeof p.recordedAt=="number"&&o.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=o.length>this.maxEntries?o.slice(-this.maxEntries):o;if(!s)return a;let d=new Map,c=async u=>{let l=d.get(u);if(l!==void 0)return l;let p=await mt(e,u);return d.set(u,p),p},f=[];for(let u of a)f.push(await lr(u,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(Ze.test(e))return this.enqueue(e,async()=>{try{await Q.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await ds(e);try{await Q.rmdir(w.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};import{promises as fr}from"fs";import*as pr from"path";async function mr(n,e){await fr.mkdir(pr.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await fr.writeFile(n,t.length>0?t.join(`
87
+ `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!et.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await V.readFile(w.historyFile(e),"utf8")}catch(u){if(u.code==="ENOENT")return[];throw u}let o=[];for(let u of i.split(`
88
+ `)){if(u.length===0)continue;let l;try{l=JSON.parse(u)}catch{continue}if(!l||typeof l!="object"||Array.isArray(l))continue;let p=l;typeof p.method=="string"&&typeof p.recordedAt=="number"&&o.push({method:p.method,params:p.params,recordedAt:p.recordedAt})}let a=o.length>this.maxEntries?o.slice(-this.maxEntries):o;if(!s)return a;let d=new Map,c=async u=>{let l=d.get(u);if(l!==void 0)return l;let p=await gt(e,u);return d.set(u,p),p},f=[];for(let u of a)f.push(await gr(u,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(et.test(e))return this.enqueue(e,async()=>{try{await V.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await fs(e);try{await V.rmdir(w.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),i=r.catch(()=>{});return this.writeQueues.set(e,i),i.finally(()=>{this.writeQueues.get(e)===i&&this.writeQueues.delete(e)}),r}};import{promises as hr}from"fs";import*as yr from"path";async function wr(n,e){await hr.mkdir(yr.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await hr.writeFile(n,t.length>0?t.join(`
89
89
  `)+`
90
- `:"")}import{z as _}from"zod";var Pa=_.object({method:_.string(),params:_.unknown(),recordedAt:_.number()}),Ta=_.object({sessionId:_.string(),lineageId:_.string(),upstreamSessionId:_.string().optional(),agentId:_.string(),cwd:_.string(),title:_.string().optional(),synopsis:Ye.optional(),summarizedThroughEntry:_.number().int().nonnegative().optional(),currentModel:_.string().optional(),currentMode:_.string().optional(),currentUsage:Sn.optional(),agentCommands:_.array(In).optional(),agentModes:_.array(bn).optional(),interactive:_.boolean().optional(),originatingClient:kn.optional(),priority:_.number().int().nonnegative().optional(),createdAt:_.string(),updatedAt:_.string()}),_a=_.object({version:_.literal(1),exportedAt:_.string(),exportedFrom:_.object({hydraVersion:_.string(),machine:_.string(),hydraHost:_.string().optional()}),session:Ta,history:_.array(Pa),promptHistory:_.array(_.string()).optional(),toolBlobs:_.record(_.string()).optional()});function et(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 gr(n){return _a.parse(n)}var hr=900*1e3,Oa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Mt=$a(Oa,16),st=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>le.spawn(i)),this.store=s??new bt,this.tombstones=r.tombstones??new St,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Ct({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.synopsisOnClose=r.synopsisOnClose??!1,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~",this.synopsisCoordinator=new xt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,persistTitle:async(i,o)=>{let a=this.get(i);if(a){await a.retitle(o);return}await this.persistTitle(i,o)},persistSynopsis:(i,o,a)=>this.persistSynopsis(i,o,a),logger:this.logger,npmRegistry:this.npmRegistry}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;synopsisOnClose;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;agentCatalog=[];async refreshAgentCatalog(){try{let{agents:e}=await Te(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.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress});if(e.transformChain&&e.transformChain.length>0){let r={...t.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Mt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}t.agentCapabilities=r}let s=new Se({cwd:e.cwd,agentId:e.agentId,agent:t.agent,upstreamSessionId:t.upstreamSessionId,agentMeta:t.agentMeta,agentCapabilities:t.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:t.initialModel,currentMode:t.initialMode,agentModes:t.initialModes,agentModels:t.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=I.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let 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 ue(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r}),o;try{o=(await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:V}})).agentCapabilities}catch(g){throw await i.kill().catch(()=>{}),g}let a;try{let g=ja(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...g&&{_meta:g}})}catch(g){return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
91
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=br(a??{}),c=e.agentModes??wr(Ir(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(g=>g.id))}`);let f=await Sr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=yr(a??{}),l=wr(vr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await kr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let g=i.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 Se({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId)});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,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Sr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await kr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Se({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:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Ae.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:qe(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=I.AgentNotInstalled,p}let s=await ue(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Rt.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:V}})}catch(p){throw await r.kill().catch(()=>{}),p}if((i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let f=w.sessionsDir(),u=[],l=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(d.has(m)){l+=1;continue}if(Fa(p.cwd,f)){l+=1;continue}let g=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(g){if(!Gs(g,p.updatedAt)){l+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}d.add(m);let h=`${fe}${Mt()}`,y=new Date().toISOString(),S=p.updatedAt??y,C={sessionId:h,lineageId:Ke(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:S,updatedAt:S};p.title!==void 0&&(C.title=p.title);let A=An(C);await this.store.write(A),u.push({version:1,...A})}return{synced:u,skipped:l}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await ue(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let o=(await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:V}})).agentCapabilities,a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=yr(a),f=vr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let m=$e(u,f),g=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,d,u,g)&&(c=u);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(r,d,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=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=Ir(a),p=br(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),i}}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=je({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}e.firstPromptSeeded&&this.synopsisOnClose&&this.synopsisCoordinator.schedule(e.sessionId)}),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:xr(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(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Na(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 mt(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:Ha(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}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Fe(r.update.prompt),o=yn(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(fe))return;let t=fe+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,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await tt(t.sessionId),d=je({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,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await tt(s.sessionId),i=je(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>tt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=je({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let m=l.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>tt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=je(u,l.hasContent);if(!r(p))continue;let m=l.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((f,u)=>f.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Ke(),f={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Ar(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of cr(o)){let f=await os(e,c);f&&(d[c]=f.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=I.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${fe}${Mt()}`;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 m=new Error(`source session not found: ${e}`);throw m.code=I.SessionNotFound,m}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let g=new Error(`agent ${r} not found in registry`);throw g.code=I.AgentNotInstalled,g}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=hn(o,t.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw m.code=I.InvalidParams,m}d=t.forkAt}else{let m=Ua(o);m?(a=m.index,d=m.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await Ar(e),u={...s,lineageId:Ke(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},...i?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=et({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:V,machine:Rt.hostname()}),p=`${fe}${Mt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d}),{sessionId:p,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await as(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Ae.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await mr(w.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await tt(e),r=je(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await js(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<hr),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${hr/1e3}s)`),await Ve(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Ve(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Fa(n,e){if(typeof n!="string"||n.length===0)return!1;let t=nt.resolve(n),s=nt.resolve(e);return t===s||t.startsWith(s+nt.sep)}function Na(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return An({sessionId:n.sessionId,lineageId:e?.lineageId??Ke(),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:xr(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,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,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function xr(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 Ha(n){return n?{...n}:void 0}function ja(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Et(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Ba(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function yr(n){return Et(n,{nestedKey:"models",configId:"model",fromObject:e=>ce(e.currentModelId)??ce(e.currentModel)??ce(e.modelId)??ce(e.model),fromConfig:e=>ce(e.currentValue)})}function ce(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Ba(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 wr(n){return n.length>0?n:void 0}function vr(n){return Et(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ne(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ne(e.options);return t.length>0?t:void 0}})??[]}function Ir(n){return Et(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Ge(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Ge(e.options);return t.length>0?t:void 0}})??[]}function br(n){return Et(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ce(e.currentModeId)??ce(e.currentMode)??ce(e.modeId)??ce(e.mode),fromConfig:e=>ce(e.currentValue)})}async function Sr(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function kr(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}function Ua(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 Ar(n){try{let e=await Ae.readFile(w.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
92
- `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function tt(n){try{let e=await Ae.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function je(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===At?!1:e?!0:void 0}import{spawn as Da}from"child_process";import*as Ue from"fs";import*as he from"fs/promises";import*as Cr from"path";var Pt=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var La=1e3,qa=6e4,Pn=3e3,Be=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??La,this.restartCapMs=r.restartCapMs??qa;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await he.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},Pn);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw rt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw rt(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw rt(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 rt(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw rt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},Pn);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 Pt(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await he.readdir(this.adapter.paths.dir())}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.endsWith(".pid"))continue;let s=Cr.join(this.adapter.paths.dir(),t),r;try{let i=await he.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Tn(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Pn;for(;Date.now()<i&&Tn(r);)await new Promise(o=>setTimeout(o,50));if(Tn(r))try{process.kill(r,"SIGKILL")}catch{}}await he.unlink(s).catch(()=>{})}}spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Ue.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
90
+ `:"")}import{z as O}from"zod";var Fa=O.object({method:O.string(),params:O.unknown(),recordedAt:O.number()}),Na=O.object({sessionId:O.string(),lineageId:O.string(),upstreamSessionId:O.string().optional(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),synopsis:Ke.optional(),summarizedThroughEntry:O.number().int().nonnegative().optional(),currentModel:O.string().optional(),currentMode:O.string().optional(),currentUsage:xn.optional(),agentCommands:O.array(An).optional(),agentModes:O.array(kn).optional(),interactive:O.boolean().optional(),originatingClient:Cn.optional(),priority:O.number().int().nonnegative().optional(),createdAt:O.string(),updatedAt:O.string()}),Ha=O.object({version:O.literal(1),exportedAt:O.string(),exportedFrom:O.object({hydraVersion:O.string(),machine:O.string(),hydraHost:O.string().optional()}),session:Na,history:O.array(Fa),promptHistory:O.array(O.string()).optional(),toolBlobs:O.record(O.string()).optional()});function tt(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 vr(n){return Ha.parse(n)}var Ir=900*1e3,Ba="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Rt=ja(Ba,16),rt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>fe.spawn(i)),this.store=s??new St,this.tombstones=r.tombstones??new At,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Mt({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.synopsisOnClose=r.synopsisOnClose??!1,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~",this.synopsisCoordinator=new Ct({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,persistTitle:async(i,o)=>{let a=this.get(i);if(a){await a.retitle(o);return}await this.persistTitle(i,o)},persistSynopsis:(i,o,a)=>this.persistSynopsis(i,o,a),logger:this.logger,npmRegistry:this.npmRegistry}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;synopsisOnClose;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;agentCatalog=[];async refreshAgentCatalog(){try{let{agents:e}=await $e(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.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress});if(e.transformChain&&e.transformChain.length>0){let r={...t.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let o=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Rt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:r});o.action==="stop"&&o.payload&&(r=o.payload)}catch{}t.agentCapabilities=r}let s=new Ae({cwd:e.cwd,agentId:e.agentId,agent:t.agent,upstreamSessionId:t.upstreamSessionId,agentMeta:t.agentMeta,agentCapabilities:t.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:r=>this.bootstrapAgent({...r,mcpServers:[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:t.initialModel,currentMode:t.initialMode,agentModes:t.initialModes,agentModels:t.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(s.sessionId)});return await this.attachManagerHooks(s),s}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let i=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw i.code=I.AlreadyAttached,i}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let 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 ae(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r}),o;try{let g=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}});o=g.agentCapabilities,i.authMethods=Et(g.authMethods)}catch(g){throw await i.kill().catch(()=>{}),ke(g,i)}let a;try{let g=qa(e.agentId,e.currentModel);a=await i.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 i.kill().catch(()=>{}),ke(g,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
91
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=xr(a??{}),c=e.agentModes??Sr(kr(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(g=>g.id))}`);let f=await Cr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(f)} for sessionId=${e.hydraSessionId}`);let u=br(a??{}),l=Sr(Ar(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(l?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Mr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let g=i.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 Ae({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:f,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:l,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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId)});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,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Cr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Mr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new Ae({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:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:i,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:o,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,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await xe.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:Ee(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let p=new Error(`agent ${e} not found in registry`);throw p.code=I.AgentNotInstalled,p}let s=await ae(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Pt.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}})}catch(p){throw await r.kill().catch(()=>{}),ke(p,r)}if(r.authMethods=Et(i.authMethods),(i.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(p){throw await r.kill().catch(()=>{}),p}await r.kill().catch(()=>{});let d=new Set;for(let p of this.sessions.values())d.add(`${p.agentId}::${p.upstreamSessionId}`);let c=await this.store.list().catch(()=>[]);for(let p of c)d.add(`${p.agentId}::${p.upstreamSessionId}`);let f=w.sessionsDir(),u=[],l=0;for(let p of a){let m=`${e}::${p.sessionId}`;if(d.has(m)){l+=1;continue}if(Ua(p.cwd,f)){l+=1;continue}let g=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(g){if(!Zs(g,p.updatedAt)){l+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}d.add(m);let h=`${pe}${Rt()}`,y=new Date().toISOString(),S=p.updatedAt??y,M={sessionId:h,lineageId:Xe(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:S,updatedAt:S};p.title!==void 0&&(M.title=p.title);let k=Mn(M);await this.store.write(k),u.push({version:1,...k})}return{synced:u,skipped:l}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let f={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(f.title=c.title),typeof c.updatedAt=="string"&&(f.updatedAt=c.updatedAt),t.push(f)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await ae(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}}),o=i.agentCapabilities;r.authMethods=Et(i.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),d=a.sessionId;if(typeof d!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let c=br(a),f=Ar(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let m=Fe(u,f),g=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,d,u,g)&&(c=u);else if(m.kind==="resolved")(m.modelId===c||await this.applySeedModel(r,d,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=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=kr(a),p=xr(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:f.length>0?f:void 0,initialModes:l.length>0?l:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),ke(i,r)}}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 d=new Error(`agent ${e} not found in registry`);throw d.code=I.AgentNotInstalled,d}let i=await ae(r,[],{npmRegistry:this.npmRegistry}),o=t??Ee(this.defaultCwd),a=this.spawner({agentId:e,cwd:o,plan:i});try{let d=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:Q}});a.authMethods=Et(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),ke(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}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 s=Ue({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0);this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...s!==void 0?{interactive:s}:{}}).catch(()=>{})}this.store.delete(e.sessionId).catch(()=>{}),this.histories.delete(e.sessionId).catch(()=>{});return}e.firstPromptSeeded&&this.synopsisOnClose&&this.synopsisCoordinator.schedule(e.sessionId)}),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:Er(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(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Da(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 gt(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:La(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}}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=He(r.update.prompt),o=In(i,200);if(o)return o}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,i=e.get(s);i||(i=new Set,e.set(s,i)),i.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(pe))return;let t=pe+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,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"live",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await nt(t.sessionId),d=Ue({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,originatingClient:t.originatingClient,interactive:d,priority:t.priority,updatedAt:c,attachedClients:t.attachedCount,status:"live",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await nt(s.sessionId),i=Ue(s,r.hasContent),o=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,originatingClient:s.originatingClient,interactive:i,priority:s.priority,updatedAt:o,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let i=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:i}),i.catch(()=>{let o=this.listCache.get(t);o&&o.promise===i&&this.listCache.delete(t)}),i}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=f=>e.includeNonInteractive?!0:f===!0,i=[...this.sessions.values()].filter(f=>!e.cwd||f.cwd===e.cwd),o=await Promise.all(i.map(f=>nt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Ue({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let m=l.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(f=>{throw this.logger?.warn(`session list: store.list() failed: ${f?.message??String(f)}`),f})).filter(f=>!s.has(f.sessionId)&&(!e.cwd||f.cwd===e.cwd)),c=await Promise.all(d.map(f=>nt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Ue(u,l.hasContent);if(!r(p))continue;let m=l.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((f,u)=>f.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=Xe(),f={...s,lineageId:c};await this.enqueueMetaWrite(e,async()=>{let u=await this.store.read(e);u&&(u.lineageId||await this.store.write({...u,lineageId:c}))}).catch(()=>{}),r=f}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await Rr(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of pr(o)){let f=await us(e,c);f&&(d[c]=f.toString("base64"))}return{record:r,history:o,promptHistory:a,toolBlobs:d}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let o=new Error(`bundle already imported as ${s.sessionId}`);throw o.code=I.BundleAlreadyImported,o.existingSessionId=s.sessionId,o}let i=this.sessions.get(s.sessionId);return i&&await i.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${pe}${Rt()}`;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 m=new Error(`source session not found: ${e}`);throw m.code=I.SessionNotFound,m}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let g=new Error(`agent ${r} not found in registry`);throw g.code=I.AgentNotInstalled,g}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=vn(o,t.forkAt),a<0){let m=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw m.code=I.InvalidParams,m}d=t.forkAt}else{let m=za(o);m?(a=m.index,d=m.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await Rr(e),u={...s,lineageId:Xe(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},...i?{currentModel:void 0,currentMode:void 0,currentUsage:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=tt({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:Q,machine:Pt.hostname()}),p=`${pe}${Rt()}`;return await this.writeImportedRecord({sessionId:p,bundle:l,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:d}),{sessionId:p,forkedFromSessionId:e,forkedAt:d}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[i,o]of Object.entries(e.bundle.toolBlobs))await ls(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await xe.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await wr(w.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e){let t=await this.store.read(e);if(!t)return!1;if(t.upstreamSessionId){let s=await nt(e),r=Ue(t,s.hasContent);await this.tombstones.add({agentId:t.agentId,upstreamSessionId:t.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:t.updatedAt,cwd:t.cwd,title:t.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,...t,updatedAt:new Date().toISOString()};for(let o of s)delete i[o];await this.store.write(i)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),i=r.catch(()=>{});return this.metaWriteQueues.set(e,i),i.finally(()=>{this.metaWriteQueues.get(e)===i&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Ls(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ir),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ir/1e3}s)`),await Ge(t.sessionId,i).catch(()=>{})),i.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${i.length} entr${i.length===1?"y":"ies"}`),await Ge(t.sessionId,[]).catch(()=>{});continue}try{let d=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${i.length} prompt(s)`),d.replayPersistedQueue(i)}catch(d){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${d.message}`)}}}};function Ua(n,e){if(typeof n!="string"||n.length===0)return!1;let t=st.resolve(n),s=st.resolve(e);return t===s||t.startsWith(s+st.sep)}function Da(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(f=>f.description!==void 0?{name:f.name,description:f.description}:{name:f.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(f=>{let u={id:f.id};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(f=>{let u={modelId:f.modelId};return f.name!==void 0&&(u.name=f.name),f.description!==void 0&&(u.description=f.description),u}):void 0)??e?.agentModels;return Mn({sessionId:n.sessionId,lineageId:e?.lineageId??Xe(),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:Er(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:o,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,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Er(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 La(n){return n?{...n}:void 0}function qa(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Tt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let o=e.fromObject(s);if(o!==void 0)return o}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[o,a]of Object.entries(r))if(o!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let d=e.fromObject(a);if(d!==void 0)return d}}let i=Ja(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function br(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>ue(e.currentModelId)??ue(e.currentModel)??ue(e.modelId)??ue(e.model),fromConfig:e=>ue(e.currentValue)})}function ke(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:{},i=s(r._meta)?r._meta:{},o=s(i["hydra-acp"])?i["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",d=new Error(a);return d.code=I.AuthRequired,d.data={...r,_meta:{...i,"hydra-acp":{...o,authMethods:e.authMethods??[],agentId:e.agentId}}},d}function Et(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0;e.push({id:s.id,description:r,...i&&{type:i}})}return e.length>0?e:void 0}function ue(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Ja(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 Sr(n){return n.length>0?n:void 0}function Ar(n){return Tt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=je(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=je(e.options);return t.length>0?t:void 0}})??[]}function kr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Ye(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Ye(e.options);return t.length>0?t:void 0}})??[]}function xr(n){return Tt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>ue(e.currentModeId)??ue(e.currentMode)??ue(e.modeId)??ue(e.mode),fromConfig:e=>ue(e.currentValue)})}async function Cr(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:i,logger:o}=n;if(!s)return r;if(s===r)return s;if(i&&i.length>0&&!i.some(a=>a.id===s)){let a=i.map(d=>d.id).join(", ");return o?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return o?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),o?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return o?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Mr(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:i}=n;if(!s)return r;if(s===r)return s;try{return i?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),i?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(o){return i?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${o.message}); session will use ${JSON.stringify(r)}`),r}}function za(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 Rr(n){try{let e=await xe.readFile(w.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
92
+ `))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function nt(n){try{let e=await xe.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ue(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===xt?!1:e?!0:void 0}import{spawn as Wa}from"child_process";import*as Le from"fs";import*as we from"fs/promises";import*as Pr from"path";var _t=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let o=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=o,{tripped:o}}let r=this.now();this.recentExits.push(r);let i=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<i;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let o=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${o}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Qa=1e3,Va=6e4,$n=3e3,De=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??Qa,this.restartCapMs=r.restartCapMs??Va;for(let i of e)this.entries.set(i.name,this.makeEntry(i))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await we.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();for(let e of this.entries.values())e.config.enabled&&this.spawn(e,0)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},$n);s.on("exit",()=>{clearTimeout(i),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw it(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw it(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw it(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw it(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw it(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(i=>{e.exitWaiters.push(i)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},$n);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 _t(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await we.readdir(this.adapter.paths.dir())}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.endsWith(".pid"))continue;let s=Pr.join(this.adapter.paths.dir(),t),r;try{let i=await we.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&On(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+$n;for(;Date.now()<i&&On(r);)await new Promise(o=>setTimeout(o,50));if(On(r))try{process.kill(r,"SIGKILL")}catch{}}await we.unlink(s).catch(()=>{})}}spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,i=r.command.length>0?r.command:[r.name],o=Le.createWriteStream(this.adapter.paths.logFile(r.name),{flags:"a"});o.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
93
93
  `);let a=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=a,e.version=void 0;let d={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:a,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[c,...f]=i;if(c===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
94
- `),o.end();return}let u=[...f,...r.args],l;try{l=Da(c,u,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
95
- `),o.end(),this.scheduleRestart(e,t);return}if(l.stdout&&l.stdout.pipe(o,{end:!1}),l.stderr&&l.stderr.pipe(o,{end:!1}),typeof l.pid=="number")try{Ue.writeFileSync(this.adapter.paths.pidFile(r.name),`${l.pid}
94
+ `),o.end();return}let u=[...f,...r.args],l;try{l=Wa(c,u,{env:d,stdio:["ignore","pipe","pipe"],detached:!1})}catch(p){o.write(`[hydra-acp] failed to spawn ${r.name}: ${p.message}
95
+ `),o.end(),this.scheduleRestart(e,t);return}if(l.stdout&&l.stdout.pipe(o,{end:!1}),l.stderr&&l.stderr.pipe(o,{end:!1}),typeof l.pid=="number")try{Le.writeFileSync(this.adapter.paths.pidFile(r.name),`${l.pid}
96
96
  `,{encoding:"utf8",mode:384})}catch(p){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${p.message}
97
97
  `)}e.child=l,e.logStream=o,e.pid=typeof l.pid=="number"?l.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,l.on("error",p=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
98
- `)}),l.on("exit",(p,m)=>{try{Ue.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${m??"null"}
98
+ `)}),l.on("exit",(p,m)=>{try{Le.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${m??"null"}
99
99
  `),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof p=="number"?p:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let g=e.exitWaiters.splice(0);for(let y of g)y();if(this.stopping||e.manuallyStopped){try{o.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let h=e.breaker.recordExit(p,r.name,this.adapter.kind);if(typeof h=="object"){e.failureReason=h.tripped,o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${h.tripped}
100
- `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function Tn(n){try{return process.kill(n,0),!0}catch{return!1}}function rt(n,e){return n.code=e,n}var Ja={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},Tt=class extends Be{constructor(e,t,s={}){super(e,Ja,t,s)}};var za={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},_t=class extends Be{connected=new Map;constructor(e,t,s={}){super(e,za,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var $t=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 ot from"fs/promises";import*as Ot from"path";var it=n=>{process.stderr.write(n+`
101
- `)};function _n(n){it=n??(e=>process.stderr.write(e+`
102
- `))}async function Mr(n,e){let t=ie();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Ot.join(w.agentsDir(),t),a;try{a=await ot.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;it(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,f=r.get(c);if(f===void 0)continue;let u=i.get(c)??new Set,l=Ot.join(o,c),p;try{p=await ot.readdir(l,{withFileTypes:!0})}catch(m){it(`hydra-acp: prune: failed to read ${l}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let g=m.name;if(g===f||u.has(g)||g.includes(".partial-"))continue;let h=Ot.join(l,g);try{await ot.rm(h,{recursive:!0,force:!0}),it(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(y){it(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function Rr(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let f=await n.registry.load();for(let u of f.agents)await cn(u)==="yes"&&a.push(u.id)}catch(f){return r("warn",`registry load failed: ${f.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:f,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${f.length}, skipped ${u}`)}catch(f){r("warn",`${c}: ${f.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function $n(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let g=Date.parse(p.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||o.push({sessionId:p.sessionId,lastUsedMs:g}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,f=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(m){f+=1,t("warn",`delete ${p} failed: ${m.message}`)}let u=o.length-a.length;if(n.verbose||c>0||f>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Wa(n.maxAgeMs)}`+(f>0?`; ${f} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let l={considered:o.length,deleted:c,failed:f,deferred:u};return d!==void 0&&(l.oldestLastUsedMs=d),l}function Er(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await $n({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Wa(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 Qa}from"crypto";function On(n){if(Array.isArray(n))return n.map(On);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=On(n[t]);return e}return n}function Pr(n){let e=JSON.stringify(On(n));return Qa("sha256").update(e).digest("hex").slice(0,16)}import*as $r from"path";import{createHash as Va,randomBytes as Ga,timingSafeEqual as Ya}from"crypto";var Or="hydra_session_",Ka=3600*24*30,Tr=12,Xa=32,Za=50;function ed(){return $r.join(w.home(),"session-tokens.json")}function _r(n){return Va("sha256").update(n).digest("hex")}function Fr(n){return Ga(n).toString("hex")}function td(){return Fr(Tr).slice(0,Tr*2)}function nd(){return`${Or}${Fr(Xa)}`}var Ft=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=ed(),s=await re(t);s&&Array.isArray(s.records)&&(e=s.records.filter(sd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=nd(),s=_r(t),r=td(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:Ka,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Or))return;let t=_r(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!Ya(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},Za))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Z(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 sd(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 Nr="Bearer ",Nt=class{constructor(e){this.token=e}token;async validate(e){return rd(e,this.token)?"service":void 0}},Ht=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},jt=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 Hr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Nr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Nr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function jr(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Bt=class{tokens=new Map;mint(e,t){let s=lt();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 rd(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 Ut=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 ct from"os";import*as ni from"path";import{posix as id}from"path";import od from"strip-ansi";function at(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var ad=/[\x00-\x08\x0b-\x1f\x7f]/g;function te(n){return od(n).replace(ad,"")}function B(n){return te(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Dr(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 md(t);case"agent_thought_chunk":case"agent_thought":return gd(t);case"user_message_chunk":return hd(t);case"prompt_received":return yd(t);case"tool_call":return wd(t,e);case"tool_call_update":return kd(t,e);case"plan":return Cd(t);case"current_mode_update":return Md(t);case"current_model_update":return Rd(t);case"turn_complete":return Ed(t);case"usage_update":return pd(t);case"available_commands_update":return ld(t);case"available_modes_update":return fd(t);case"session_info_update":return cd(t);case"config_option_update":return dd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function dd(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function cd(n){let e=H(n,"title"),t=e!==void 0?B(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),i}function ud(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:B(r)};typeof s.description=="string"&&(i.description=B(s.description)),e.push(i)}return e}function ld(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:ud(e)}:null}function fd(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:B(r.id)};typeof r.name=="string"&&(i.name=B(r.name)),typeof r.description=="string"&&(i.description=B(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function pd(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 md(n){let e=dt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:at(n)}}function gd(n){let e=typeof n.text=="string"?te(n.text):dt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:at(n)}}function hd(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=dt(n.content);return t===null?null:{kind:"user-text",text:t}}function yd(n){let e=Pd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Lr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Br(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 Dt(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=Br(r.oldText),o=Br(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function qr(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:te(t)}function wd(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title")??H(n,"name")??H(n,"label")??"tool call",r=H(n,"name")??H(n,"title");if(Lr(r)){let l=qr(n);if(l!==null){let p=H(n,"status"),m={kind:"exit-plan-mode",toolCallId:t,plan:l};return p!==void 0&&(m.status=p),m}}let i=zr(B(s),n,e),o=H(n,"status"),a=H(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Dt(n);c!==null&&(d.editDiff=c);let f=Jr(n);f!==void 0&&(d.detail=f);let u=at(n);return u!==void 0&&(d.workerTaskId=u),d}var Ur=64;function Jr(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.command=="string"&&t.command.trim().length>0){let i=B(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return bd(i,Ur)}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 Sd(Ce(B(s)),Ur)}var vd=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Id(n){for(let e of vd)if(n.startsWith(e))return!0;return!1}function zr(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ce(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Ce(o)}return Id(n)?Ce(`/${n}`):t.cwd&&t.cwd.length>0?Ce(id.resolve(t.cwd,n)):n}function bd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Sd(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 kd(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title"),r=s!==void 0?zr(B(s),n,e):void 0,i=H(n,"status"),o=Dt(n),a=Jr(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=H(n,"name")??s;if(Lr(c)){let l={kind:"exit-plan-mode",toolCallId:t},p=qr(n);return p!==null&&(l.plan=p),i!==void 0&&(l.status=i),l}let f={kind:"tool-call-update",toolCallId:t};if(r!==void 0&&(f.title=r),a!==void 0&&(f.detail=a),i!==void 0&&(f.status=i),o!==null&&(f.editDiff=o),i==="failed"){let l=Ad(n);l!==null&&(f.errorText=l),xd(n,l)&&(f.upstreamInterrupted=!0)}let u=at(n);return u!==void 0&&(f.workerTaskId=u),f}function Ad(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=dt(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return te(s)}return null}function xd(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 Cd(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?B(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function Md(n){let e=H(n,"currentModeId")??H(n,"currentMode")??H(n,"mode");return e?{kind:"mode-changed",mode:B(e)}:null}function Rd(n){let e=H(n,"currentModel")??H(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:B(e),...s&&s.length>0?{availableModels:s}:{}}}function Ed(n){let e=H(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 dt(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?te(e.text):null}function Pd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=dt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function H(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Wr(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=_d(o);if(c.length===0)continue;let f=c;if(d!==void 0){let u=e.get(d)??[],l=[];for(let p of c)u.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||l.push(p);if(l.length===0)continue;e.set(d,[...u,...l]),f=l}for(let u of f)Td(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Qr(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Td(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 _d(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,f=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;f===void 0||u===void 0||e.push({path:o,oldText:f,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=Dt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Vr(n){let e=$d(n),t=Od(e),s=[];Fd(s,n),Nd(s,e,t);let r=s.join(`
100
+ `);try{o.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t)},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function On(n){try{return process.kill(n,0),!0}catch{return!1}}function it(n,e){return n.code=e,n}var Ga={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},$t=class extends De{constructor(e,t,s={}){super(e,Ga,t,s)}};var Ya={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},Ot=class extends De{connected=new Map;constructor(e,t,s={}){super(e,Ya,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}};var Ft=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 at from"fs/promises";import*as Nt from"path";var ot=n=>{process.stderr.write(n+`
101
+ `)};function Fn(n){ot=n??(e=>process.stderr.write(e+`
102
+ `))}async function Tr(n,e){let t=ie();if(!t)return;let s=await n.load(),r=new Map;for(let d of s.agents)r.set(d.id,d.version??"current");let i=e.activeAgentVersions(),o=Nt.join(w.agentsDir(),t),a;try{a=await at.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;ot(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,f=r.get(c);if(f===void 0)continue;let u=i.get(c)??new Set,l=Nt.join(o,c),p;try{p=await at.readdir(l,{withFileTypes:!0})}catch(m){ot(`hydra-acp: prune: failed to read ${l}: ${m.message}`);continue}for(let m of p){if(!m.isDirectory())continue;let g=m.name;if(g===f||u.has(g)||g.includes(".partial-"))continue;let h=Nt.join(l,g);try{await at.rm(h,{recursive:!0,force:!0}),ot(`hydra-acp: pruned stale ${c} ${g} (${h})`)}catch(y){ot(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function _r(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let f=await n.registry.load();for(let u of f.agents)await fn(u)==="yes"&&a.push(u.id)}catch(f){return r("warn",`registry load failed: ${f.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:f,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${f.length}, skipped ${u}`)}catch(f){r("warn",`${c}: ${f.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},o=a=>{t||(e=setTimeout(()=>{i().then(d=>{o(d)}).catch(d=>{r("warn",`tick crashed: ${d.message}`),o(n.intervalMs)})},a),e.unref())};return o(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function Nn(n){let e=n.maxDeletions??200,t=(p,m)=>{n.logger&&n.logger[p](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let g=Date.parse(p.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||o.push({sessionId:p.sessionId,lastUsedMs:g}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,m)=>p.lastUsedMs-m.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,f=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(m){f+=1,t("warn",`delete ${p} failed: ${m.message}`)}let u=o.length-a.length;if(n.verbose||c>0||f>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${Ka(n.maxAgeMs)}`+(f>0?`; ${f} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let l={considered:o.length,deleted:c,failed:f,deferred:u};return d!==void 0&&(l.oldestLastUsedMs=d),l}function $r(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Nn({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},i),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function Ka(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 Xa}from"crypto";function Hn(n){if(Array.isArray(n))return n.map(Hn);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Hn(n[t]);return e}return n}function Or(n){let e=JSON.stringify(Hn(n));return Xa("sha256").update(e).digest("hex").slice(0,16)}import*as Hr from"path";import{createHash as Za,randomBytes as ed,timingSafeEqual as td}from"crypto";var jr="hydra_session_",nd=3600*24*30,Fr=12,sd=32,rd=50;function id(){return Hr.join(w.home(),"session-tokens.json")}function Nr(n){return Za("sha256").update(n).digest("hex")}function Br(n){return ed(n).toString("hex")}function od(){return Br(Fr).slice(0,Fr*2)}function ad(){return`${jr}${Br(sd)}`}var Ht=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=id(),s=await re(t);s&&Array.isArray(s.records)&&(e=s.records.filter(dd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=ad(),s=Nr(t),r=od(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:nd,a=new Date(i.getTime()+o*1e3),d={id:r,hash:s,label:e.label,createdAt:i.toISOString(),expiresAt:a.toISOString(),lastUsedAt:i.toISOString()};return this.records.set(s,d),this.scheduleWrite(),{id:r,token:t,expiresAt:d.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(jr))return;let t=Nr(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),i=Buffer.from(t,"hex");if(r.length!==i.length||!td(r,i))return;let o=new Date;if(new Date(s.expiresAt).getTime()<=o.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=o.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:i})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},rd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>Z(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 dd(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 Ur="Bearer ",jt=class{constructor(e){this.token=e}token;async validate(e){return cd(e,this.token)?"service":void 0}},Bt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Ut=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 Dr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Ur)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Ur.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Lr(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),i="hydra-acp-token.";if(r.startsWith(i))return r.slice(i.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var Dt=class{tokens=new Map;mint(e,t){let s=ft();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 cd(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 Lt=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 ut from"os";import*as oi from"path";import{posix as ud}from"path";import ld from"strip-ansi";function dt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var fd=/[\x00-\x08\x0b-\x1f\x7f]/g;function te(n){return ld(n).replace(fd,"")}function B(n){return te(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function zr(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 vd(t);case"agent_thought_chunk":case"agent_thought":return Id(t);case"user_message_chunk":return bd(t);case"prompt_received":return Sd(t);case"tool_call":return Ad(t,e);case"tool_call_update":return Rd(t,e);case"plan":return Td(t);case"current_mode_update":return _d(t);case"current_model_update":return $d(t);case"turn_complete":return Od(t);case"usage_update":return wd(t);case"available_commands_update":return hd(t);case"available_modes_update":return yd(t);case"session_info_update":return md(t);case"config_option_update":return pd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function pd(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let i=[];for(let o of r.options){if(!o||typeof o!="object")continue;let a=o;typeof a.value=="string"&&i.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:i,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function md(n){let e=H(n,"title"),t=e!==void 0?B(e):void 0,s=n._meta,r;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s["hydra-acp"];if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.agentId;typeof a=="string"&&(r=a)}}if(t===void 0&&r===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),i}function gd(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,i={name:B(r)};typeof s.description=="string"&&(i.description=B(s.description)),e.push(i)}return e}function hd(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:gd(e)}:null}function yd(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let i={id:B(r.id)};typeof r.name=="string"&&(i.name=B(r.name)),typeof r.description=="string"&&(i.description=B(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function wd(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 vd(n){let e=ct(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:dt(n)}}function Id(n){let e=typeof n.text=="string"?te(n.text):ct(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:dt(n)}}function bd(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=ct(n.content);return t===null?null:{kind:"user-text",text:t}}function Sd(n){let e=Fd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Wr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function qr(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 qt(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let i=qr(r.oldText),o=qr(r.newText);if(i===void 0&&o===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:i?.text??"",newText:o?.text??"",...i?.ref?{oldRef:i.ref}:{},...o?.ref?{newRef:o.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Qr(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:te(t)}function Ad(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title")??H(n,"name")??H(n,"label")??"tool call",r=H(n,"name")??H(n,"title");if(Wr(r)){let l=Qr(n);if(l!==null){let p=H(n,"status"),m={kind:"exit-plan-mode",toolCallId:t,plan:l};return p!==void 0&&(m.status=p),m}}let i=Gr(B(s),n,e),o=H(n,"status"),a=H(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=qt(n);c!==null&&(d.editDiff=c);let f=Vr(n);f!==void 0&&(d.detail=f);let u=dt(n);return u!==void 0&&(d.workerTaskId=u),d}var Jr=64;function Vr(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(typeof t.command=="string"&&t.command.trim().length>0){let i=B(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");return Cd(i,Jr)}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 Md(Me(B(s)),Jr)}var kd=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function xd(n){for(let e of kd)if(n.startsWith(e))return!0;return!1}function Gr(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,i=[r.file_path,r.filePath,r.path];for(let o of i)if(!(typeof o!="string"||o.length===0)&&(o===`/${n}`||o.endsWith(`/${n}`)||o===n))return Me(o)}return xd(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(ud.resolve(t.cwd,n)):n}function Cd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Md(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 Rd(n,e={}){let t=H(n,"toolCallId")??H(n,"id");if(!t)return null;let s=H(n,"title"),r=s!==void 0?Gr(B(s),n,e):void 0,i=H(n,"status"),o=qt(n),a=Vr(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=H(n,"name")??s;if(Wr(c)){let l={kind:"exit-plan-mode",toolCallId:t},p=Qr(n);return p!==null&&(l.plan=p),i!==void 0&&(l.status=i),l}let f={kind:"tool-call-update",toolCallId:t};if(r!==void 0&&(f.title=r),a!==void 0&&(f.detail=a),i!==void 0&&(f.status=i),o!==null&&(f.editDiff=o),i==="failed"){let l=Ed(n);l!==null&&(f.errorText=l),Pd(n,l)&&(f.upstreamInterrupted=!0)}let u=dt(n);return u!==void 0&&(f.workerTaskId=u),f}function Ed(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=ct(s.content);if(i!==null&&i.length>0)return i}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return te(s)}return null}function Pd(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 Td(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,i=typeof r.content=="string"?B(r.content):void 0;if(!i)continue;let o={content:i};typeof r.status=="string"&&(o.status=r.status),typeof r.priority=="string"&&(o.priority=r.priority),t.push(o)}return{kind:"plan",entries:t}}function _d(n){let e=H(n,"currentModeId")??H(n,"currentMode")??H(n,"mode");return e?{kind:"mode-changed",mode:B(e)}:null}function $d(n){let e=H(n,"currentModel")??H(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:B(e),...s&&s.length>0?{availableModels:s}:{}}}function Od(n){let e=H(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function ct(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?te(e.text):null}function Fd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=ct(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function H(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Yr(n){let e=new Map,t=new Map;for(let r of n){let o=r.params?.update;if(!o||typeof o!="object")continue;let a=o.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let d=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:void 0,c=Hd(o);if(c.length===0)continue;let f=c;if(d!==void 0){let u=e.get(d)??[],l=[];for(let p of c)u.some(m=>m.path===p.path&&m.oldText===p.oldText&&m.newText===p.newText)||l.push(p);if(l.length===0)continue;e.set(d,[...u,...l]),f=l}for(let u of f)Nd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function Kr(n){let e=[];for(let t of n){let s=-1;for(let i=e.length-1;i>=0;i--)if(e[i].newText===t.oldText){s=i;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Nd(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 Hd(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,o=typeof i.file_path=="string"?i.file_path:typeof i.path=="string"?i.path:void 0,a=i.edits;if(o!==void 0&&Array.isArray(a)){for(let d of a){if(!d||typeof d!="object")continue;let c=d,f=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;f===void 0||u===void 0||e.push({path:o,oldText:f,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let d=typeof o.oldText=="string"?o.oldText:"",c=typeof o.newText=="string"?o.newText:"";e.push({path:a,oldText:d,newText:c})}if(e.length>0)return e}let r=qt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Xr(n){let e=jd(n),t=Bd(e),s=[];Ud(s,n),Dd(s,e,t);let r=s.join(`
103
103
  `);return r.endsWith(`
104
104
  `)||(r+=`
105
- `),r}function $d(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=Dr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Od(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 Fd(n,e){let t=e.session,s=zs(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${xe(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${Fn(a.size)}`:void 0;d.push(c?`${Fn(a.used)} / ${c} tokens`:`${Fn(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
106
- `)),n.push("")}function Nd(n,e,t){if(!e.some(c=>Hd(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},d=()=>{o||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),o=!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 f of c.text.split(`
107
- `))n.push(`> ${xe(f)}`);n.push(""),n.push("**Assistant:**"),n.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let f=c.text.split(`
108
- `);for(let u of f)n.push(`> _${xe(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let f=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Bd(f.status)} ${jd(f)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let f of c.entries){let u=f.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${xe(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${xe(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${xe(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Hd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function jd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${xe(n.title)}${t}`}function Bd(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 xe(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Fn(n){return n.toLocaleString("en-US")}function Gr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Ud(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let f of s){let u=f.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(f)}o?i="AND":a&&(i="OR");let c=d.map(f=>Dd(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function Dd(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Yr(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:Yr(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Yr(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Ld(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var qd=5,Jd=200,Kr=30;async function ei(n,e,t={}){let s=Ud(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??qd,i=t.maxSessions??Jd,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],f=!1;for(let u of d){if(c.length>=i){f=!0;break}let l=await n.loadHistory(u.sessionId).catch(()=>[]),p=zd(l,s,r);if(p.snippets.length===0)continue;let m={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(m.title=u.title),c.push(m)}return{query:e,truncated:f,results:c}}function zd(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Wd(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Wd(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Qd(a).filter(c=>Ld(t,c.kind));for(let c of d){let f=c.text.toLowerCase(),u=f.indexOf(r);if(u===-1)continue;let l=0;for(;u!==-1;)l++,u=f.indexOf(r,u+r.length);if(i+=l,o.length<s){let p=f.indexOf(r),m={kind:c.kind,text:Xd(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Qd(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Lt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?te(s.text):Lt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(Yd(s))return[];let i=Lt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=Kd(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Vd(s);default:return[]}}function Vd(n){let e=Xr(n,"name"),t=Xr(n,"title"),s=[];if(t!==void 0){let a=B(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=B(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Zr(r);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=Zr(i);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=Gd(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function Gd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=B(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=B(s);if(r.length>0)return r}}return null}function Yd(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 Lt(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?te(e.text):""}function Kd(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Lt(t);s.length>0&&e.push(s)}return e.join("")}function Xr(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Zr(n){try{return JSON.stringify(n)}catch{return""}}function Xd(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-Kr),d=Math.min(s.length,o+i.length+Kr),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function ti(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Gr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function si(n,e,t){n.get("/v1/sessions",async s=>{let r=s.query,i=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:i})}}),n.get("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.getOne(o);return a||(r.code(404).send({error:"session not found"}),r)}),n.post("/v1/sessions/search",async(s,r)=>{let i=s.body??{},o=typeof i.q=="string"?i.q:"";if(o.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(i.sessionIds)?i.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await ei(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=qe(i.cwd??t.cwd),a=i.agentId??t.agentId;try{let d=await e.create({cwd:o,agentId:a,mcpServers:i.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),n.post("/v1/sessions/collect",async(s,r)=>{let i=s.body??{},o=typeof i.maxAgeDays=="number"&&i.maxAgeDays>0?i.maxAgeDays*24*60*60*1e3:0,a=typeof i.limit=="number"&&i.limit>0?i.limit:1e3,d=i.selection==="explicit"||i.selection==="unpromoted"?i.selection:"unpromoted";try{let c=await $n({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),n.post("/v1/sessions/:id/kill",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=f=>ni.join(ct.tmpdir(),`hydra-acp-stdin-${f}.log`));try{return a.openStream(c)}catch(f){return r.code(409).send({error:f.message}),r}}),n.post("/v1/sessions/:id/stdin",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",f=d.eof===!0;try{return a.streamWrite(c,f)}catch(u){return r.code(409).send({error:u.message}),r}}),n.patch("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{};if(a.priority!==void 0){let c=a.priority,f;if(c===null||c===0)f=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)f=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,f)){r.code(404).send({error:"session not found"});return}r.code(204).send();return}if(a.regen===!0){if(!(e.get(o)!==void 0||await e.hasRecord(o))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(o),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(o,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.delete("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.get("/v1/sessions/:id/export",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.query?.tools,d=a==="references"?"references":or(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=et({record:c.record,history:d==="summary"?ar(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:V,machine:ct.hostname(),hydraHost:ti(t)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(f)}),n.get("/v1/sessions/:id/diff",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=s.query??{},c=d.fold==="true"||d.fold==="1",f=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(l=>l.trim()).filter(l=>l.length>0)):void 0,u=Wr(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:Qr(l.hunks)}))),r.code(200).send(u)}),n.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let i=s.params,o=await e.resolveCanonicalId(i.id)??i.id,a=await e.loadToolBlob(o,i.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),n.get("/v1/sessions/:id/transcript",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=et({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:V,machine:ct.hostname(),hydraHost:ti(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Vr(d))}),n.post("/v1/sessions/:id/fork",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=qe(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}if(a.title!==void 0){if(typeof a.title!="string"){r.code(400).send({error:"title must be a string"});return}d.title=a.title}try{let c=await e.forkSession(o,d);r.code(201).send(c)}catch(c){let f=c;if(f.code===I.SessionNotFound){r.code(404).send({error:f.message});return}if(f.code===I.InvalidParams||f.code===I.AgentNotInstalled){r.code(400).send({error:f.message});return}r.code(500).send({error:f.message})}}),n.post("/v1/sessions/import",async(s,r)=>{let i=s.body??{};if(i.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let o;if(i.cwd!==void 0){if(typeof i.cwd!="string"||i.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}o=i.cwd}let a;try{a=gr(i.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:i.replace===!0,...o!==void 0?{cwd:o}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===I.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),n.get("/v1/sessions/:id/history",async(s,r)=>{let i=s.params.id,o=s.query,a=o?.follow==="1"||o?.follow==="true",d=await e.resolveCanonicalId(i)??i,c=e.get(d),f,u,l=!1,p=1e4,m=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
105
+ `),r}function jd(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=zr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Bd(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 Ud(n,e){let t=e.session,s=Gs(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Ce(r)}`),n.push("");let i=[];i.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let o=[t.agentId];t.currentModel&&o.push(`model: ${t.currentModel}`),t.currentMode&&o.push(`mode: ${t.currentMode}`),i.push(`- **Agent:** ${o.filter(Boolean).join(" \xB7 ")}`),i.push(`- **Cwd:** ${t.cwd}`),i.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let d=[];if(a.used!==void 0){let c=a.size!==void 0?`${jn(a.size)}`:void 0;d.push(c?`${jn(a.used)} / ${c} tokens`:`${jn(a.used)} tokens`)}if(a.costAmount!==void 0){let c=a.costCurrency??"USD";d.push(`$${a.costAmount.toFixed(2)} ${c}`)}i.push(`- **Usage:** ${d.join(" \xB7 ")}`)}n.push(i.join(`
106
+ `)),n.push("")}function Dd(n,e,t){if(!e.some(c=>Ld(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let s=new Set,r=0,i="",o=!1,a=()=>{i.length!==0&&(n.push(i.trimEnd()),n.push(""),i="")},d=()=>{o||(r+=1,n.push("---"),n.push(""),n.push(`## Turn ${r}`),n.push(""),o=!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 f of c.text.split(`
107
+ `))n.push(`> ${Ce(f)}`);n.push(""),n.push("**Assistant:**"),n.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let f=c.text.split(`
108
+ `);for(let u of f)n.push(`> _${Ce(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let f=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Jd(f.status)} ${qd(f)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let f of c.entries){let u=f.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Ce(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Ce(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Ce(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Ld(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function qd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Ce(n.title)}${t}`}function Jd(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 Ce(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function jn(n){return n.toLocaleString("en-US")}function Zr(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function zd(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let i="OR",o=!1,a=!1,d=[];for(let f of s){let u=f.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(f)}o?i="AND":a&&(i="OR");let c=d.map(f=>Wd(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function Wd(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ei(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:ei(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ei(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Qd(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Vd=5,Gd=200,ti=30;async function ri(n,e,t={}){let s=zd(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Vd,i=t.maxSessions??Gd,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],f=!1;for(let u of d){if(c.length>=i){f=!0;break}let l=await n.loadHistory(u.sessionId).catch(()=>[]),p=Yd(l,s,r);if(p.snippets.length===0)continue;let m={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(m.title=u.title),c.push(m)}return{query:e,truncated:f,results:c}}function Yd(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:i,term:o}of e.terms){let a=Kd(n,o,i,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function Kd(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=Xd(a).filter(c=>Qd(t,c.kind));for(let c of d){let f=c.text.toLowerCase(),u=f.indexOf(r);if(u===-1)continue;let l=0;for(;u!==-1;)l++,u=f.indexOf(r,u+r.length);if(i+=l,o.length<s){let p=f.indexOf(r),m={kind:c.kind,text:sc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(m.toolName=c.toolName),o.push(m)}}}return{totalMatches:i,snippets:o}}function Xd(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let i=Jt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?te(s.text):Jt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(tc(s))return[];let i=Jt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=nc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return Zd(s);default:return[]}}function Zd(n){let e=ni(n,"name"),t=ni(n,"title"),s=[];if(t!==void 0){let a=B(t);if(a.length>0){let d={kind:"tool",text:a};e!==void 0&&(d.toolName=e),s.push(d)}}if(e!==void 0&&e!==t){let a=B(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=si(r);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=si(i);if(a.length>0){let d={kind:"tool-input",text:B(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=ec(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function ec(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=s.content;if(!i||typeof i!="object")continue;let o=i;if(o.type==="text"&&typeof o.text=="string"){let a=B(o.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=B(s);if(r.length>0)return r}}return null}function tc(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 Jt(n){if(typeof n=="string")return te(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?te(e.text):""}function nc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Jt(t);s.length>0&&e.push(s)}return e.join("")}function ni(n,e){let t=n[e];return typeof t=="string"?t:void 0}function si(n){try{return JSON.stringify(n)}catch{return""}}function sc(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),i=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),o=i.length>0?r.indexOf(i):0;o===-1&&(o=0);let a=Math.max(0,o-ti),d=Math.min(s.length,o+i.length+ti),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function ii(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Zr(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ai(n,e,t){n.get("/v1/sessions",async s=>{let r=s.query,i=r?.includeNonInteractive==="1"||r?.includeNonInteractive==="true";return{sessions:await e.list({cwd:r?.cwd,includeNonInteractive:i})}}),n.get("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.getOne(o);return a||(r.code(404).send({error:"session not found"}),r)}),n.post("/v1/sessions/search",async(s,r)=>{let i=s.body??{},o=typeof i.q=="string"?i.q:"";if(o.trim().length===0)return r.code(400).send({error:"q is required"}),r;let a=Array.isArray(i.sessionIds)?i.sessionIds.filter(c=>typeof c=="string"&&c.length>0):void 0;return await ri(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Ee(i.cwd??t.cwd),a=i.agentId??t.agentId;try{let d=await e.create({cwd:o,agentId:a,mcpServers:i.mcpServers});r.code(201).send({sessionId:d.sessionId,agentId:d.agentId,cwd:d.cwd})}catch(d){r.code(500).send({error:d.message})}}),n.post("/v1/sessions/collect",async(s,r)=>{let i=s.body??{},o=typeof i.maxAgeDays=="number"&&i.maxAgeDays>0?i.maxAgeDays*24*60*60*1e3:0,a=typeof i.limit=="number"&&i.limit>0?i.limit:1e3,d=i.selection==="explicit"||i.selection==="unpromoted"?i.selection:"unpromoted";try{let c=await Nn({manager:e,maxAgeMs:o,maxDeletions:a,selection:d,verbose:!1});r.code(200).send(c)}catch(c){r.code(500).send({error:c.message})}}),n.post("/v1/sessions/:id/kill",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){a.close({deleteRecord:!1}).catch(()=>{}),r.code(202).send();return}if(!await e.hasRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c={};(d.mode==="memory"||d.mode==="file")&&(c.mode=d.mode),typeof d.capacityBytes=="number"&&(c.capacityBytes=d.capacityBytes),typeof d.fileCapBytes=="number"&&(c.fileCapBytes=d.fileCapBytes),(c.mode??"memory")==="file"&&(c.filePathFor=f=>oi.join(ut.tmpdir(),`hydra-acp-stdin-${f}.log`));try{return a.openStream(c)}catch(f){return r.code(409).send({error:f.message}),r}}),n.post("/v1/sessions/:id/stdin",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(!a)return r.code(404).send({error:"session not found"}),r;let d=s.body??{},c=typeof d.chunk=="string"?d.chunk:"",f=d.eof===!0;try{return a.streamWrite(c,f)}catch(u){return r.code(409).send({error:u.message}),r}}),n.patch("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{};if(a.priority!==void 0){let c=a.priority,f;if(c===null||c===0)f=void 0;else if(typeof c=="number"&&Number.isInteger(c)&&c>0)f=c;else{r.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(o,f)){r.code(404).send({error:"session not found"});return}r.code(204).send();return}if(a.regen===!0){if(!(e.get(o)!==void 0||await e.hasRecord(o))){r.code(404).send({error:"session not found"});return}e.scheduleSynopsis(o),r.code(202).send();return}if(typeof a.title!="string"||a.title.trim().length===0){r.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(o,a.title)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.delete("/v1/sessions/:id",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=e.get(o);if(a){await a.close({deleteRecord:!0}),r.code(204).send();return}if(!await e.deleteRecord(o)){r.code(404).send({error:"session not found"});return}r.code(204).send()}),n.get("/v1/sessions/:id/export",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.query?.tools,d=a==="references"?"references":ur(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=tt({record:c.record,history:d==="summary"?lr(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:Q,machine:ut.hostname(),hydraHost:ii(t)}),u=new Date().toISOString().replace(/[:.]/g,"-");r.header("Content-Disposition",`attachment; filename="${o}-${u}.hydra"`),r.code(200).send(f)}),n.get("/v1/sessions/:id/diff",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=s.query??{},c=d.fold==="true"||d.fold==="1",f=typeof d.paths=="string"&&d.paths.length>0?new Set(d.paths.split(",").map(l=>l.trim()).filter(l=>l.length>0)):void 0,u=Yr(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:Kr(l.hunks)}))),r.code(200).send(u)}),n.get("/v1/sessions/:id/tools/:hash",async(s,r)=>{let i=s.params,o=await e.resolveCanonicalId(i.id)??i.id,a=await e.loadToolBlob(o,i.hash);if(a===null){r.code(404).send({error:"tool blob not found"});return}r.header("Content-Type","text/plain; charset=utf-8"),r.code(200).send(a)}),n.get("/v1/sessions/:id/transcript",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=await e.exportBundle(o);if(!a){r.code(404).send({error:"session not found"});return}let d=tt({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:Q,machine:ut.hostname(),hydraHost:ii(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(Xr(d))}),n.post("/v1/sessions/:id/fork",async(s,r)=>{let i=s.params.id,o=await e.resolveCanonicalId(i)??i,a=s.body??{},d={};if(a.forkAt!==void 0){if(typeof a.forkAt!="string"||a.forkAt.length===0){r.code(400).send({error:"forkAt must be a non-empty string"});return}d.forkAt=a.forkAt}if(a.cwd!==void 0){if(typeof a.cwd!="string"||a.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}d.cwd=Ee(a.cwd)}if(a.agentId!==void 0){if(typeof a.agentId!="string"||a.agentId.length===0){r.code(400).send({error:"agentId must be a non-empty string"});return}d.agentId=a.agentId}if(a.title!==void 0){if(typeof a.title!="string"){r.code(400).send({error:"title must be a string"});return}d.title=a.title}try{let c=await e.forkSession(o,d);r.code(201).send(c)}catch(c){let f=c;if(f.code===I.SessionNotFound){r.code(404).send({error:f.message});return}if(f.code===I.InvalidParams||f.code===I.AgentNotInstalled){r.code(400).send({error:f.message});return}r.code(500).send({error:f.message})}}),n.post("/v1/sessions/import",async(s,r)=>{let i=s.body??{};if(i.bundle===void 0){r.code(400).send({error:"missing bundle"});return}let o;if(i.cwd!==void 0){if(typeof i.cwd!="string"||i.cwd.length===0){r.code(400).send({error:"cwd must be a non-empty string"});return}o=i.cwd}let a;try{a=vr(i.bundle)}catch(d){r.code(400).send({error:"invalid bundle",details:d.message});return}try{let d=await e.importBundle(a,{replace:i.replace===!0,...o!==void 0?{cwd:o}:{}});r.code(201).send(d)}catch(d){let c=d;if(c.code===I.BundleAlreadyImported){r.code(409).send({error:"bundle already imported",existingSessionId:c.existingSessionId});return}r.code(500).send({error:c.message})}}),n.get("/v1/sessions/:id/history",async(s,r)=>{let i=s.params.id,o=s.query,a=o?.follow==="1"||o?.follow==="true",d=await e.resolveCanonicalId(i)??i,c=e.get(d),f,u,l=!1,p=1e4,m=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
109
109
  `):(m.push(h),m.length>p&&m.shift()))})),s.raw.on("close",()=>{u?.(),r.raw.writableEnded||r.raw.end()});try{f=await c.getHistorySnapshot()}catch(h){throw u?.(),h}}else{let h=await e.getHistory(d);if(h===void 0)return r.code(404).send({error:"session not found"}),r;f=h}r.raw.setHeader("Content-Type","application/x-ndjson"),r.raw.setHeader("Cache-Control","no-cache"),r.raw.statusCode=200;let g=new Set;for(let h of f??[]){r.raw.write(JSON.stringify(h)+`
110
- `);let y=h;typeof y.recordedAt=="number"&&g.add(String(y.recordedAt))}for(;m.length>0;){let h=m.splice(0,m.length);for(let y of h){let S=y,C=typeof S.recordedAt=="number"?String(S.recordedAt):"";C&&g.has(C)||r.raw.write(JSON.stringify(y)+`
111
- `)}}return l=!0,u||r.raw.end(),r})}function ri(n,e,t,s={}){n.get("/v1/agents",async()=>Te(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await ue(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===I.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function ii(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var Zd=/^[A-Za-z0-9._-]+$/;function qt(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=ec(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){ut(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){ut(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){ut(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){ut(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){ut(o,d)}})}function ut(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 ec(n){let e=n.name;if(typeof e!="string"||!Zd.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function oi(n,e){qt(n,"extension",e)}function ai(n,e){qt(n,"transformer",e)}function di(n,e){n.get("/v1/config",async()=>e)}import{z as Le}from"zod";import*as De from"fs/promises";import*as ci from"path";import{randomBytes as Fp,scrypt as tc,timingSafeEqual as nc}from"crypto";import{promisify as sc}from"util";var rc=sc(tc);function ui(){return ci.join(w.home(),"password-hash")}var ic=128*1024*1024;async function li(){try{return(await De.readFile(ui(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await De.readFile(ui(),"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),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await rc(n,o,a.length,{N:s,r,p:i,maxmem:ic});return d.length!==a.length?!1:nc(d,a)}var oc=Le.object({password:Le.string().min(1),label:Le.string().min(1).max(256).optional(),ttlSec:Le.number().int().positive().optional()}),ac=Le.object({id:Le.string().optional()}).optional();function pi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=dc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=oc.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await li())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await fi(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=ac.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function dc(n){return n.ip||"unknown"}import{nanoid as Dn}from"nanoid";function Nn(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as gi}from"crypto";function $(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function pc(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ne(n,e,t){let s=n.get(e);if(!s)throw $(I.SessionNotFound,t??`session ${e} not found`);return s}async function Hn(n,e){let t=yi(n),s;try{s=await n.manager.resurrect({...e,mcpServers:t?.descriptors})}catch(r){throw t!==void 0&&t.abandon(r instanceof Error?r:void 0),r}return t!==void 0&&t.bindToSession(s),wc(s,n),s}function hi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=jr({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Nn(t),a=new be(o),d={clientId:`hydra_client_${Dn(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,l)=>{if(d.attached.get(u)?.readonly)throw $(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=Is.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),yc()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},m=Array.isArray(p.commands)?p.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(g=>g!==void 0):[];return u.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let p=l??{},m=typeof p.instructions=="string"?p.instructions:void 0,g=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let S={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(S.outputSchema=y.outputSchema),S}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let l=u??{},p=Array.isArray(l.intercepts)?l.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.method=="string"?l.method:void 0,g=l.envelope,h=l.route;if(!p||!m)throw $(-32602,"emit_message requires sessionId and method");let y=ne(e.manager,p),S=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(S)return y.dischargeClaim(S,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,m,g)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,m,g)};throw $(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(-32602,"hydra-acp/session/request_permission requires sessionId");return ne(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>gc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,S=y&&typeof y.title=="string"?y.title:void 0;if(!m&&g){let F=e.manager.get(g);F&&(m=F.cwd)}if(!m)throw $(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let C=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:g,interactive:C,transformChain:[],title:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw $(I.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,m=l.until==="idle"?"idle":"turn_complete",g=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw $(-32602,"await_child requires childSessionId");let h=ne(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let A=[],F=[],U=0,G=!1,L,k,P=!1,j=()=>{P||(P=!0,clearTimeout(q),L?.(),k?.(),y(G?{entries:A,truncated:!0}:{entries:A}))};L=h.onBroadcast(Y=>{let D=pc(Y);for(A.push(Y),F.push(D),U+=D;A.length>0&&(A.length>1e3||U>1048576);)A.shift(),U-=F.shift()??0,G=!0;m==="turn_complete"&&Y.params?.update?.sessionUpdate==="turn_complete"&&j()});let q=setTimeout(j,g);typeof q.unref=="function"&&q.unref(),k=h.onClose(()=>j())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!p)throw $(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let l=u??{},p=typeof l.token=="string"?l.token:void 0,m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw $(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=await e.manager.loadToolBlob(p,l.hash);if(m===null)throw $(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("session/new",async u=>{let l=bs.parse(u),p=Qe(u?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(k=>typeof k=="string")?p.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,S=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=gi(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let P={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};S=[...l.mcpServers??[],P]}let C=yi(e);C!==void 0&&(S=[...S??[],...C.descriptors]);let A;try{A=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:S,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:mi(a),transformChain:g,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(k){throw y!==void 0&&y.abandon(k instanceof Error?k:void 0),C!==void 0&&C.abandon(k instanceof Error?k:void 0),k}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let k=h,P=e.mcpTokenRegistry;y.complete(A),A.onClose(()=>{P.unbind(k)})}C!==void 0&&C.bindToSession(A);let F,U;try{F=Jt(a,A,d),{entries:U}=await A.attach(F,"full")}catch(k){throw await A.close({deleteRecord:!1}).catch(()=>{}),k}d.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:F.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let k of U){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}})()});let G=jn(A),L=Bn(A);return{sessionId:A.sessionId,...G?{modes:G}:{},...L?{models:L}:{},configOptions:A.buildConfigOptions(),_meta:Un(e.manager,A,{clientId:F.clientId})}}),a.onRequest("session/attach",async u=>{let l=ks.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Qe(l._meta),g=m.resume,h=m.readonly===!0;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(y);if(!S&&h){let k=await e.manager.loadFromDisk(y);if(!k)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);let P=await e.manager.loadHistory(y),j=l.clientId??`cli_${Dn(8)}`;d.attached.set(k.hydraSessionId,{sessionId:k.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${k.hydraSessionId} clientId=${j} attachedCount=${d.attached.size} replayed=${P.length}`);for(let q of P)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:k.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:P.length,_meta:hc(k)}}if(!S){let k=await e.manager.loadFromDisk(y),P=k;if(g&&(P={...k,hydraSessionId:l.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 $(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let j=P.originatingClient?P:{...P,originatingClient:d.clientInfo};S=await Hn(e,{...j,onInstallProgress:mi(a)})}let C=Jt(a,S,d,l.clientInfo,l.clientId),A=m.replayMode==="drip",{entries:F,appliedPolicy:U}=await S.attach(C,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:A,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:C.clientId,readonly:h}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${C.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${U} replayed=${F.length} readonly=${h}${A?" replayMode=drip":""}`),A){let k=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,P=750;(async()=>{let j=null;for(let q of F){let Y=typeof q.recordedAt=="number"?q.recordedAt:null;if(j!==null&&Y!==null){let D=Math.min(P,Math.max(0,(Y-j)/k));D>0&&await new Promise(we=>setTimeout(we,D))}Y!==null&&(j=Y);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let k=0;k<F.length&&!a.isClosed();k++){let P=F[k],j=a.notify(P.method,P.params).catch(()=>{});(k+1)%200===0&&await j}S.replayPendingPermissions(C);let G=jn(S),L=Bn(S);return{sessionId:S.sessionId,clientId:C.clientId,connectedClients:S.connectedClients(C.clientId),historyPolicy:U,replayed:F.length,...G?{modes:G}:{},...L?{models:L}:{},configOptions:S.buildConfigOptions(),_meta:Un(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=As.parse(u),p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(l.sessionId);return m?.detach(p.clientId),d.attached.delete(l.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[We]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=xs.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==At).map(Cs)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw $(I.InternalError,"agent registry unavailable");return Te(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Ms.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),$(I.SessionNotFound,"not attached to session");let m=e.manager.get(l.sessionId);if(!m){let g=await e.manager.loadFromDisk(l.sessionId);if(!g)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),m=await Hn(e,g);let h=Jt(a,m,d,void 0,p.clientId);await m.attach(h,"none")}return m.prompt(p.clientId,l)});let f=u=>{let l;try{l=yt.parse(u)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let m=e.manager.get(l.sessionId);m&&m.cancel(p.clientId).catch(g=>{n.log.warn(`session/cancel for ${l.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=yt.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=Es.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ne(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=yt.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ne(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Ps.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ne(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Ts.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"not attached to session");return ne(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,g=e.manager.get(m);if(!g){let A=await e.manager.loadFromDisk(m);if(!A)throw $(I.SessionNotFound,`session ${p} not found in memory or on disk`);g=await Hn(e,A)}let h=Jt(a,g,d),{entries:y}=await g.attach(h,"pending_only");d.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let A of y){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}g.replayPendingPermissions(h);let S=jn(g),C=Bn(g);return{sessionId:g.sessionId,...S?{modes:S}:{},...C?{models:C}:{},configOptions:g.buildConfigOptions(),_meta:Un(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=mc(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),$(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:m}=p,g=await p.session.forwardRequest("session/set_model",{...u,modelId:m});return p.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async u=>{let l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw $(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw $(I.InvalidParams,"session/set_mode requires string modeId");let m=ne(e.manager,l.sessionId),g=await m.forwardRequest("session/set_mode",u);return m.applyModeChange(l.modeId),g}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>$(I.InvalidParams,y),m=l?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let g=ne(e.manager,l.sessionId),h=g.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),g.applyModelChange(l.value);break}case"mode":{l.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),g.applyModeChange(l.value);break}case"agent":{l.value!==g.agentId&&await g.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw $(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw $(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),ne(e.manager,p).forwardRequest(l,u)})})}function mi(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(_s,t).catch(()=>{})}}function jn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Bn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function mc(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(),i=$e(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function gc(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw $(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw $(I.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw $(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ne(t.manager,r).addTransformer(i),{ok:!0}}function hc(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,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{[We]:ht(e,t)}}function Un(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()};return ze(e.agentMeta,ht(s,r))}function yc(){return{protocolVersion:1,agentInfo:{name:"hydra",version:V},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"bearer-token",description:"Bearer token presented at WS upgrade"}],_meta:ze(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function wc(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 Jt(n,e,t,s,r){return{clientId:r??`cli_${Dn(8)}`,connection:n,clientInfo:s}}function yi(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=gi(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var zt=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as vc}from"crypto";import{McpServer as Ic}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as bc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z}from"zod";var wi="Bearer ";function Wt(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 Sc(n){let e=new Ic({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:z.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent: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:z.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent: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:z.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:z.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:z.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:z.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:z.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo(),o={outcome:r,writeCursor:i.writeCursor,closed:i.closed};return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent:o}}),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:z.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:z.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:z.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:z.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:z.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:z.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:z.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:z.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:z.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),i=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:i}}),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{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}),e}var kc=1e4;function vi(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=Sc(a),f=new bc({sessionIdGenerator:()=>vc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Wt(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(g=>{l=setTimeout(()=>g(void 0),kc)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),m===void 0){a.code(503).send({error:"session not ready"});return}f=m}let u=await s(d,f);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Qt=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 Pc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Tc}from"crypto";import{Server as Ac}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as xc,ListToolsRequestSchema as Cc}from"@modelcontextprotocol/sdk/types.js";var Mc=6e4;function Ii(n,e,t,s={}){let r=s.invokeTimeoutMs??Mc,i=typeof t=="function"?async()=>t():async()=>t,o=new Ac({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),a=new Map(e.tools.map(d=>[d.name,d]));return o.setRequestHandler(Cc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(xc,async d=>{let c=d.params.name;if(!a.has(c))return Vt(`unknown tool: ${c}`);try{let f=await i(),u=await Rc(e.connection,n,c,d.params.arguments??{},f,r);return Ec(u,c)}catch(f){return Vt(f instanceof Error?f.message:String(f))}}),o}async function Rc(n,e,t,s,r,i){let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Error(`extension timeout after ${i}ms`)),i)});try{return await Promise.race([n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function Ec(n,e){if(n===null||typeof n!="object")return Vt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Vt(`extension ${e} omitted content array`)}function Vt(n){return{content:[{type:"text",text:n}],isError:!0}}var _c=1e4;function bi(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let S=r.get(f);if(S!==void 0){r.delete(f);for(let C of S.values())await i(C)}}));let p=l.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let h=Ii(u,m,async()=>{let S=e.lookup(f);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let C,A=new Promise(U=>{C=setTimeout(()=>U(void 0),_c)}),F=await Promise.race([S.sessionReady.catch(()=>{}),A]);if(C!==void 0&&clearTimeout(C),F===void 0)throw new Error("session not ready");return F.sessionId},s.buildOptions),y=new Pc({sessionIdGenerator:()=>Tc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Wt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let m=f.params.name,g=await a(l,m);if(g===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await g.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Nc(n,e){jc(n);let t=n.daemon.tls?{key:await ye.readFile(n.daemon.tls.key),cert:await ye.readFile(n.daemon.tls.cert)}:void 0;await ye.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Hc(n.daemon.logLevel),i=$c({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Oc,{options:{handleProtocols:Jn}}),sn(N=>{i.log.info(N)}),an(N=>{i.log.info(N)});let o=await Ft.load(),a=new Ut,d=new Bt,c=new jt([new Nt(e),new Ht(o),d]),f=Hr({validator:c});i.addHook("onRequest",async(N,ve)=>{N.routeOptions.config?.skipAuth||N.url==="/acp"||N.url?.startsWith("/acp?")||await f(N,ve)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new Je(n,{onFetched:()=>{Mr(p,y)}});_n(N=>i.log.info(N));let m={info:N=>i.log.info(N),warn:N=>i.log.warn(N)},g=N=>le.spawn({...N,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});is(n.compressToolContent);let h=new $t,y=new st(p,g,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,synopsisOnClose:n.synopsisOnClose,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),S=new Tt(Xn(n),void 0,{tokenRegistry:d}),C=new _t(Zn(n),void 0,{tokenRegistry:d});ii(i,V,Pr(n)),si(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),ri(i,p,y,{npmRegistry:n.npmRegistry}),oi(i,S),ai(i,C),di(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},synopsisOnClose:n.synopsisOnClose,defaultTransformers:[...n.defaultTransformers]}),pi(i,{store:o,rateLimiter:a});let A=new zt,F=new Qt;vi(i,A),bi(i,A,F);let U,G=()=>{if(U!==void 0)return U;let N=i.server.address(),ve=N&&typeof N=="object"?N.port:n.daemon.port;return U=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${ve}`,U};hi(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(N,ve)=>S.reportVersion(N,ve),onTransformerVersion:(N,ve)=>C.reportVersion(N,ve),transformers:C,extensionCommands:h,mcpTokenRegistry:A,extensionMcp:F,getDaemonOrigin:G,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let L=i.server.address(),k=L&&typeof L=="object"?L.port:n.daemon.port;await ye.mkdir(w.home(),{recursive:!0}),await ye.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:k,startedAt:new Date().toISOString()})+`
112
- `,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",j=n.daemon.tls?"wss":"ws",q={daemonUrl:`${P}://${n.daemon.host}:${k}`,daemonHost:n.daemon.host,daemonPort:k,serviceToken:e,daemonWsUrl:`${j}://${n.daemon.host}:${k}/acp`,hydraHome:w.home()};S.setContext(q),C.setContext(q),await S.start(),await C.start(),y.resurrectPendingQueues().catch(N=>{i.log.warn(`queue replay scan failed: ${N.message}`)});let Y=n.daemon.agentSyncIntervalMinutes*60*1e3,D=Y>0?Rr({registry:p,manager:y,intervalMs:Y,logger:m}):void 0,we=n.daemon.sessionGcIntervalMinutes*60*1e3,Ai=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ln=we>0?Er({manager:y,intervalMs:we,maxAgeMs:Ai,logger:m}):void 0;return{app:i,manager:y,registry:p,extensions:S,transformers:C,mcpTokenRegistry:A,extensionMcp:F,processRegistry:d,shutdown:async()=>{Ln&&Ln(),D&&D(),clearInterval(u),clearInterval(l),await o.flush(),await S.stop(),await C.stop(),await y.closeAll(),await y.flushSynopsis(3e4),await y.shutdownSynopsis(),await y.flushMetaWrites(),await y.flushHistoryWrites(),sn(null),an(null),_n(null),await i.close();try{ki.unlinkSync(w.pidFile())}catch{}try{r.flushSync()}catch{}}}}async function Hc(n){let e=await Fc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=Si.destination(2);return{stream:Si.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function jc(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{le as AgentInstance,be as JsonRpcConnection,Je as Registry,Se as Session,st as SessionManager,Li as defaultConfig,Mi as ensureServiceToken,lt as generateServiceToken,ts as loadConfig,Ci as loadServiceToken,ln as ndjsonStreamFromStdio,w as paths,ue as planSpawn,Nc as startDaemon,Di as writeConfig,Nn as wsToMessageStream};
110
+ `);let y=h;typeof y.recordedAt=="number"&&g.add(String(y.recordedAt))}for(;m.length>0;){let h=m.splice(0,m.length);for(let y of h){let S=y,M=typeof S.recordedAt=="number"?String(S.recordedAt):"";M&&g.has(M)||r.raw.write(JSON.stringify(y)+`
111
+ `)}}return l=!0,u||r.raw.end(),r})}function di(n,e,t,s={}){n.get("/v1/agents",async()=>$e(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,i)=>{let o=r.params.id,a=await e.getAgent(o);if(!a){i.code(404).send({error:`agent ${o} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){i.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let d=await ae(a,[],{npmRegistry:s.npmRegistry}),c=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";i.send({agentId:a.id,version:d.version,distribution:c,installed:!0,command:d.command})}catch(d){i.code(500).send({error:d.message})}}),n.post("/v1/agents/:id/sync",async(r,i)=>{let o=r.params.id;try{let{synced:a,skipped:d}=await t.syncFromAgent(o);return{synced:a.map(c=>({sessionId:c.sessionId,upstreamSessionId:c.upstreamSessionId,agentId:c.agentId,cwd:c.cwd,title:c.title,updatedAt:c.updatedAt})),skipped:d}}catch(a){let d=a;if(d.code===I.AgentNotInstalled){i.code(404).send({error:d.message});return}i.code(409).send({error:d.message})}})}function ci(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var rc=/^[A-Za-z0-9._-]+$/;function zt(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(i,o)=>{let a=i.params.name,d=t.get(a);if(!d){o.code(404).send({error:`unknown ${e}: ${a}`});return}return d}),n.post(r,async(i,o)=>{let a=i.body??{},d=ic(a);if("error"in d){o.code(400).send({error:d.error});return}try{let c=t.register(d.config);o.code(201).send(c)}catch(c){lt(o,c)}}),n.delete(`${r}/:name`,async(i,o)=>{let a=i.params.name;try{await t.unregister(a),o.code(204).send()}catch(d){lt(o,d)}}),n.post(`${r}/:name/start`,async(i,o)=>{let a=i.params.name;try{let d=await t.startByName(a);o.code(200).send(d)}catch(d){lt(o,d)}}),n.post(`${r}/:name/stop`,async(i,o)=>{let a=i.params.name;try{let d=await t.stopByName(a);o.code(200).send(d)}catch(d){lt(o,d)}}),n.post(`${r}/:name/restart`,async(i,o)=>{let a=i.params.name;try{let d=await t.restartByName(a);o.code(200).send(d)}catch(d){lt(o,d)}})}function lt(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 ic(n){let e=n.name;if(typeof e!="string"||!rc.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(o=>typeof o!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(o=>typeof o!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(o=>typeof o!="string"))return{error:"env values must be strings"};let i=n.enabled;return i!==void 0&&typeof i!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:i===void 0?!0:i}}}function ui(n,e){zt(n,"extension",e)}function li(n,e){zt(n,"transformer",e)}function fi(n,e){n.get("/v1/config",async()=>e)}import{z as Je}from"zod";import*as qe from"fs/promises";import*as pi from"path";import{randomBytes as Up,scrypt as oc,timingSafeEqual as ac}from"crypto";import{promisify as dc}from"util";var cc=dc(oc);function mi(){return pi.join(w.home(),"password-hash")}var uc=128*1024*1024;async function gi(){try{return(await qe.readFile(mi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function hi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await qe.readFile(mi(),"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),i=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(i))return!1;let o=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(o.length===0||a.length===0)return!1;let d=await cc(n,o,a.length,{N:s,r,p:i,maxmem:uc});return d.length!==a.length?!1:ac(d,a)}var lc=Je.object({password:Je.string().min(1),label:Je.string().min(1).max(256).optional(),ttlSec:Je.number().int().positive().optional()}),fc=Je.object({id:Je.string().optional()}).optional();function yi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=pc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=lc.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await gi())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await hi(i.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:i.label,ttlSec:i.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=fc.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let i=r?.id??t.authIdentity;if(!i||i==="service")return s.code(200).send({revoked:!1});let o=await e.store.revoke(i);return s.code(200).send({revoked:o})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function pc(n){return n.ip||"unknown"}import{nanoid as Jn}from"nanoid";function Bn(n){let e=[],t=[],s=!1,r=i=>{if(!s){s=!0;for(let o of t)o(i)}};return n.on("message",(i,o)=>{if(o)return;let a=i.toString("utf8");try{let d=JSON.parse(a);for(let c of e)c(d)}catch(d){for(let c of e)c({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${d.message}`}})}}),n.on("close",()=>r()),n.on("error",i=>r(i)),{async send(i){if(s)throw new Error("ws is closed");let o=JSON.stringify(i);await new Promise((a,d)=>{n.send(o,c=>{if(c){d(c);return}a()})})},onMessage(i){e.push(i)},onClose(i){t.push(i)},async close(){s||(await new Promise(i=>{let o=!1,a=()=>{o||(o=!0,clearTimeout(d),i())},d=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as vi}from"crypto";function $(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function wc(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,i=s.content;if(typeof i=="string")r+=i.length;else if(i&&typeof i=="object"){let a=i;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let o=s.toolCall;if(o&&(typeof o.rawInput=="string"?r+=o.rawInput.length:o.rawInput&&typeof o.rawInput=="object"&&(r+=256),typeof o.rawOutput=="string"?r+=o.rawOutput.length:o.rawOutput&&typeof o.rawOutput=="object"&&(r+=256),Array.isArray(o.content)))for(let a of o.content){if(!a||typeof a!="object")continue;let d=a;if(typeof d.text=="string"&&(r+=d.text.length),d.content&&typeof d.content=="object"){let c=d.content;typeof c.text=="string"&&(r+=c.text.length)}}return r}function ne(n,e,t){let s=n.get(e);if(!s)throw $(I.SessionNotFound,t??`session ${e} not found`);return s}async function Un(n,e){let t=bi(n),s;try{s=await n.manager.resurrect({...e,mcpServers:t?.descriptors})}catch(r){throw t!==void 0&&t.abandon(r instanceof Error?r:void 0),r}return t!==void 0&&t.bindToSession(s),kc(s,n),s}function Ii(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Lr({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let i=e.processRegistry?.resolve(r),o=Bn(t),a=new Se(o),d={clientId:`hydra_client_${Jn(12)}`,processIdentity:i,attached:new Map};a.onClose(()=>{for(let u of d.attached.values())e.manager.get(u.sessionId)?.detach(u.clientId);d.attached.clear()});let c=(u,l)=>{if(d.attached.get(u)?.readonly)throw $(I.PermissionDenied,`${l} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let l=ks.parse(u??{});l.clientInfo?.name&&(d.clientInfo={name:l.clientInfo.name,...l.clientInfo.version!==void 0?{version:l.clientInfo.version}:{}});let p=l.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),Ac()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},m=Array.isArray(p.commands)?p.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let y={verb:h.verb};return typeof h.argsHint=="string"&&(y.argsHint=h.argsHint),typeof h.description=="string"&&(y.description=h.description),y}).filter(g=>g!==void 0):[];return u.register(i.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let p=l??{},m=typeof p.instructions=="string"?p.instructions:void 0,g=Array.isArray(p.tools)?p.tools.map(h=>{if(!h||typeof h!="object")return;let y=h;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let S={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(S.outputSchema=y.outputSchema),S}).filter(h=>h!==void 0):[];if(g.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,m,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let l=u??{},p=Array.isArray(l.intercepts)?l.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let m=e.transformers.resolveChain([i.name])[0];if(m)for(let g of e.manager.liveSessions())g.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.method=="string"?l.method:void 0,g=l.envelope,h=l.route;if(!p||!m)throw $(-32602,"emit_message requires sessionId and method");let y=ne(e.manager,p),S=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(S)return y.dischargeClaim(S,g),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,m,g)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,m,g)};throw $(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(-32602,"hydra-acp/session/request_permission requires sessionId");return ne(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>bc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let l=u??{},p=typeof l.agentId=="string"?l.agentId:e.defaultAgent,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,h=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,S=y&&typeof y.title=="string"?y.title:void 0;if(!m&&g){let N=e.manager.get(g);N&&(m=N.cwd)}if(!m)throw $(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let M=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:m,parentSessionId:g,interactive:M,transformChain:[],title:S})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"fork_session requires sessionId");let p=typeof l.forkAt=="string"?l.forkAt:void 0,m=typeof l.cwd=="string"?l.cwd:void 0,g=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...m!==void 0?{cwd:m}:{},...g!==void 0?{agentId:g}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let l=u??{};if(typeof l.sessionId!="string")throw $(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=e.manager.get(p);if(m)return await m.close({deleteRecord:!0}),{deleted:!0,sessionId:p};if(!await e.manager.deleteRecord(p))throw $(I.SessionNotFound,`session ${p} not found`);return{deleted:!0,sessionId:p}}),a.onRequest("hydra-acp/child_session/await",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0,m=l.until==="idle"?"idle":"turn_complete",g=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw $(-32602,"await_child requires childSessionId");let h=ne(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let k=[],N=[],U=0,G=!1,L,A,T=!1,j=()=>{T||(T=!0,clearTimeout(q),L?.(),A?.(),y(G?{entries:k,truncated:!0}:{entries:k}))};L=h.onBroadcast(Y=>{let D=wc(Y);for(k.push(Y),N.push(D),U+=D;k.length>0&&(k.length>1e3||U>1048576);)k.shift(),U-=N.shift()??0,G=!0;m==="turn_complete"&&Y.params?.update?.sessionUpdate==="turn_complete"&&j()});let q=setTimeout(j,g);typeof q.unref=="function"&&q.unref(),A=h.onClose(()=>j())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let l=u??{},p=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!p)throw $(-32602,"close_child_session requires childSessionId");let m=e.manager.get(p);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let l=u??{},p=typeof l.token=="string"?l.token:void 0,m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&m&&e.manager.get(m)?.keepAliveClaim(p,g),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let l=u??{};if(typeof l.sessionId!="string"||typeof l.hash!="string")throw $(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,m=await e.manager.loadToolBlob(p,l.hash);if(m===null)throw $(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async u=>vc(u,e)),a.onRequest("session/new",async u=>{let l=xs.parse(u),p=Ve(u?._meta),m=Array.isArray(p.transformers)&&p.transformers.every(A=>typeof A=="string")?p.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,y,S=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=vi(32).toString("hex"),y=e.mcpTokenRegistry.reserve(h);let T={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};S=[...l.mcpServers??[],T]}let M=bi(e);M!==void 0&&(S=[...S??[],...M.descriptors]);let k;try{k=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:S,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:wi(a),transformChain:g,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{}})}catch(A){throw y!==void 0&&y.abandon(A instanceof Error?A:void 0),M!==void 0&&M.abandon(A instanceof Error?A:void 0),A}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let A=h,T=e.mcpTokenRegistry;y.complete(k),k.onClose(()=>{T.unbind(A)})}M!==void 0&&M.bindToSession(k);let N,U;try{N=Wt(a,k,d),{entries:U}=await k.attach(N,"full")}catch(A){throw await k.close({deleteRecord:!1}).catch(()=>{}),A}d.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let A of U){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}})()});let G=Dn(k),L=Ln(k);return{sessionId:k.sessionId,...G?{modes:G}:{},...L?{models:L}:{},configOptions:k.buildConfigOptions(),_meta:qn(e.manager,k,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let l=Ms.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let m=Ve(l._meta),g=m.resume,h=m.readonly===!0;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(y);if(!S&&h){let A=await e.manager.loadFromDisk(y);if(!A)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);let T=await e.manager.loadHistory(y),j=l.clientId??`cli_${Jn(8)}`;d.attached.set(A.hydraSessionId,{sessionId:A.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${A.hydraSessionId} clientId=${j} attachedCount=${d.attached.size} replayed=${T.length}`);for(let q of T)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:A.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:T.length,_meta:Sc(A)}}if(!S){let A=await e.manager.loadFromDisk(y),T=A;if(g&&(T={...A,hydraSessionId:l.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!T)throw $(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let j=T.originatingClient?T:{...T,originatingClient:d.clientInfo};S=await Un(e,{...j,onInstallProgress:wi(a)})}let M=Wt(a,S,d,l.clientInfo,l.clientId),k=m.replayMode==="drip",{entries:N,appliedPolicy:U}=await S.attach(M,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:k,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:M.clientId,readonly:h}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${M.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${U} replayed=${N.length} readonly=${h}${k?" replayMode=drip":""}`),k){let A=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,T=750;(async()=>{let j=null;for(let q of N){let Y=typeof q.recordedAt=="number"?q.recordedAt:null;if(j!==null&&Y!==null){let D=Math.min(T,Math.max(0,(Y-j)/A));D>0&&await new Promise(Ie=>setTimeout(Ie,D))}Y!==null&&(j=Y);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let A=0;A<N.length&&!a.isClosed();A++){let T=N[A],j=a.notify(T.method,T.params).catch(()=>{});(A+1)%200===0&&await j}S.replayPendingPermissions(M);let G=Dn(S),L=Ln(S);return{sessionId:S.sessionId,clientId:M.clientId,connectedClients:S.connectedClients(M.clientId),historyPolicy:U,replayed:N.length,...G?{modes:G}:{},...L?{models:L}:{},configOptions:S.buildConfigOptions(),_meta:qn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=Rs.parse(u),p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(l.sessionId);return m?.detach(p.clientId),d.attached.delete(l.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Qe]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=Es.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==xt).map(Ps)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw $(I.InternalError,"agent registry unavailable");return $e(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Ts.parse(u);c(l.sessionId,"session/prompt");let p=d.attached.get(l.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${l.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),$(I.SessionNotFound,"not attached to session");let m=e.manager.get(l.sessionId);if(!m){let g=await e.manager.loadFromDisk(l.sessionId);if(!g)throw $(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),m=await Un(e,g);let h=Wt(a,m,d,void 0,p.clientId);await m.attach(h,"none")}return m.prompt(p.clientId,l)});let f=u=>{let l;try{l=wt.parse(u)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let p=d.attached.get(l.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${l.sessionId}`);return}let m=e.manager.get(l.sessionId);m&&m.cancel(p.clientId).catch(g=>{n.log.warn(`session/cancel for ${l.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=$s.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ne(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=wt.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ne(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Os.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ne(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Fs.parse(u);c(l.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(l.sessionId);if(!p)throw $(I.SessionNotFound,"not attached to session");return ne(e.manager,l.sessionId).amendPrompt(p.clientId,l)}),a.onRequest("session/load",async u=>{let l=u??{},p=typeof l.sessionId=="string"?l.sessionId:void 0;if(!p)throw $(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(p)??p,g=e.manager.get(m);if(!g){let k=await e.manager.loadFromDisk(m);if(!k)throw $(I.SessionNotFound,`session ${p} not found in memory or on disk`);g=await Un(e,k)}let h=Wt(a,g,d),{entries:y}=await g.attach(h,"pending_only");d.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let k of y){if(a.isClosed())break;await a.notify(k.method,k.params).catch(()=>{})}g.replayPendingPermissions(h);let S=Dn(g),M=Ln(g);return{sessionId:g.sessionId,...S?{modes:S}:{},...M?{models:M}:{},configOptions:g.buildConfigOptions(),_meta:qn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Ic(u,e.manager);if(p.kind==="error")throw n.log.warn(p.logMessage),$(p.code,p.message);if(p.kind==="no_op")return n.log.warn(p.logMessage),await a.notify("session/update",{sessionId:p.sessionId,update:{sessionUpdate:"current_model_update",currentModel:p.currentModel}}).catch(()=>{}),null;n.log.info(p.logMessage);let{modelId:m}=p,g=await p.session.forwardRequest("session/set_model",{...u,modelId:m});return p.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async u=>{let l=u,p=l?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!l||typeof l.sessionId!="string")throw $(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof l.modeId!="string")throw $(I.InvalidParams,"session/set_mode requires string modeId");let m=ne(e.manager,l.sessionId),g=await m.forwardRequest("session/set_mode",u);return m.applyModeChange(l.modeId),g}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>$(I.InvalidParams,y),m=l?.sessionId;if(typeof m=="string"&&c(m,"session/set_config_option"),!l||typeof l.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof l.configId!="string")throw p("session/set_config_option requires string configId");if(typeof l.value!="string")throw p("session/set_config_option requires string value");let g=ne(e.manager,l.sessionId),h=g.buildConfigOptions().find(y=>y.id===l.configId);if(!h)throw p(`unknown configId ${JSON.stringify(l.configId)} for this session`);if(!h.options.some(y=>y.value===l.value))throw p(`value ${JSON.stringify(l.value)} is not valid for configId ${JSON.stringify(l.configId)}`);switch(l.configId){case"model":{l.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),g.applyModelChange(l.value);break}case"mode":{l.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),g.applyModeChange(l.value);break}case"agent":{l.value!==g.agentId&&await g.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(u,l)=>{if(!l.startsWith("session/")||u===null||typeof u!="object")throw $(I.MethodNotFound,`Method not found: ${l}`);let p=u.sessionId;if(typeof p!="string")throw $(I.MethodNotFound,`Method not found: ${l}`);return c(p,l),ne(e.manager,p).forwardRequest(l,u)})})}async function vc(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw $(I.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],i=typeof r?.sessionId=="string"?r.sessionId:void 0,o=typeof r?.agentId=="string"?r.agentId:void 0,a=i!==void 0?e.manager.getAgentForSession(i):void 0;if(!a||!a.isAlive()){let c=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(c)}let d=(a.authMethods??[]).map(c=>c.id);if(!d.includes(s))throw $(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${d.map(c=>JSON.stringify(c)).join(", ")}]`);try{return await a.connection.request("authenticate",{methodId:s})}catch(c){throw ke(c,a)}}function wi(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(Ns,t).catch(()=>{})}}function Dn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let i={id:r.id,name:r.name??r.id};return r.description!==void 0&&(i.description=r.description),i});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function Ln(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let i={modelId:r.modelId};return r.name!==void 0&&(i.name=r.name),r.description!==void 0&&(i.description=r.description),i});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function Ic(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(),i=Fe(t.modelId,r);if(i.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(i.kind==="resolved")return{kind:"ok",session:s,modelId:i.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(i.modelId)}`};let o=r.map(d=>d.modelId).join(", "),a=i.kind==="ambiguous"?`ambiguous (trailing-segment matches [${i.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${o}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${o}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${o}] (no current model to fall back to)`}}async function bc(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw $(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw $(I.InternalError,"transformer manager not configured");let i=t.transformers.resolveChain([e])[0];if(!i)throw $(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return ne(t.manager,r).addTransformer(i),{ok:!0}}function Sc(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,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{[Qe]:yt(e,t)}}function qn(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()};return We(e.agentMeta,yt(s,r))}function Ac(){return{protocolVersion:1,agentInfo:{name:"hydra",version:Q},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,sessionCapabilities:{attach:{},list:{}}},authMethods:[{id:"proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:We(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function kc(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 Wt(n,e,t,s,r){return{clientId:r??`cli_${Jn(8)}`,connection:n,clientInfo:s}}function bi(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=vi(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),i=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),o=n.mcpTokenRegistry;return{descriptors:i,bindToSession:a=>{s.complete(a),a.onClose(()=>{o.unbind(t)})},abandon:a=>s.abandon(a)}}var Qt=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((o,a)=>{t=o,s=a});r.catch(()=>{});let i={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,i),{complete:o=>{i.session=o,t(o)},abandon:o=>{this.byToken.delete(e),s(o??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as xc}from"crypto";import{McpServer as Cc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Mc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z}from"zod";var Si="Bearer ";function Vt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Si))return;let t=e.slice(Si.length).trim();return t.length>0?t:void 0}function Rc(n){let e=new Cc({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:z.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent: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:z.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return{content:[{type:"text",text:JSON.stringify(s)}],structuredContent: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:z.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:z.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:z.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let i=await n.streamRead(t,s,r);return{content:[{type:"text",text:JSON.stringify(i)}],structuredContent:i}}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:z.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:z.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),i=n.streamInfo(),o={outcome:r,writeCursor:i.writeCursor,closed:i.closed};return{content:[{type:"text",text:JSON.stringify(o)}],structuredContent:o}}),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:z.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:z.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:z.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:z.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:z.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:z.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:z.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:z.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:z.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),i=r;return{content:[{type:"text",text:JSON.stringify(r)}],structuredContent:i}}),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{content:[{type:"text",text:JSON.stringify(t)}],structuredContent:t}}),e}var Ec=1e4;function Ai(n,e){let t=new Map;async function s(o,a){let d=t.get(o);if(d!==void 0)return d.transport;let c=Rc(a),f=new Mc({sessionIdGenerator:()=>xc()});await c.connect(f);let u={server:c,transport:f};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await f.close()}catch{}try{await c.close()}catch{}}),f}async function r(o,a){let d=Vt(o);if(d===void 0){a.code(401).send({error:"missing bearer token"});return}let c=e.lookup(d);if(c===void 0){a.code(404).send({error:"unknown stdin token"});return}let f;if(c.session!==void 0)f=c.session;else{let l,p=new Promise(g=>{l=setTimeout(()=>g(void 0),Ec)}),m=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),m===void 0){a.code(503).send({error:"session not ready"});return}f=m}let u=await s(d,f);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Gt=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 Nc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Hc}from"crypto";import{Server as Pc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Tc,ListToolsRequestSchema as _c}from"@modelcontextprotocol/sdk/types.js";var $c=6e4;function ki(n,e,t,s={}){let r=s.invokeTimeoutMs??$c,i=typeof t=="function"?async()=>t():async()=>t,o=new Pc({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!1}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),a=new Map(e.tools.map(d=>[d.name,d]));return o.setRequestHandler(_c,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Tc,async d=>{let c=d.params.name;if(!a.has(c))return Yt(`unknown tool: ${c}`);try{let f=await i(),u=await Oc(e.connection,n,c,d.params.arguments??{},f,r);return Fc(u,c)}catch(f){return Yt(f instanceof Error?f.message:String(f))}}),o}async function Oc(n,e,t,s,r,i){let o,a=new Promise((d,c)=>{o=setTimeout(()=>c(new Error(`extension timeout after ${i}ms`)),i)});try{return await Promise.race([n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r}),a])}finally{o!==void 0&&clearTimeout(o)}}function Fc(n,e){if(n===null||typeof n!="object")return Yt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Yt(`extension ${e} omitted content array`)}function Yt(n){return{content:[{type:"text",text:n}],isError:!0}}var jc=1e4;function xi(n,e,t,s={}){let r=new Map;async function i(f){try{await f.transport.close()}catch{}try{await f.server.close()}catch{}}function o(f){for(let u of r.values()){let l=u.get(f);l!==void 0&&(u.delete(f),i(l))}}t.onChange(f=>{o(f)});async function a(f,u){let l=r.get(f);l===void 0&&(l=new Map,r.set(f,l),e.addDisposer(f,async()=>{let S=r.get(f);if(S!==void 0){r.delete(f);for(let M of S.values())await i(M)}}));let p=l.get(u);if(p!==void 0)return p.transport;let m=t.lookup(u);if(m===void 0)return;let h=ki(u,m,async()=>{let S=e.lookup(f);if(S===void 0)throw new Error("mcp token no longer bound");if(S.session!==void 0)return S.session.sessionId;let M,k=new Promise(U=>{M=setTimeout(()=>U(void 0),jc)}),N=await Promise.race([S.sessionReady.catch(()=>{}),k]);if(M!==void 0&&clearTimeout(M),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new Nc({sessionIdGenerator:()=>Hc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Vt(f);if(l===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(l)===void 0){u.code(404).send({error:"unknown mcp token"});return}let m=f.params.name,g=await a(l,m);if(g===void 0){u.code(404).send({error:`unknown mcp server: ${m}`});return}u.hijack(),await g.handleRequest(f.raw,u.raw,f.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.get("/mcp/:name",c,async(f,u)=>{await d(f,u)}),n.delete("/mcp/:name",c,async(f,u)=>{await d(f,u)})}async function Lc(n,e){Jc(n);let t=n.daemon.tls?{key:await ve.readFile(n.daemon.tls.key),cert:await ve.readFile(n.daemon.tls.cert)}:void 0;await ve.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await qc(n.daemon.logLevel),i=Bc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Uc,{options:{handleProtocols:Vn}}),an(E=>{i.log.info(E)}),un(E=>{i.log.info(E)});let o=await Ht.load(),a=new Lt,d=new Dt,c=new Ut([new jt(e),new Bt(o),d]),f=Dr({validator:c});i.addHook("onRequest",async(E,le)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,le)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new ze(n,{onFetched:()=>{Tr(p,y)}});Fn(E=>i.log.info(E));let m={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},g=E=>fe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});cs(n.compressToolContent);let h=new Ft,y=new rt(p,g,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,synopsisOnClose:n.synopsisOnClose,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),S=new $t(ns(n),void 0,{tokenRegistry:d}),M=new Ot(ss(n),void 0,{tokenRegistry:d});ci(i,Q,Or(n)),ai(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),di(i,p,y,{npmRegistry:n.npmRegistry}),ui(i,S),li(i,M),fi(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},synopsisOnClose:n.synopsisOnClose,defaultTransformers:[...n.defaultTransformers]}),yi(i,{store:o,rateLimiter:a});let k=new Qt,N=new Gt;Ai(i,k),xi(i,k,N);let U,G=()=>{if(U!==void 0)return U;let E=i.server.address(),le=E&&typeof E=="object"?E.port:n.daemon.port;return U=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${le}`,U};Ii(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,le)=>S.reportVersion(E,le),onTransformerVersion:(E,le)=>M.reportVersion(E,le),transformers:M,extensionCommands:h,mcpTokenRegistry:k,extensionMcp:N,getDaemonOrigin:G,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let L=i.server.address(),A=L&&typeof L=="object"?L.port:n.daemon.port;await ve.mkdir(w.home(),{recursive:!0}),await ve.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:A,startedAt:new Date().toISOString()})+`
112
+ `,{encoding:"utf8",mode:384});let T=n.daemon.tls?"https":"http",j=n.daemon.tls?"wss":"ws",q={daemonUrl:`${T}://${n.daemon.host}:${A}`,daemonHost:n.daemon.host,daemonPort:A,serviceToken:e,daemonWsUrl:`${j}://${n.daemon.host}:${A}/acp`,hydraHome:w.home()};S.setContext(q),M.setContext(q),await S.start(),await M.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let Y=n.daemon.agentSyncIntervalMinutes*60*1e3,D=Y>0?_r({registry:p,manager:y,intervalMs:Y,logger:m}):void 0,Ie=n.daemon.sessionGcIntervalMinutes*60*1e3,Ri=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,zn=Ie>0?$r({manager:y,intervalMs:Ie,maxAgeMs:Ri,logger:m}):void 0;return{app:i,manager:y,registry:p,extensions:S,transformers:M,mcpTokenRegistry:k,extensionMcp:N,processRegistry:d,shutdown:async()=>{zn&&zn(),D&&D(),clearInterval(u),clearInterval(l);let E=async(le,Wn)=>{try{await Wn()}catch(Kt){i.log.warn(`shutdown step ${le} failed: ${Kt instanceof Error?Kt.message:String(Kt)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>S.stop()),await E("transformers.stop",()=>M.stop()),await E("manager.closeAll",()=>y.closeAll()),await E("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await E("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await E("manager.flushMetaWrites",()=>y.flushMetaWrites()),await E("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),an(null),un(null),Fn(null),await E("app.close",()=>i.close());try{Mi.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function qc(n){let e=await Dc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=Ci.destination(2);return{stream:Ci.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Jc(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{fe as AgentInstance,Se as JsonRpcConnection,ze as Registry,Ae as Session,rt as SessionManager,Wi as defaultConfig,Ti as ensureServiceToken,ft as generateServiceToken,is as loadConfig,Pi as loadServiceToken,mn as ndjsonStreamFromStdio,w as paths,ae as planSpawn,Lc as startDaemon,zi as writeConfig,Bn as wsToMessageStream};