@hydra-acp/cli 0.1.79 → 0.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +250 -250
  2. package/dist/index.js +59 -59
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- import*as $i from"fs";import*as Se from"fs/promises";import Vc from"fastify";import Gc from"@fastify/websocket";var Xn="acp.v1";function Zn(n,e){return n.has(Xn)?Xn:!1}import _i from"pino";import Yc from"pino-roll";import*as ye from"fs/promises";import{homedir as sn}from"os";import{z as v}from"zod";import*as T from"path";import*as tn from"os";var Fi="HYDRA_ACP_HOME";function Ee(n){let e=tn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Oi(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function $(){let n=process.env[Fi];if(n&&n.length>0)return T.resolve(n);let e=Oi();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return T.join(tn.homedir(),".hydra-acp")}var w={home:$,config:()=>T.join($(),"config.json"),authToken:()=>T.join($(),"auth-token"),remotes:()=>T.join($(),"remotes.json"),pidFile:()=>T.join($(),"daemon.pid"),logFile:()=>T.join($(),"daemon.log"),currentLogFile:()=>T.join($(),"current.log"),registryCache:()=>T.join($(),"registry.json"),agentsDir:()=>T.join($(),"agents"),agentLogFile:n=>T.join($(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>T.join($(),"sessions"),sessionDir:n=>T.join($(),"sessions",n),sessionFile:n=>T.join($(),"sessions",n,"meta.json"),historyFile:n=>T.join($(),"sessions",n,"history.jsonl"),toolsDir:n=>T.join($(),"sessions",n,"tools"),toolBlobFile:(n,e)=>T.join($(),"sessions",n,"tools",e),queueFile:n=>T.join($(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>T.join($(),"sessions",".tombstones"),tombstoneAgentDir:n=>T.join($(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>T.join($(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>T.join($(),"extensions"),extensionLogFile:n=>T.join($(),"extensions",`${n}.log`),extensionPidFile:n=>T.join($(),"extensions",`${n}.pid`),transformersDir:()=>T.join($(),"transformers"),transformerLogFile:n=>T.join($(),"transformers",`${n}.log`),transformerPidFile:n=>T.join($(),"transformers",`${n}.pid`),transformerState:(n,e)=>T.join($(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>T.join($(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>T.join($(),"prompt-history"),tuiLogFile:()=>T.join($(),"tui.log"),shimWireLogFile:()=>T.join($(),"shim-wire.log")};import*as Pe from"fs/promises";function gt(){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 es(){try{let e=(await Pe.readFile(w.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Ni(){let n=await es();if(!n)throw new Error(`No service token found at ${w.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function nn(n){await Pe.mkdir(w.home(),{recursive:!0}),await Pe.writeFile(w.authToken(),n+`
2
- `,{encoding:"utf8",mode:384})}async function ji(){let n=await es();if(n)return n;let e=gt();return await nn(e),process.stderr.write(`hydra-acp: initialized ${w.authToken()} with a fresh service token.
3
- `),e}import*as z from"fs/promises";import*as ts from"fs";import*as te from"path";import{randomBytes as Hi}from"crypto";async function ne(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
- `;await Bi(n,r,t)}async function Bi(n,e,t={}){let s=await Ui(n),r=Di(s);await z.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Li()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await z.writeFile(i,e,o),await z.rename(i,s)}catch(o){throw await z.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{ts.chmodSync(s,t.mode)}catch{}}async function Ui(n){let e;try{e=await z.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await z.readlink(n),s=te.isAbsolute(t)?t:te.resolve(te.dirname(n),t);try{let r=await z.realpath(te.dirname(s));return te.join(r,te.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function oe(n){let e;try{e=await z.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 Di(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Li(){return Hi(4).toString("hex")}var ss="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",qi=v.object({cert:v.string(),key:v.string()}),rs=55514,Ji=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(rs),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:qi.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)}),zi=v.object({url:v.string().url().default(ss),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),Wi=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()}),Qi=v.object({packageSpec:v.string().optional()}),Vi=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"),openFileCommand:v.union([v.string(),v.array(v.string())]).optional(),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()}),ns=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Gi=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)}),Yi=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)}),is=v.object({daemon:Ji.default({}),registry:zi.default({url:ss,ttlHours:24,pinned:!1}),agents:v.record(v.string(),Wi).default({}),agentOverrides:v.record(v.string(),Qi).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(ns,Gi).default({}),transformers:v.record(ns,Yi).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Vi.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 os(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function as(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function ds(){return await Ki(),await oe(w.config())??{}}async function Ki(){let n;try{n=await ye.lstat(w.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await ye.stat(w.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await ye.readlink(w.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${w.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Xi(){let n=await ds(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await ye.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 nn(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ne(w.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${w.config()} to ${w.authToken()}.
5
- `)}async function cs(){return await Xi(),is.parse(await ds())}async function Zi(n){await ne(w.config(),n,{mode:384})}function eo(){return is.parse({})}function Te(n){return n==="~"||n==="$HOME"?sn():n.startsWith("~/")?sn()+n.slice(1):n.startsWith("$HOME/")?sn()+n.slice(5):n}import*as W from"fs/promises";import{createHash as to}from"crypto";import{gzip as no,gunzip as so}from"zlib";import{promisify as us}from"util";var ls=us(no),ro=us(so),fs=/^[A-Za-z0-9_-]+$/,io=/^[a-f0-9]{64}$/,rn=!0;function ps(n){rn=n}function mt(n,e){return fs.test(n)?e===void 0||io.test(e):!1}function ht(n,e){return`${w.toolBlobFile(n,e)}.gz`}async function on(n,e){if(!mt(n))return null;let t=to("sha256").update(e,"utf8").digest("hex"),s=ht(n,t),r=w.toolBlobFile(n,t);for(let a of[s,r])try{return await W.access(a),t}catch{}await W.mkdir(w.toolsDir(n),{recursive:!0});let i=rn?s:r,o=rn?await ls(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await W.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function yt(n,e){if(!mt(n,e))return null;try{let t=await W.readFile(ht(n,e));return(await ro(t)).toString("utf8")}catch{}try{return await W.readFile(w.toolBlobFile(n,e),"utf8")}catch{return null}}async function gs(n,e){if(!mt(n,e))return null;try{return await W.readFile(ht(n,e))}catch{}try{let t=await W.readFile(w.toolBlobFile(n,e));return await ls(t)}catch{return null}}async function ms(n,e,t){if(!mt(n,e))return;let s=ht(n,e);try{await W.access(s);return}catch{}await W.mkdir(w.toolsDir(n),{recursive:!0}),await W.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function hs(n){fs.test(n)&&await W.rm(w.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as Ms from"fs/promises";import*as wt from"path";import{z as C}from"zod";import*as ws from"fs";import*as V from"fs/promises";import*as we from"path";import{spawn as vs}from"child_process";import{Readable as oo}from"stream";function ae(){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 cn(n,e=ae()){if(e)return n[e]}var _e=n=>{process.stderr.write(n+`
6
- `)};function un(n){_e=n??(e=>process.stderr.write(e+`
7
- `))}async function Is(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${ae()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=ae();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=we.resolve(t,n.target.cmd);if(await dn(s))return s;if(await ao({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await dn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await V.chmod(s,493).catch(()=>{}),s}async function ao(n){await V.mkdir(we.dirname(n.installDir),{recursive:!0});let e=await V.mkdtemp(`${n.installDir}.partial-`);try{_e(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await co({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});_e(`hydra-acp: extracting ${n.agentId}`),$e(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await lo(t,e),await V.unlink(t).catch(()=>{});try{await V.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await dn(n.installDir)){await V.rm(e,{recursive:!0,force:!0}).catch(()=>{}),$e(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}_e(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),$e(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await V.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function $e(n,e){if(n)try{n(e)}catch{}}async function co(n){let e=uo(n.url),t=we.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=ws.createWriteStream(t),o=oo.fromWeb(s.body);$e(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,$e(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=f&&(d=p,_e(ys(n.agentId,a,r)))}),await new Promise((l,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>l()),o.pipe(i)}),_e(ys(n.agentId,a,r,!0)),$e(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function ys(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 uo(n){let e=new URL(n);return we.posix.basename(e.pathname)||"archive"}async function lo(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await an("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await fo("unzip")){await an("unzip",["-q",n,"-d",e]);return}await an("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function an(n,e){return new Promise((t,s)=>{let r=vs(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 fo(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=vs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function dn(n){try{return await V.access(n),!0}catch{return!1}}import*as Z from"fs/promises";import*as de from"path";import{spawn as po}from"child_process";var fn=n=>{process.stderr.write(n+`
8
- `)};function pn(n){fn=n??(e=>process.stderr.write(e+`
9
- `))}async function Ss(n){let e=ae();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=wo(n.packageSpec),r=vo(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=de.join(t,"node_modules",".bin",n.bin);if(await ke(o))return o;if(await ke(t)){let u=await bs(i);if(u)return u.binPath}await go({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await bs(i);if(a)return a.binPath;let d=await As(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 go(n){await Z.mkdir(de.dirname(n.installDir),{recursive:!0});let e=await Z.mkdtemp(`${n.installDir}.partial-`);try{fn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),ln(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await yo({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await Z.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await ke(n.installDir)){await Z.rm(e,{recursive:!0,force:!0}).catch(()=>{}),ln(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}fn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),ln(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Z.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function ln(n,e){if(n)try{n(e)}catch{}}var mo=5,ho=25;function yo(n){return ks(n,0)}async function ks(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=po("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<mo)return await new Promise(r=>setTimeout(r,ho*(e+1))),ks(n,e+1);throw t}}function wo(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 vo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function As(n,e){let t=de.join(n,"node_modules",e,"package.json");try{let s=await Z.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 bs(n){let e=de.join(n.installDir,"node_modules",".bin"),t=de.join(e,n.hint);if(await ke(t))return{binName:n.hint,binPath:t};let s=await As(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=de.join(e,i);if(await ke(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=de.join(e,i);if(await ke(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=de.join(e,n.basename);if(await ke(r))return{binName:n.basename,binPath:r}}}async function ke(n){try{return await Z.access(n),!0}catch{return!1}}var Io=C.object({package:C.string(),bin:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Fe=C.object({archive:C.string().url().optional(),cmd:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),bo=C.object({"darwin-aarch64":Fe.optional(),"darwin-x86_64":Fe.optional(),"linux-aarch64":Fe.optional(),"linux-x86_64":Fe.optional(),"windows-x86_64":Fe.optional(),"windows-aarch64":Fe.optional()}),So=C.object({package:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),ko=C.object({command:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Ao=C.object({command:C.string().optional(),url:C.string().optional(),description:C.string().optional()}),xo=C.object({npx:Io.optional(),binary:bo.optional(),uvx:So.optional(),exec:ko.optional()}),Co=C.object({id:C.string(),name:C.string(),version:C.string().optional(),description:C.string().optional(),authors:C.array(C.string()).optional(),license:C.string().optional(),icon:C.string().optional(),repository:C.string().optional(),website:C.string().optional(),distribution:xo,onboarding:Ao.optional()}),xs=C.object({version:C.string(),agents:C.array(Co),extensions:C.array(C.unknown()).optional()}),Qe=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=>gn(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=xs.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 oe(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=xs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ne(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 gn(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 Oe(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 mn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function mn(n){let e=ae();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=cn(n.distribution.binary,e);if(s?.cmd){let r=wt.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await Cs(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??gn(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=wt.join(i,"node_modules",".bin",r);if(await Cs(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Cs(n){try{return await Ms.access(n),!0}catch{return!1}}async function se(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??gn(n)??r.package,a=t.onInstallProgress;return{command:await Ss({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=cn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ae()??"this platform"}.`);let i=t.onInstallProgress,o=await Is({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 _o}from"child_process";import*as bt from"fs";import*as Ds 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 O}from"zod";var Rs=O.object({protocolVersion:O.number().optional(),clientCapabilities:O.record(O.unknown()).optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional()}),Ro=O.enum(["full","pending_only","none","after_message"]),Es=O.object({cwd:O.string(),mcpServers:O.array(O.unknown()).optional(),_meta:O.record(O.unknown()).optional()}),Ps=O.object({upstreamSessionId:O.string(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),agentArgs:O.array(O.string()).optional()}),Ts=O.object({sessionId:O.string(),historyPolicy:Ro.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 M}from"zod";var _s=M.object({sessionId:M.string()}),$s=M.object({cwd:M.string().optional(),cursor:M.string().optional()}),hn=M.object({used:M.number().optional(),size:M.number().optional(),costAmount:M.number().optional(),costCurrency:M.string().optional()}),ju=M.object({sessionId:M.string(),upstreamSessionId:M.string().optional(),cwd:M.string(),title:M.string().optional(),agentId:M.string().optional(),currentModel:M.string().optional(),currentUsage:hn.optional(),importedFromMachine:M.string().optional(),importedFromUpstreamSessionId:M.string().optional(),parentSessionId:M.string().optional(),forkedFromSessionId:M.string().optional(),forkedFromMessageId:M.string().optional(),originatingClient:M.object({name:M.string(),version:M.string().optional()}).optional(),interactive:M.boolean().optional(),priority:M.number().int().nonnegative().optional(),updatedAt:M.string(),attachedClients:M.number().int().nonnegative(),status:M.enum(["live","cold"]).default("live"),busy:M.boolean().default(!1),awaitingInput:M.boolean().default(!1),_meta:M.record(M.unknown()).optional()}),Eo=M.object({sessionId:M.string(),cwd:M.string(),title:M.string().optional(),updatedAt:M.string().optional(),_meta:M.record(M.unknown()).optional()}),Hu=M.object({sessions:M.array(Eo),nextCursor:M.string().optional()});function vt(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 Fs(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:Ve(n._meta,vt(n))};return n.title!==void 0&&(e.title=n.title),e}var Ge="hydra-acp";function Po(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function Ye(n){if(!n)return{};let e=n[Ge];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=Ps.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=hn.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}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Po(t.env);r!==void 0&&(s.env=r)}return s}function Ve(n,e){return{...n??{},[Ge]:e}}import{z as b}from"zod";var Os=b.object({sessionId:b.string(),prompt:b.array(b.unknown()),_meta:b.record(b.unknown()).optional()}),It=b.object({sessionId:b.string()}),Ns=b.object({clientId:b.string(),name:b.string().optional(),version:b.string().optional()}),Ju=b.object({sessionId:b.string(),messageId:b.string(),originator:Ns,prompt:b.array(b.unknown()),position:b.number().int().nonnegative(),queueDepth:b.number().int().positive(),enqueuedAt:b.number()}),zu=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Wu=b.object({sessionId:b.string(),messageId:b.string(),reason:b.enum(["started","cancelled","abandoned"])}),js=b.object({sessionId:b.string(),messageId:b.string()}),Qu=b.object({cancelled:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Hs=b.object({sessionId:b.string(),messageId:b.string(),prompt:b.array(b.unknown())}),Vu=b.object({updated:b.boolean(),reason:b.enum(["ok","not_found","already_running"])}),Bs=b.object({sessionId:b.string(),targetMessageId:b.string(),prompt:b.array(b.unknown()),replaceQueue:b.boolean().optional(),onTargetCompleted:b.enum(["reject","send_anyway"]).optional()}),Gu=b.object({amended:b.boolean(),reason:b.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:b.string().optional()}),Yu=b.object({sessionId:b.string(),cancelledMessageId:b.string(),newMessageId:b.string(),prompt:b.array(b.unknown()),originator:Ns,amendedAt:b.number()});import{z as ve}from"zod";var Zu=ve.object({agentId:ve.string(),version:ve.string(),source:ve.enum(["binary","npm"]),phase:ve.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ve.number().optional(),totalBytes:ve.number().optional(),packageSpec:ve.string().optional()}),Us="hydra-acp/agents/install_progress";function yn(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
- `);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(`
1
+ import*as _i from"fs";import*as Se from"fs/promises";import Gc from"fastify";import Yc from"@fastify/websocket";var Zn="acp.v1";function es(n,e){return n.has(Zn)?Zn:!1}import Ti from"pino";import Kc from"pino-roll";import*as ye from"fs/promises";import{homedir as rn}from"os";import{z as v}from"zod";import*as T from"path";import*as nn from"os";var $i="HYDRA_ACP_HOME";function Ee(n){let e=nn.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function Fi(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function $(){let n=process.env[$i];if(n&&n.length>0)return T.resolve(n);let e=Fi();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return T.join(nn.homedir(),".hydra-acp")}var w={home:$,config:()=>T.join($(),"config.json"),authToken:()=>T.join($(),"auth-token"),remotes:()=>T.join($(),"remotes.json"),pidFile:()=>T.join($(),"daemon.pid"),logFile:()=>T.join($(),"daemon.log"),currentLogFile:()=>T.join($(),"current.log"),registryCache:()=>T.join($(),"registry.json"),agentsDir:()=>T.join($(),"agents"),agentLogFile:n=>T.join($(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>T.join($(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>T.join($(),"sessions"),sessionDir:n=>T.join($(),"sessions",n),sessionFile:n=>T.join($(),"sessions",n,"meta.json"),historyFile:n=>T.join($(),"sessions",n,"history.jsonl"),toolsDir:n=>T.join($(),"sessions",n,"tools"),toolBlobFile:(n,e)=>T.join($(),"sessions",n,"tools",e),queueFile:n=>T.join($(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>T.join($(),"sessions",".tombstones"),tombstoneAgentDir:n=>T.join($(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>T.join($(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>T.join($(),"extensions"),extensionLogFile:n=>T.join($(),"extensions",`${n}.log`),extensionPidFile:n=>T.join($(),"extensions",`${n}.pid`),transformersDir:()=>T.join($(),"transformers"),transformerLogFile:n=>T.join($(),"transformers",`${n}.log`),transformerPidFile:n=>T.join($(),"transformers",`${n}.pid`),transformerState:(n,e)=>T.join($(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>T.join($(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>T.join($(),"prompt-history"),tuiLogFile:()=>T.join($(),"tui.log"),shimWireLogFile:()=>T.join($(),"shim-wire.log")};import*as Pe from"fs/promises";function mt(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function ts(){try{let e=(await Pe.readFile(w.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function Oi(){let n=await ts();if(!n)throw new Error(`No service token found at ${w.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function sn(n){await Pe.mkdir(w.home(),{recursive:!0}),await Pe.writeFile(w.authToken(),n+`
2
+ `,{encoding:"utf8",mode:384})}async function Ni(){let n=await ts();if(n)return n;let e=mt();return await sn(e),process.stderr.write(`hydra-acp: initialized ${w.authToken()} with a fresh service token.
3
+ `),e}import*as z from"fs/promises";import*as ns from"fs";import*as te from"path";import{randomBytes as ji}from"crypto";async function ne(n,e,t={}){let r=(t.pretty??!0?JSON.stringify(e,null,2):JSON.stringify(e))+`
4
+ `;await Hi(n,r,t)}async function Hi(n,e,t={}){let s=await Bi(n),r=Ui(s);await z.mkdir(r,{recursive:!0});let i=`${s}.tmp-${process.pid}-${Di()}`;try{let o={encoding:"utf8"};t.mode!==void 0&&(o.mode=t.mode),await z.writeFile(i,e,o),await z.rename(i,s)}catch(o){throw await z.unlink(i).catch(()=>{}),o}if(t.mode!==void 0)try{ns.chmodSync(s,t.mode)}catch{}}async function Bi(n){let e;try{e=await z.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await z.readlink(n),s=te.isAbsolute(t)?t:te.resolve(te.dirname(n),t);try{let r=await z.realpath(te.dirname(s));return te.join(r,te.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function oe(n){let e;try{e=await z.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 Ui(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Di(){return ji(4).toString("hex")}var rs="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Li=v.object({cert:v.string(),key:v.string()}),is=55514,qi=v.object({host:v.string().default("127.0.0.1"),port:v.number().int().positive().default(is),logLevel:v.enum(["debug","info","warn","error"]).default("info"),tls:Li.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(rs),ttlHours:v.number().positive().default(24),pinned:v.boolean().default(!1)}),zi=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()}),Wi=v.object({packageSpec:v.string().optional()}),Qi=v.object({repaintThrottleMs:v.number().int().nonnegative().default(1e3),maxScrollbackLines:v.number().int().positive().default(1e4),mouse:v.boolean().default(!0),inAppSelection:v.boolean().optional(),selectionClipboard:v.enum(["primary","clipboard","both"]).default("both"),openFileCommand:v.union([v.string(),v.array(v.string())]).optional(),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()}),ss=v.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Vi=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)}),Gi=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)}),os=v.object({daemon:qi.default({}),registry:Ji.default({url:rs,ttlHours:24,pinned:!1}),agents:v.record(v.string(),zi).default({}),agentOverrides:v.record(v.string(),Wi).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(ss,Vi).default({}),transformers:v.record(ss,Gi).default({}),defaultTransformers:v.array(v.string()).default([]),npmRegistry:v.string().url().optional(),tui:Qi.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"wide",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function as(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function ds(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function cs(){return await Yi(),await oe(w.config())??{}}async function Yi(){let n;try{n=await ye.lstat(w.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await ye.stat(w.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await ye.readlink(w.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${w.config()} is a broken symlink (-> ${t}); its target is missing. Refusing to treat this as "no config" and overwrite it. Restore the target (e.g. decrypt/check out your dotfiles) or remove the dangling link.`)}}async function Ki(){let n=await cs(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await ye.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 sn(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await ne(w.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${w.config()} to ${w.authToken()}.
5
+ `)}async function us(){return await Ki(),os.parse(await cs())}async function Xi(n){await ne(w.config(),n,{mode:384})}function Zi(){return os.parse({})}function Te(n){return n==="~"||n==="$HOME"?rn():n.startsWith("~/")?rn()+n.slice(1):n.startsWith("$HOME/")?rn()+n.slice(5):n}import*as W from"fs/promises";import{createHash as eo}from"crypto";import{gzip as to,gunzip as no}from"zlib";import{promisify as ls}from"util";var fs=ls(to),so=ls(no),ps=/^[A-Za-z0-9_-]+$/,ro=/^[a-f0-9]{64}$/,on=!0;function gs(n){on=n}function ht(n,e){return ps.test(n)?e===void 0||ro.test(e):!1}function yt(n,e){return`${w.toolBlobFile(n,e)}.gz`}async function an(n,e){if(!ht(n))return null;let t=eo("sha256").update(e,"utf8").digest("hex"),s=yt(n,t),r=w.toolBlobFile(n,t);for(let a of[s,r])try{return await W.access(a),t}catch{}await W.mkdir(w.toolsDir(n),{recursive:!0});let i=on?s:r,o=on?await fs(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await W.writeFile(i,o,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function wt(n,e){if(!ht(n,e))return null;try{let t=await W.readFile(yt(n,e));return(await so(t)).toString("utf8")}catch{}try{return await W.readFile(w.toolBlobFile(n,e),"utf8")}catch{return null}}async function ms(n,e){if(!ht(n,e))return null;try{return await W.readFile(yt(n,e))}catch{}try{let t=await W.readFile(w.toolBlobFile(n,e));return await fs(t)}catch{return null}}async function hs(n,e,t){if(!ht(n,e))return;let s=yt(n,e);try{await W.access(s);return}catch{}await W.mkdir(w.toolsDir(n),{recursive:!0}),await W.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function ys(n){ps.test(n)&&await W.rm(w.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as Rs from"fs/promises";import*as vt from"path";import{z as C}from"zod";import*as vs from"fs";import*as V from"fs/promises";import*as we from"path";import{spawn as Is}from"child_process";import{Readable as io}from"stream";function ae(){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 un(n,e=ae()){if(e)return n[e]}var _e=n=>{process.stderr.write(n+`
6
+ `)};function ln(n){_e=n??(e=>process.stderr.write(e+`
7
+ `))}async function bs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${ae()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=ae();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=we.resolve(t,n.target.cmd);if(await cn(s))return s;if(await oo({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await cn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await V.chmod(s,493).catch(()=>{}),s}async function oo(n){await V.mkdir(we.dirname(n.installDir),{recursive:!0});let e=await V.mkdtemp(`${n.installDir}.partial-`);try{_e(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ao({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});_e(`hydra-acp: extracting ${n.agentId}`),$e(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await uo(t,e),await V.unlink(t).catch(()=>{});try{await V.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await cn(n.installDir)){await V.rm(e,{recursive:!0,force:!0}).catch(()=>{}),$e(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}_e(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),$e(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await V.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function $e(n,e){if(n)try{n(e)}catch{}}async function ao(n){let e=co(n.url),t=we.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=vs.createWriteStream(t),o=io.fromWeb(s.body);$e(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,d=Date.now(),c=0,l=2e3,u=150;return o.on("data",f=>{a+=f.length;let p=Date.now();p-c>=u&&(c=p,$e(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),p-d>=l&&(d=p,_e(ws(n.agentId,a,r)))}),await new Promise((f,p)=>{o.on("error",p),i.on("error",p),i.on("finish",()=>f()),o.pipe(i)}),_e(ws(n.agentId,a,r,!0)),$e(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function ws(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 co(n){let e=new URL(n);return we.posix.basename(e.pathname)||"archive"}async function uo(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await dn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await lo("unzip")){await dn("unzip",["-q",n,"-d",e]);return}await dn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function dn(n,e){return new Promise((t,s)=>{let r=Is(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 lo(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Is(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function cn(n){try{return await V.access(n),!0}catch{return!1}}import*as Z from"fs/promises";import*as de from"path";import{spawn as fo}from"child_process";var pn=n=>{process.stderr.write(n+`
8
+ `)};function gn(n){pn=n??(e=>process.stderr.write(e+`
9
+ `))}async function ks(n){let e=ae();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=yo(n.packageSpec),r=wo(s),i={installDir:t,packageName:s,hint:n.bin,basename:r},o=de.join(t,"node_modules",".bin",n.bin);if(await ke(o))return o;if(await ke(t)){let u=await Ss(i);if(u)return u.binPath}await po({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await Ss(i);if(a)return a.binPath;let d=await xs(t,s),c=typeof d=="object"&&d!==null?Object.keys(d):typeof d=="string"?[r]:[],l=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/)${l}`)}async function po(n){await Z.mkdir(de.dirname(n.installDir),{recursive:!0});let e=await Z.mkdtemp(`${n.installDir}.partial-`);try{pn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),fn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ho({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await Z.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await ke(n.installDir)){await Z.rm(e,{recursive:!0,force:!0}).catch(()=>{}),fn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}pn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),fn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await Z.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function fn(n,e){if(n)try{n(e)}catch{}}var go=5,mo=25;function ho(n){return As(n,0)}async function As(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],i;try{i=fo("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"}`,l=o.trim();s(new Error(l?`npm install ${n.packageSpec} failed (${c})
10
+ stderr: ${l}`:`npm install ${n.packageSpec} failed (${c})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<go)return await new Promise(r=>setTimeout(r,mo*(e+1))),As(n,e+1);throw t}}function yo(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 wo(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function xs(n,e){let t=de.join(n,"node_modules",e,"package.json");try{let s=await Z.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 Ss(n){let e=de.join(n.installDir,"node_modules",".bin"),t=de.join(e,n.hint);if(await ke(t))return{binName:n.hint,binPath:t};let s=await xs(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let i=r[0],o=de.join(e,i);if(await ke(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=de.join(e,i);if(await ke(o))return{binName:i,binPath:o}}}}if(n.basename!==n.hint){let r=de.join(e,n.basename);if(await ke(r))return{binName:n.basename,binPath:r}}}async function ke(n){try{return await Z.access(n),!0}catch{return!1}}var vo=C.object({package:C.string(),bin:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Fe=C.object({archive:C.string().url().optional(),cmd:C.string().optional(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),Io=C.object({"darwin-aarch64":Fe.optional(),"darwin-x86_64":Fe.optional(),"linux-aarch64":Fe.optional(),"linux-x86_64":Fe.optional(),"windows-x86_64":Fe.optional(),"windows-aarch64":Fe.optional()}),bo=C.object({package:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),So=C.object({command:C.string(),args:C.array(C.string()).optional(),env:C.record(C.string()).optional()}),ko=C.object({command:C.string().optional(),url:C.string().optional(),description:C.string().optional()}),Ao=C.object({npx:vo.optional(),binary:Io.optional(),uvx:bo.optional(),exec:So.optional()}),xo=C.object({id:C.string(),name:C.string(),version:C.string().optional(),description:C.string().optional(),authors:C.array(C.string()).optional(),license:C.string().optional(),icon:C.string().optional(),repository:C.string().optional(),website:C.string().optional(),distribution:Ao,onboarding:ko.optional()}),Cs=C.object({version:C.string(),agents:C.array(xo),extensions:C.array(C.unknown()).optional()}),Qe=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=>mn(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:Co(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=Cs.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 oe(w.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=Cs.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await ne(w.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Co(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 mn(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 Oe(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 hn(o),source:s.has(o.id)?"local":"registry",...o.onboarding?{onboarding:o.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:i}}async function hn(n){let e=ae();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=un(n.distribution.binary,e);if(s?.cmd){let r=vt.resolve(w.agentInstallDir(n.id,e,t),s.cmd);if(await Ms(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??mn(n)??s.package,i=w.agentNpmInstallDir(n.id,e,t),o=vt.join(i,"node_modules",".bin",r);if(await Ms(o))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function Ms(n){try{return await Rs.access(n),!0}catch{return!1}}async function se(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??mn(n)??r.package,a=t.onInstallProgress;return{command:await ks({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=un(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${ae()??"this platform"}.`);let i=t.onInstallProgress,o=await bs({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 To}from"child_process";import*as St from"fs";import*as Ls 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 O}from"zod";var Es=O.object({protocolVersion:O.number().optional(),clientCapabilities:O.record(O.unknown()).optional(),clientInfo:O.object({name:O.string(),version:O.string().optional()}).optional()}),Mo=O.enum(["full","pending_only","none","after_message"]),Ps=O.object({cwd:O.string(),mcpServers:O.array(O.unknown()).optional(),_meta:O.record(O.unknown()).optional()}),Ts=O.object({upstreamSessionId:O.string(),agentId:O.string(),cwd:O.string(),title:O.string().optional(),agentArgs:O.array(O.string()).optional()}),_s=O.object({sessionId:O.string(),historyPolicy:Mo.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 M}from"zod";var $s=M.object({sessionId:M.string()}),Fs=M.object({cwd:M.string().optional(),cursor:M.string().optional()}),yn=M.object({used:M.number().optional(),size:M.number().optional(),costAmount:M.number().optional(),costCurrency:M.string().optional()}),Hu=M.object({sessionId:M.string(),upstreamSessionId:M.string().optional(),cwd:M.string(),title:M.string().optional(),agentId:M.string().optional(),currentModel:M.string().optional(),currentUsage:yn.optional(),importedFromMachine:M.string().optional(),importedFromUpstreamSessionId:M.string().optional(),parentSessionId:M.string().optional(),forkedFromSessionId:M.string().optional(),forkedFromMessageId:M.string().optional(),originatingClient:M.object({name:M.string(),version:M.string().optional()}).optional(),interactive:M.boolean().optional(),priority:M.number().int().nonnegative().optional(),updatedAt:M.string(),attachedClients:M.number().int().nonnegative(),status:M.enum(["live","cold"]).default("live"),busy:M.boolean().default(!1),awaitingInput:M.boolean().default(!1),_meta:M.record(M.unknown()).optional()}),Ro=M.object({sessionId:M.string(),cwd:M.string(),title:M.string().optional(),updatedAt:M.string().optional(),_meta:M.record(M.unknown()).optional()}),Bu=M.object({sessions:M.array(Ro),nextCursor:M.string().optional()});function It(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 Os(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:Ve(n._meta,It(n))};return n.title!==void 0&&(e.title=n.title),e}var Ge="hydra-acp";function Eo(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function Ye(n){if(!n)return{};let e=n[Ge];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=Ts.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=yn.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}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Eo(t.env);r!==void 0&&(s.env=r)}return s}function Ve(n,e){return{...n??{},[Ge]:e}}import{z as S}from"zod";var Ns=S.object({sessionId:S.string(),prompt:S.array(S.unknown()),_meta:S.record(S.unknown()).optional()}),bt=S.object({sessionId:S.string()}),js=S.object({clientId:S.string(),name:S.string().optional(),version:S.string().optional()}),zu=S.object({sessionId:S.string(),messageId:S.string(),originator:js,prompt:S.array(S.unknown()),position:S.number().int().nonnegative(),queueDepth:S.number().int().positive(),enqueuedAt:S.number()}),Wu=S.object({sessionId:S.string(),messageId:S.string(),prompt:S.array(S.unknown())}),Qu=S.object({sessionId:S.string(),messageId:S.string(),reason:S.enum(["started","cancelled","abandoned"])}),Hs=S.object({sessionId:S.string(),messageId:S.string()}),Vu=S.object({cancelled:S.boolean(),reason:S.enum(["ok","not_found","already_running"])}),Bs=S.object({sessionId:S.string(),messageId:S.string(),prompt:S.array(S.unknown())}),Gu=S.object({updated:S.boolean(),reason:S.enum(["ok","not_found","already_running"])}),Us=S.object({sessionId:S.string(),targetMessageId:S.string(),prompt:S.array(S.unknown()),replaceQueue:S.boolean().optional(),onTargetCompleted:S.enum(["reject","send_anyway"]).optional()}),Yu=S.object({amended:S.boolean(),reason:S.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:S.string().optional()}),Ku=S.object({sessionId:S.string(),cancelledMessageId:S.string(),newMessageId:S.string(),prompt:S.array(S.unknown()),originator:js,amendedAt:S.number()});import{z as ve}from"zod";var el=ve.object({agentId:ve.string(),version:ve.string(),source:ve.enum(["binary","npm"]),phase:ve.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ve.number().optional(),totalBytes:ve.number().optional(),packageSpec:ve.string().optional()}),Ds="hydra-acp/agents/install_progress";function wn(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
+ `);for(;d!==-1;){let c=t.slice(0,d).trim();if(t=t.slice(d+1),c.length>0)try{let l=JSON.parse(c);for(let u of s)u(l)}catch(l){for(let u of s)u({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse ndjson line: ${l.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 To}from"nanoid";var wn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Ae=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 wn;let s=To(),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 $o=4096,pe=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??$o,this.killEscalationMs=e.killEscalationMs??Fo,this.logger=e.logger,this.fileLog=Oo(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=yn(t.stdout,t.stdin);this.connection=new Ae(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,l)=>{e.write(d,u=>{if(u){l(u);return}c()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),o()}}}import{nanoid as Po}from"nanoid";var vn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Ae=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 vn;let s=Po(),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 _o=4096,pe=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??_o,this.killEscalationMs=e.killEscalationMs??$o,this.logger=e.logger,this.fileLog=Fo(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=wn(t.stdout,t.stdin);this.connection=new Ae(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=_o(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=To(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)})}},Fo=2e3;function Oo(n){try{let e=w.agentLogFile(n);bt.mkdirSync(Ds.dirname(e),{recursive:!0});let t=bt.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Me from"fs/promises";import*as _t from"os";import*as it from"path";import{customAlphabet as Qa}from"nanoid";import{customAlphabet as Ys}from"nanoid";import*as qs from"fs/promises";var No=64*1024*1024,jo=1*1024*1024,Ne=64*1024,Ho=6e4,Bo=100,Uo=1e3,Do=64*1024,Lo=256*1024,Ls=20;function qo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var St=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??No,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(jo,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,Ne));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,Ne)),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,Ne)),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,Ho));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(qo(e.pattern),d),f=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Bo,Uo)),l=Math.max(1,Math.min(e.maxBytes??Do,Lo)),p=Math.max(0,Math.min(e.contextBefore??0,Ls)),g=Math.max(0,Math.min(e.contextAfter??0,Ls)),m=[],h=[],y=[],k=0,S=!1,A=0,N=0,H=(R,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:R,line:P}),D.remaining--,k+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==f&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let he of D.before)k+=he.line.length}k+=P.length,m.push(D),g>0&&y.push({match:D,remaining:g})}if(p>0)for(h.push({cursor:R,line:P});h.length>p;)h.shift();let B=m.length>=u&&y.length===0,q=k>=l;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(A,R).toString("utf8"),j=r+A;if(A=R+1,N=A,H(j,P)){S=!0;break}}if(!S&&A<o.length&&this.closed){let R=o.subarray(A).toString("utf8"),P=r+A;H(P,R)&&(S=!0),N=o.length}let X=Math.min(r+N,this.writeCursor),J={matches:m,truncated:S,nextCursor:X,scannedBytes:N};return i>0&&(J.gap=i),this.closed&&X>=this.writeCursor&&(J.eof=!0),J}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(()=>qs.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var kt=[{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."}],vl=new Map(kt.map(n=>[n.verb,n]));function Js(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function je(n,e){return vn(n,e.map(t=>t.modelId))}function vn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=Js(n),s=e.filter(i=>Js(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function zs(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=In(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=In(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?zo(r,i.outIndex,Jo(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)?Wo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Qo(l)&&(l=Vo(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 In(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Jo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function zo(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 Wo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Qo(n){let t=In(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Vo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ce from"fs/promises";async function Ke(n,e){let t=w.queueFile(n);if(e.length===0){await ce.unlink(t).catch(()=>{});return}await ce.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)})}},$o=2e3;function Fo(n){try{let e=w.agentLogFile(n);St.mkdirSync(Ls.dirname(e),{recursive:!0});let t=St.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Me from"fs/promises";import*as $t from"os";import*as it from"path";import{customAlphabet as Wa}from"nanoid";import{customAlphabet as Ks}from"nanoid";import*as Js from"fs/promises";var Oo=64*1024*1024,No=1*1024*1024,Ne=64*1024,jo=6e4,Ho=100,Bo=1e3,Uo=64*1024,Do=256*1024,qs=20;function Lo(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var kt=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??Oo,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(No,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,Ne));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),l={bytes:this.sliceFromRing(r,d),nextCursor:r+d};return i>0&&(l.gap=i),this.closed&&r+d>=this.writeCursor&&(l.eof=!0),l}tail(e){let t=Math.max(0,Math.min(e,Ne)),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,Ne)),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,jo));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(Lo(e.pattern),d),l=e.invert??!1,u=Math.max(1,Math.min(e.maxMatches??Ho,Bo)),f=Math.max(1,Math.min(e.maxBytes??Uo,Do)),p=Math.max(0,Math.min(e.contextBefore??0,qs)),g=Math.max(0,Math.min(e.contextAfter??0,qs)),m=[],h=[],y=[],A=0,k=!1,b=0,N=0,j=(R,P)=>{for(let D of y)D.remaining>0&&(D.match.after===void 0&&(D.match.after=[]),D.match.after.push({cursor:R,line:P}),D.remaining--,A+=P.length);for(;y.length>0&&y[0].remaining===0;)y.shift();if(c.test(P)!==l&&m.length<u){let D={cursor:R,line:P};if(p>0&&h.length>0){D.before=h.slice();for(let he of D.before)A+=he.line.length}A+=P.length,m.push(D),g>0&&y.push({match:D,remaining:g})}if(p>0)for(h.push({cursor:R,line:P});h.length>p;)h.shift();let B=m.length>=u&&y.length===0,q=A>=f;return B||q};for(let R=0;R<o.length;R++){if(o[R]!==10)continue;let P=o.subarray(b,R).toString("utf8"),H=r+b;if(b=R+1,N=b,j(H,P)){k=!0;break}}if(!k&&b<o.length&&this.closed){let R=o.subarray(b).toString("utf8"),P=r+b;j(P,R)&&(k=!0),N=o.length}let K=Math.min(r+N,this.writeCursor),J={matches:m,truncated:k,nextCursor:K,scannedBytes:N};return i>0&&(J.gap=i),this.closed&&K>=this.writeCursor&&(J.eof=!0),J}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(()=>Js.appendFile(t,r)).catch(o=>{this.logWriteError?.(o)}),i&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var At=[{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(At.map(n=>[n.verb,n]));function zs(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function je(n,e){return In(n,e.map(t=>t.modelId))}function In(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=zs(n),s=e.filter(i=>zs(i)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let i=e.filter(o=>o.toLowerCase().includes(r));if(i.length===1)return{kind:"resolved",modelId:i[0],requested:n};if(i.length>1)return{kind:"ambiguous",requested:n,candidates:i}}return{kind:"unknown",requested:n}}function Ws(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=bn(d);if(c?.sessionUpdate!=="tool_call_update")continue;let l=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(l!==void 0&&(e.set(l,a),c.rawInput&&typeof c.rawInput=="object"&&!Array.isArray(c.rawInput)&&Object.keys(c.rawInput).length>0&&s.set(l,c.rawInput),Array.isArray(c.content)&&c.content.length>0)){let u=t.get(l);u?u.push(...c.content):t.set(l,[...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=bn(d);if(!c||typeof c.sessionUpdate!="string"){r.push(d),i=null;continue}let l=c.sessionUpdate;if(l==="agent_message_chunk"||l==="agent_thought_chunk"||l==="user_message_chunk"){i&&i.kind===l?Jo(r,i.outIndex,qo(c.content)):(r.push(d),i={outIndex:r.length-1,kind:l});continue}if(i=null,l==="tool_call_update"){let u=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(u!==void 0&&e.get(u)!==a)continue;let f=u!==void 0&&t.has(u)?zo(d,t.get(u)??[]):d;u!==void 0&&s.has(u)&&!Wo(f)&&(f=Qo(f,s.get(u))),r.push(f);continue}if(l==="plan"){o!==null?r[o]=d:(r.push(d),o=r.length-1);continue}(l==="prompt_received"||l==="turn_complete")&&(o=null),r.push(d)}return r}function bn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function qo(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Jo(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 zo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function Wo(n){let t=bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Qo(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}import*as ce from"fs/promises";async function Ke(n,e){let t=w.queueFile(n);if(e.length===0){await ce.unlink(t).catch(()=>{});return}await ce.mkdir(w.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
20
20
  `)+`
21
- `;await ce.writeFile(t,s,"utf8")}async function Ws(n){let e=w.queueFile(n),t;try{t=await ce.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 ce.unlink(e).catch(()=>{})}import*as er from"fs/promises";var Ks="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Xs=Ys(Ks,16),Vs=Ys(Ks,16),ge="hydra_session_";function He(){return`m_${Xs()}`}function Zs(n){return n.startsWith(ge)?n.slice(ge.length):n}var Go=1e3,bn=300*1e3,Yo=64,xe=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;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},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??`${ge}${Xs()}`,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.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Go,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){sa(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_${Vs()}`,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,g=i,m=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(g,new Set([...m,c.name]),p+1).then(()=>h()).catch(()=>h()))},bn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:m,side:"response"})});return}t.add(c.name)}let o=ra(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=na(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 K(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw K(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:zs(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?kn(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 K(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw K(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=He();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ye((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=Be(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:He()};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>Yo;){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 K(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=He(),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=He(),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 K(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_${Vs()}`,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??Sn(e);if(l==="processing"){let p=a,g=o,m=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,g,new Set([...m,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:Sn(e))))},bn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(f,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:m,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):bn,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:Sn(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=Be((e??{}).prompt),r=An(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=Ue(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=Ue(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=Xe(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=Ue(o.options);if(d.length>0){let c=Xe(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,g=typeof p=="string"&&p.trim()?p.trim():f[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=f,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:l,category:"other",type:"select",currentValue:g,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(Zo(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(ea(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(",")}]`),ta(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(kt.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=kt.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(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},f=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let u,l=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,f]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return l=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.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 ce.writeFile(t,s,"utf8")}async function Qs(n){let e=w.queueFile(n),t;try{t=await ce.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 Vs(n){let e=w.queueFile(n);await ce.unlink(e).catch(()=>{})}import*as tr from"fs/promises";var Xs="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Zs=Ks(Xs,16),Gs=Ks(Xs,16),ge="hydra_session_";function He(){return`m_${Zs()}`}function er(n){return n.startsWith(ge)?n.slice(ge.length):n}var Vo=1e3,Sn=300*1e3,Go=64,xe=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;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},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??`${ge}${Zs()}`,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.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??Vo,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){na(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 l=`t_${Gs()}`,u;try{u=await c.connection.request("hydra-acp/transformer/message",{token:l,phase:"response",method:"session/update",direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(p){this.logger?.warn(`transformer ${c.name} error on response:session/update: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return;if(f==="processing"){let p=d,g=i,m=new Set(t);await new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:c.name}),this.runResponseChain(g,new Set([...m,c.name]),p+1).then(()=>h()).catch(()=>h()))},Sn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(l,{resolve:()=>h(),timer:y,transformerName:c.name,method:"session/update",envelope:g,chainIdx:p,originatedBy:m,side:"response"})});return}t.add(c.name)}let o=sa(i);if(o!==null){this.setAgentAdvertisedCommands(o);return}let a=ta(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:Ws(o),r=await this.getHistorySnapshot(t.toolContent??"inline"),i=this.buildStateSnapshotReplay();if(e==="after_message"){let o=t.afterMessageId?An(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=He();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(Ye((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=Be(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:He()};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>Go;){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(l=>l.messageId===r&&l.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=He(),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=He(),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 l=`t_${Gs()}`,u;try{u=await d.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${d.name} error on ${c}: ${p.message}`);continue}let f=u?.action??"continue";if(f==="stop")return i==="notification"?void 0:u?.payload??kn(e);if(f==="processing"){let p=a,g=o,m=new Set(s);return new Promise(h=>{let y=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:d.name}),this.forwardRequest(e,g,new Set([...m,d.name]),p+1,i).then(h).catch(()=>h(i==="notification"?void 0:kn(e))))},Sn);typeof y.unref=="function"&&y.unref(),this.pendingClaims.set(l,{resolve:h,timer:y,transformerName:d.name,method:e,envelope:g,chainIdx:p,originatedBy:m,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):Sn,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:kn(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=Be((e??{}).prompt),r=xn(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=Ue(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=Ue(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=Xe(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=Ue(o.options);if(d.length>0){let c=Xe(o.options),l=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,f=typeof u=="string"&&u.trim()?u.trim():a,p=o.currentValue,g=typeof p=="string"&&p.trim()?p.trim():l[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=l,typeof p=="string"&&p.trim()&&(h.currentValue=p.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:f,category:"other",type:"select",currentValue:g,options:l})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let i=r.trim();if(!i||i===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(i)}`),this.currentMode=i;for(let o of this.modeHandlers)try{o(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},i=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,i=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,i=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,i=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,i=!0)}if(!i)return!0;this._currentUsage=r;let o=this.currentUsage??r;for(let a of this.usageHandlers)try{a(o)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;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(Xo(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(",")}]`),ea(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}`,l={name:s.argsHint?`${d} ${s.argsHint}`:d};s.description&&(l.description=s.description),e.push(l)}}}return e.push(...this.agentAdvertisedCommands),e}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let i of this.titleHandlers)try{i(r)}catch{}}}async handleSlashCommand(e,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(At.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=At.map(u=>u.verb);if(this.extensionCommands){let u=new Set;for(let{name:f}of this.extensionCommands.list())u.has(f)||(c.push(f),u.add(f))}let l=new Error(`unknown /hydra verb: ${i} (known: ${c.join(", ")})`);throw l.code=I.InvalidParams,l}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let i=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),o=i?.[1]??"",a=(i?.[2]??"").trim();if(!r.commands.some(g=>g.verb===o)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${o?` ${o}`:""}: unknown verb (known: ${g||"(none)"})`)}let d={sessionId:this.sessionId,verb:o,args:a};s!==void 0&&(d.messageId=s);let c=()=>{},l=new Promise(g=>{c=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>c({stopReason:"cancelled",reason:g})});let u,f=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",d),m=await Promise.race([g,l]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return f=!0,this.logger?.info(`extension ${e} ${o} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};u=m}catch(g){return this.emitExtensionReply(`${e} ${o}: ${g.message}`)}finally{s!==void 0&&!f&&this.inFlightExtensionDispatches.delete(s)}let p=u&&typeof u=="object"&&typeof u.text=="string"?u.text:"";return p.length>0?this.emitExtensionReply(p):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
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(`
@@ -29,40 +29,40 @@ ${e}
29
29
  ${t.join(`
30
30
  `)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
31
31
  ${s}
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(`
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(l=>l.modelId===o):!0,c=i.map(l=>{let u=l.modelId===o?"\u25B6 ":" ",f=l.name&&l.name!==l.modelId?` ${l.name}`:"";return`${u}${l.modelId}${f}`});!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=je(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),d=a.length>0?a:i,c=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,f=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
35
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=je(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let i=this.agentAdvertisedModels.map(u=>u.modelId),o=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:i.filter(u=>u.toLowerCase().includes(o)),d=a.length>0?a:i,c=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,l=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
36
36
  ${c}.
37
- ${f}:
37
+ ${l}:
38
38
  ${d.join(`
39
39
  `)}
40
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let f=c.id===i?"\u25B6 ":" ",u=c.name&&c.name!==c.id?` ${c.name}`:"";return`${f}${c.id}${u}`});!a&&i&&d.unshift(`\u25B6 ${i}`),o=d.join(`
40
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,i=this.currentMode,o;if(r.length===0)o=i?`Current mode: ${i}`:"_(no modes advertised yet)_";else{let a=i?r.some(c=>c.id===i):!0,d=r.map(c=>{let l=c.id===i?"\u25B6 ":" ",u=c.name&&c.name!==c.id?` ${c.name}`:"";return`${l}${c.id}${u}`});!a&&i&&d.unshift(`\u25B6 ${i}`),o=d.join(`
41
41
  `)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
42
42
  ${o}
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 K(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 f=this.buildConfigOptions();if(f.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
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 l=this.buildConfigOptions();if(l.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 u=f.map(l=>Gs(l));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 u=l.map(f=>Ys(f));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
46
46
  ${u.join(`
47
47
 
48
48
  `)}
49
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(f=>f.id===s);if(!o){let f=i.map(u=>u.id).join(`
49
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let i=this.buildConfigOptions(),o=i.find(l=>l.id===s);if(!o){let l=i.map(u=>u.id).join(`
50
50
  `);return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
51
51
  "${s}" is not a known config option.
52
52
  Available options:
53
- ${f}
53
+ ${l}
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
- ${Gs(o)}
56
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(f=>f.value),d=vn(r,a),c=r;if(d.kind==="resolved")c=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let f=r.toLowerCase(),u=d.kind==="ambiguous"?d.candidates:a.filter(m=>m.toLowerCase().includes(f)),l=u.length>0?u:a,p=d.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${d.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,g=d.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
55
+ ${Ys(o)}
56
+ `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=o.options.map(l=>l.value),d=In(r,a),c=r;if(d.kind==="resolved")c=d.modelId;else if(d.kind==="ambiguous"||d.kind==="unknown"){let l=r.toLowerCase(),u=d.kind==="ambiguous"?d.candidates:a.filter(m=>m.toLowerCase().includes(l)),f=u.length>0?u:a,p=d.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${d.candidates.join(", ")}`:u.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,g=d.kind==="ambiguous"||u.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
57
57
  ${p}.
58
58
  ${g}:
59
- ${l.join(`
59
+ ${f.join(`
60
60
  `)}
61
- `},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(c!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:c}),this.applyModelChange(c),{stopReason:"end_turn"}):s==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):s==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:c}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[]};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 K(new Error("/hydra agent requires an agent id"),I.InvalidParams);if(e===this.agentId)throw K(new Error(`already on agent ${e}`),I.InvalidParams);if(!this.spawnReplacementAgent)throw K(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.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let 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 K(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 K(new Error("session is closing"),I.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let 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 g=Be(u.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let g=u.status,m=u.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${g}`})}}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 St(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??Ne,Ne)),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(()=>er.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=!Xo(e,r),o=i?ia(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 K(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=oa(s);return new Promise((i,o)=>{let a=!1,d=[],c=0,f,u={addClient:m};this.inFlightPermissions.add(u);let l=this.sessionId,p=h=>{a||(a=!0,this.inFlightPermissions.delete(u),h())},g=h=>h?.code===I.MethodNotFound;function m(h){if(a)return;let y=h.connection.request("session/request_permission",s);d.push({client:h}),c++,y.then(k=>{c--,p(()=>{let S=aa({toolCallId:r,result:k,resolver:h});for(let A of d)A.client.clientId!==h.clientId&&A.client.connection.notify("session/update",{sessionId:l,update:S}).catch(()=>{});i(k)})}).catch(k=>{if(c--,g(k)||(f=k),c===0&&!a){let S=f??K(new Error("no client handled permission request"),I.PermissionDenied);p(()=>o(S))}})}for(let h of t)m(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:He(),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(()=>Ke(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=Be(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 K(n,e){return n.code=e,n}var Ko=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function Xo(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Ko.has(s)}function Zo(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 ea(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 ta(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 Ue(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 Xe(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 na(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 sa(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 ra(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 ia(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:He()}}}function kn(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 oa(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 aa(n){let e=da(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=ca(n.resolver),t}function da(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 ca(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 Be(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Sn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Gs(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 s==="model"?(c!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:c}),this.applyModelChange(c),{stopReason:"end_turn"}):s==="mode"?(c!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:c}),this.applyModeChange(c),{stopReason:"end_turn"}):s==="agent"?(c!==this.agentId&&await this.runAgentCommandInline(c),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:c}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[]};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.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(i.agent);let o=this.agent;this.agent=i.agent,this.agentId=e,this.upstreamSessionId=i.upstreamSessionId,this.agentMeta=i.agentMeta,this.agentCapabilities=i.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=i.initialModel,this.currentMode=i.initialMode,this.setAgentAdvertisedModels(i.initialModels??[]),this.setAgentAdvertisedModes(i.initialModes??[]),await o.kill().catch(()=>{}),r&&await this.runInternalPrompt(r).catch(()=>{}),this.broadcastAgentSwitch(s,e);let a={agentId:this.agentId,upstreamSessionId:this.upstreamSessionId};for(let 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.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let i=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await i.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let o={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(o)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let 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 g=Be(u.prompt);g&&s.push({speaker:"user",text:g})}else if(p==="agent_message_chunk"){let m=u.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(p==="tool_call"||p==="tool_call_update"){let g=u.status,m=u.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${g}`})}}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 kt(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??Ne,Ne)),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(()=>Vs(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(()=>tr.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=!Ko(e,r),o=i?ra(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=ia(s);return new Promise((i,o)=>{let a=!1,d=[],c=0,l,u={addClient:m};this.inFlightPermissions.add(u);let f=this.sessionId,p=h=>{a||(a=!0,this.inFlightPermissions.delete(u),h())},g=h=>h?.code===I.MethodNotFound;function m(h){if(a)return;let y=h.connection.request("session/request_permission",s);d.push({client:h}),c++,y.then(A=>{c--,p(()=>{let k=oa({toolCallId:r,result:A,resolver:h});for(let b of d)b.client.clientId!==h.clientId&&b.client.connection.notify("session/update",{sessionId:f,update:k}).catch(()=>{});i(A)})}).catch(A=>{if(c--,g(A)||(l=A),c===0&&!a){let k=l??X(new Error("no client handled permission request"),I.PermissionDenied);p(()=>o(k))}})}for(let h of t)m(h)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:He(),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},l=this.insertEntryAt(c,o);this.persistRewrite(),this.broadcastQueueAdded(c,{position:l}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r.afterMessageId;if(typeof i=="string"&&i.length>0)return{afterMessageId:i}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,i=this.promptQueue.findIndex(o=>o.messageId===r);if(i>=0)return this.promptQueue.splice(i+1,0,e),s+i+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Ke(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=Be(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 Yo=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update"]);function Ko(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&Yo.has(s)}function Xo(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 ea(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 Ue(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 Xe(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 ta(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 na(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 sa(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 ra(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:He()}}}function An(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 ia(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 oa(n){let e=aa(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=da(n.resolver),t}function aa(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 da(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 Be(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function kn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function Ys(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 An(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 De from"fs/promises";import*as Ol from"path";import{customAlphabet as fa}from"nanoid";import{z as x}from"zod";import{z as re}from"zod";var Ze=re.object({goal:re.string().optional(),outcome:re.string().optional(),files_touched:re.array(re.string()).optional(),tools_used:re.array(re.string()).optional(),rejected_approaches:re.array(re.string()).optional(),open_threads:re.array(re.string()).optional()}),ua=200,xn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
65
+ `)}`}function xn(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 De from"fs/promises";import*as Nl from"path";import{customAlphabet as la}from"nanoid";import{z as x}from"zod";import{z as re}from"zod";var Ze=re.object({goal:re.string().optional(),outcome:re.string().optional(),files_touched:re.array(re.string()).optional(),tools_used:re.array(re.string()).optional(),rejected_approaches:re.array(re.string()).optional(),open_threads:re.array(re.string()).optional()}),ca=200,Cn=`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 nr(n){let e=n.trim();if(e.length===0)return;let t=tr(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(t=tr(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,ua))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Ze.safeParse(s.synopsis);i.success&&la(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function tr(n){try{return JSON.parse(n)}catch{return}}function la(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 pa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ga=fa(pa,16),ma="hydra_lineage_";function et(){return`${ma}${ga()}`}var Mn=x.object({name:x.string(),description:x.string().optional()}),Rn=x.object({id:x.string(),name:x.string().optional(),description:x.string().optional()}),ha=x.object({modelId:x.string(),name:x.string().optional(),description:x.string().optional()}),En=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional(),cumulativeCost:x.number().optional()}),Pn=x.object({name:x.string(),version:x.string().optional()}),ya=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:Ze.optional(),summarizedThroughEntry:x.number().int().nonnegative().optional(),agentArgs:x.array(x.string()).optional(),currentModel:x.string().optional(),currentMode:x.string().optional(),currentUsage:En.optional(),agentCommands:x.array(Mn).optional(),agentModes:x.array(Rn).optional(),agentModels:x.array(ha).optional(),pendingHistorySync:x.boolean().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:Pn.optional(),interactive:x.boolean().optional(),priority:x.number().int().nonnegative().optional(),forwardedEnv:x.record(x.string(),x.string()).optional(),createdAt:x.string(),updatedAt:x.string()}),Cn=/^[A-Za-z0-9_-]+$/;function wa(n){if(!Cn.test(n))throw new Error(`unsafe session id: ${n}`)}var At=class{async write(e){wa(e.sessionId);let t={version:1,...e};await ne(w.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Cn.test(e))return;let t=await oe(w.sessionFile(e));if(t!==void 0)try{return ya.parse(t)}catch{return}}async delete(e){if(Cn.test(e)){try{await De.unlink(w.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await De.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 De.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 Tn(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,forwardedEnv:n.forwardedEnv,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as me from"fs/promises";import{z as ue}from"zod";var va=ue.object({version:ue.literal(1),agentId:ue.string(),upstreamSessionId:ue.string(),deletedAt:ue.string(),upstreamUpdatedAt:ue.string().optional(),cwd:ue.string().optional(),title:ue.string().optional(),reason:ue.enum(["user","expired"]).optional(),interactive:ue.boolean().optional()}),xt=class{async add(e){let t={version:1,...e};await ne(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 oe(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 va.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 sr(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as pr from"fs/promises";import{fileURLToPath as Ia}from"url";import*as tt from"path";import*as Ct from"fs";function ba(){try{let n=tt.dirname(Ia(import.meta.url));for(let e=0;e<8;e+=1){let t=tt.join(n,"package.json");if(Ct.existsSync(t)){let r=JSON.parse(Ct.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=tt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var G=ba(),Mt="hydra-acp-cat";var rr=`[older history truncated]
76
- `,Sa=["file_path","path","command","pattern","query"];function ir(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=Ca(d.prompt).trim();f.length>0&&s.push(`User: ${f}`)}else if(c==="agent_message_chunk"){let f=Ma(d.content);f.length>0&&(r+=f)}else c==="tool_call"?(i(),s.push(ka(d))):c==="turn_complete"&&i()}return i(),Ea(s.join(`
77
- `),t)}function ka(n){let e=Aa(n),t=xa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Aa(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function xa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Sa){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Ra(r,200)}`)}return t}function Ca(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 Ma(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Ra(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Ea(n,e){if(n.length<=e)return n;let t=n.split(`
78
- `);for(;t.length>0;){let s=rr+t.join(`
79
- `);if(s.length<=e)return s;t.shift()}return rr}var Pa=12e4;async function ar(n){let e=n.timeoutMs??Pa,t,s,r=!1;try{let i=(async()=>{t=pe.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:G}}),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 g=_a(a);if(g.size===0||g.has(n.modelId))try{await t.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];t.connection.onNotification("session/update",g=>{let m=Ta(g);m.length>0&&c.push(m)});let f=ir(n.history,{maxChars:n.maxTranscriptChars}),u=f.length>0?`${f}
75
+ Use empty arrays/strings where a field doesn't apply.`;function sr(n){let e=n.trim();if(e.length===0)return;let t=nr(e);if(t===void 0){let i=e.indexOf("{"),o=e.lastIndexOf("}");if(i<0||o<=i||(t=nr(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,ca))}if(s.synopsis!==void 0&&s.synopsis!==null){let i=Ze.safeParse(s.synopsis);i.success&&ua(i.data)&&(r.synopsis=i.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}function nr(n){try{return JSON.parse(n)}catch{return}}function ua(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 fa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pa=la(fa,16),ga="hydra_lineage_";function et(){return`${ga}${pa()}`}var Rn=x.object({name:x.string(),description:x.string().optional()}),En=x.object({id:x.string(),name:x.string().optional(),description:x.string().optional()}),ma=x.object({modelId:x.string(),name:x.string().optional(),description:x.string().optional()}),Pn=x.object({used:x.number().optional(),size:x.number().optional(),costAmount:x.number().optional(),costCurrency:x.string().optional(),cumulativeCost:x.number().optional()}),Tn=x.object({name:x.string(),version:x.string().optional()}),ha=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:Ze.optional(),summarizedThroughEntry:x.number().int().nonnegative().optional(),agentArgs:x.array(x.string()).optional(),currentModel:x.string().optional(),currentMode:x.string().optional(),currentUsage:Pn.optional(),agentCommands:x.array(Rn).optional(),agentModes:x.array(En).optional(),agentModels:x.array(ma).optional(),pendingHistorySync:x.boolean().optional(),parentSessionId:x.string().optional(),forkedFromSessionId:x.string().optional(),forkedFromMessageId:x.string().optional(),originatingClient:Tn.optional(),interactive:x.boolean().optional(),priority:x.number().int().nonnegative().optional(),forwardedEnv:x.record(x.string(),x.string()).optional(),createdAt:x.string(),updatedAt:x.string()}),Mn=/^[A-Za-z0-9_-]+$/;function ya(n){if(!Mn.test(n))throw new Error(`unsafe session id: ${n}`)}var xt=class{async write(e){ya(e.sessionId);let t={version:1,...e};await ne(w.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Mn.test(e))return;let t=await oe(w.sessionFile(e));if(t!==void 0)try{return ha.parse(t)}catch{return}}async delete(e){if(Mn.test(e)){try{await De.unlink(w.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await De.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 De.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 _n(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,forwardedEnv:n.forwardedEnv,createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as me from"fs/promises";import{z as ue}from"zod";var wa=ue.object({version:ue.literal(1),agentId:ue.string(),upstreamSessionId:ue.string(),deletedAt:ue.string(),upstreamUpdatedAt:ue.string().optional(),cwd:ue.string().optional(),title:ue.string().optional(),reason:ue.enum(["user","expired"]).optional(),interactive:ue.boolean().optional()}),Ct=class{async add(e){let t={version:1,...e};await ne(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 oe(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 wa.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 rr(n,e){return e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as gr from"fs/promises";import{fileURLToPath as va}from"url";import*as tt from"path";import*as Mt from"fs";function Ia(){try{let n=tt.dirname(va(import.meta.url));for(let e=0;e<8;e+=1){let t=tt.join(n,"package.json");if(Mt.existsSync(t)){let r=JSON.parse(Mt.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=tt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var G=Ia(),Rt="hydra-acp-cat";var ir=`[older history truncated]
76
+ `,ba=["file_path","path","command","pattern","query"];function or(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 l=xa(d.prompt).trim();l.length>0&&s.push(`User: ${l}`)}else if(c==="agent_message_chunk"){let l=Ca(d.content);l.length>0&&(r+=l)}else c==="tool_call"?(i(),s.push(Sa(d))):c==="turn_complete"&&i()}return i(),Ra(s.join(`
77
+ `),t)}function Sa(n){let e=ka(n),t=Aa(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function ka(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Aa(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of ba){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Ma(r,200)}`)}return t}function xa(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 Ca(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 Ra(n,e){if(n.length<=e)return n;let t=n.split(`
78
+ `);for(;t.length>0;){let s=ir+t.join(`
79
+ `);if(s.length<=e)return s;t.shift()}return ir}var Ea=12e4;async function dr(n){let e=n.timeoutMs??Ea,t,s,r=!1;try{let i=(async()=>{t=pe.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:G}}),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 g=Ta(a);if(g.size===0||g.has(n.modelId))try{await t.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(m){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${m.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...g].join(", ")}]); continuing on default`)}let c=[];t.connection.onNotification("session/update",g=>{let m=Pa(g);m.length>0&&c.push(m)});let l=or(n.history,{maxChars:n.maxTranscriptChars}),u=l.length>0?`${l}
80
80
 
81
- ${xn}`:xn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let l=c.join(""),p=nr(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 Ta(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 _a(n){let e=new Set;or(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&or(e,t.availableModels),e}function or(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 $a(n){let e=new Map;for(let t of fr(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 ur(n){return $a(n).map(e=>e.name)}function Fa(n){let e=new Map;for(let t of fr(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 lr(n){return Fa(n).map(e=>e.path)}function fr(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:dr(i),paths:new Set},e.set(d,c)):c.toolName=dr(i);for(let f of cr(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 cr(i.rawInput,i.locations))a.paths.add(d)}return e}function dr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function cr(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 Oa=2,Rt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Oa}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 se(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await pr.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 ar({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=Na(f.synopsis,s);u&&ja(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!f.title)} fields=${Ha(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 Na(n,e){let t=lr(e),s=ur(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 ja(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 Ha(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 Y from"fs/promises";function gr(n){return n==="summary"?"summary":"inline"}var _n=256;function mr(n,e){return e!=="summary"?n:n.map(Ba)}function Ba(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(hr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=$n(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function Ua(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function hr(n){if(Ua(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=$n(e.text)),typeof e.content=="string"?t.content=$n(e.content):e.content&&typeof e.content=="object"&&(t.content=hr(e.content)),t}function $n(n){if(typeof n=="string"&&n.length>_n){let e=n.length-_n;return`${n.slice(0,_n)}\u2026[+${e} chars omitted from summary export]`}return n}var Da=2048;function yr(n){let e=new Set,t=s=>{if(wr(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 wr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function La(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 Nn(n,e){if(!La(n))return n;let t=n.params,s=t.update,r=await Fn(s,e);return{...n,params:{...t,update:r}}}async function Fn(n,e){if(typeof n=="string"){if(n.length<=Da)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 Fn(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await Fn(r,e);return t}return n}async function vr(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await On(t,e);return s===t?n:{...n,params:s}}async function On(n,e){if(wr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await On(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 On(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var nt=/^[A-Za-z0-9_-]+$/,qa=1e3,Et=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??qa}async append(e,t){if(nt.test(e))return this.enqueue(e,async()=>{await Y.mkdir(w.sessionDir(e),{recursive:!0});let s=await Nn(t,i=>on(e,i)),r=JSON.stringify(s)+`
82
- `;await Y.appendFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(nt.test(e))return this.enqueue(e,async()=>{await Y.mkdir(w.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await Nn(i,o=>on(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
81
+ ${Cn}`:Cn;await t.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:u}]});let f=c.join(""),p=sr(f);return p||n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse as snapshot JSON (replyLen=${f.length} preview=${JSON.stringify(f.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 Pa(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 Ta(n){let e=new Set;ar(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&ar(e,t.availableModels),e}function ar(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 _a(n){let e=new Map;for(let t of pr(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 lr(n){return _a(n).map(e=>e.name)}function $a(n){let e=new Map;for(let t of pr(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 fr(n){return $a(n).map(e=>e.path)}function pr(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:cr(i),paths:new Set},e.set(d,c)):c.toolName=cr(i);for(let l of ur(i.rawInput,i.locations))c.paths.add(l);continue}if(typeof i.toolCallId!="string"||i.toolCallId.length===0)continue;let a=e.get(i.toolCallId);if(a!==void 0)for(let d of ur(i.rawInput,i.locations))a.paths.add(d)}return e}function cr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function ur(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 Fa=2,Et=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Fa}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 se(o,[],{npmRegistry:this.opts.npmRegistry}),d=this.opts.synopsisModel,c=w.sessionDir(e);await gr.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 l=await dr({agentId:i,cwd:c,plan:a,history:s,modelId:d,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!l){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}l.title&&await this.opts.persistTitle(e,l.title);let u=Oa(l.synopsis,s);u&&Na(u)?(await this.opts.persistSynopsis(e,u,s.length),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!l.title)} fields=${ja(u)}`)):l.title&&this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`)}catch(t){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${t.message}`)}}};function Oa(n,e){let t=fr(e),s=lr(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 Na(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 ja(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 Y from"fs/promises";function mr(n){return n==="summary"?"summary":"inline"}var $n=256;function hr(n,e){return e!=="summary"?n:n.map(Ha)}function Ha(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(yr));let o=r.rawOutput;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o,d={};a.error!==void 0&&(d.error=Fn(a.error)),a.metadata!==void 0&&(d.metadata=a.metadata),i.rawOutput=d}return{...n,params:{...t,update:i}}}function Ba(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function yr(n){if(Ba(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=Fn(e.text)),typeof e.content=="string"?t.content=Fn(e.content):e.content&&typeof e.content=="object"&&(t.content=yr(e.content)),t}function Fn(n){if(typeof n=="string"&&n.length>$n){let e=n.length-$n;return`${n.slice(0,$n)}\u2026[+${e} chars omitted from summary export]`}return n}var Ua=2048;function wr(n){let e=new Set,t=s=>{if(vr(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 vr(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Da(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 jn(n,e){if(!Da(n))return n;let t=n.params,s=t.update,r=await On(s,e);return{...n,params:{...t,update:r}}}async function On(n,e){if(typeof n=="string"){if(n.length<=Ua)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 On(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await On(r,e);return t}return n}async function Ir(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await Nn(t,e);return s===t?n:{...n,params:s}}async function Nn(n,e){if(vr(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let i=await Nn(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 Nn(i,e);o!==i&&(t=!0),s[r]=o}return t?s:n}return n}var nt=/^[A-Za-z0-9_-]+$/,La=1e3,Pt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??La}async append(e,t){if(nt.test(e))return this.enqueue(e,async()=>{await Y.mkdir(w.sessionDir(e),{recursive:!0});let s=await jn(t,i=>an(e,i)),r=JSON.stringify(s)+`
82
+ `;await Y.appendFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(nt.test(e))return this.enqueue(e,async()=>{await Y.mkdir(w.sessionDir(e),{recursive:!0});let s=[];for(let i of t)s.push(await jn(i,o=>an(e,o)));let r=s.length===0?"":s.map(i=>JSON.stringify(i)).join(`
83
83
  `)+`
84
84
  `;await Y.writeFile(w.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(nt.test(e))return this.enqueue(e,async()=>{let s;try{s=await Y.readFile(w.historyFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let r=s.split(`
85
85
  `).filter(o=>o.length>0);if(r.length<=t)return;let i=r.slice(-t);await Y.writeFile(w.historyFile(e),i.join(`
86
86
  `)+`
87
87
  `,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!nt.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let i;try{i=await Y.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 yt(e,u);return d.set(u,p),p},f=[];for(let u of a)f.push(await vr(u,c));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(nt.test(e))return this.enqueue(e,async()=>{try{await Y.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await hs(e);try{await Y.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 Ir}from"fs";import*as br from"path";async function Sr(n,e){await Ir.mkdir(br.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await Ir.writeFile(n,t.length>0?t.join(`
88
+ `)){if(u.length===0)continue;let f;try{f=JSON.parse(u)}catch{continue}if(!f||typeof f!="object"||Array.isArray(f))continue;let p=f;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 f=d.get(u);if(f!==void 0)return f;let p=await wt(e,u);return d.set(u,p),p},l=[];for(let u of a)l.push(await Ir(u,c));return l}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(nt.test(e))return this.enqueue(e,async()=>{try{await Y.unlink(w.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await ys(e);try{await Y.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 br}from"fs";import*as Sr from"path";async function kr(n,e){await br.mkdir(Sr.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await br.writeFile(n,t.length>0?t.join(`
89
89
  `)+`
90
- `:"")}import{z as F}from"zod";var Ja=F.object({method:F.string(),params:F.unknown(),recordedAt:F.number()}),za=F.object({sessionId:F.string(),lineageId:F.string(),upstreamSessionId:F.string().optional(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),synopsis:Ze.optional(),summarizedThroughEntry:F.number().int().nonnegative().optional(),currentModel:F.string().optional(),currentMode:F.string().optional(),currentUsage:En.optional(),agentCommands:F.array(Mn).optional(),agentModes:F.array(Rn).optional(),interactive:F.boolean().optional(),originatingClient:Pn.optional(),priority:F.number().int().nonnegative().optional(),createdAt:F.string(),updatedAt:F.string()}),Wa=F.object({version:F.literal(1),exportedAt:F.string(),exportedFrom:F.object({hydraVersion:F.string(),machine:F.string(),hydraHost:F.string().optional()}),session:za,history:F.array(Ja),promptHistory:F.array(F.string()).optional(),toolBlobs:F.record(F.string()).optional()});function st(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 kr(n){return Wa.parse(n)}var Ar=900*1e3,Va="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Pt=Qa(Va,16),ot=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>pe.spawn(i)),this.store=s??new At,this.tombstones=r.tombstones??new xt,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Et({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 Rt({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 Oe(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,forwardedEnv:e.forwardedEnv});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_${Pt()}`,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 xe({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,forwardedEnv:e.forwardedEnv,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 m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=I.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await se(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});o=m.agentCapabilities,i.authMethods=Tt(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ce(m,i)}let a;try{let m=Xa(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===I.AuthRequired)throw await i.kill().catch(()=>{}),Ce(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
91
- `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Er(a??{}),c=e.agentModes??Cr(Rr(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let f=await Pr({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=xr(a??{}),l=Cr(Mr(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(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await Tr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new xe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers: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,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Pr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await Tr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new xe({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,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Me.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:Te(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 se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:_t.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=Tt(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 g=`${e}::${p.sessionId}`;if(d.has(g)){l+=1;continue}if(Ga(p.cwd,f)){l+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!sr(m,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 ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ge}${Pt()}`,y=new Date().toISOString(),k=p.updatedAt??y,S={sessionId:h,lineageId:et(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:k,updatedAt:k};p.title!==void 0&&(S.title=p.title);let A=Tn(S);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 se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}}),o=i.agentCapabilities;r.authMethods=Tt(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=xr(a),f=Mr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=je(u,f),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,u,m)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=f.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let l=Rr(a),p=Er(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(()=>{}),Ce(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 se(r,[],{npmRegistry:this.npmRegistry}),o=t??Te(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:G}});a.authMethods=Tt(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ce(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Le({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:$r(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=Ya(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 yt(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:Ka(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,forwardedEnv:t.forwardedEnv}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Be(r.update.prompt),o=An(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(ge))return;let t=ge+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 rt(t.sessionId),d=Le({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 rt(s.sessionId),i=Le(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=>rt(f.sessionId)));for(let f=0;f<i.length;f+=1){let u=i[f],l=o[f];s.add(u.sessionId);let p=Le({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},l.hasContent);if(!r(p))continue;let g=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:g,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=>rt(f.sessionId)));for(let f=0;f<d.length;f+=1){let u=d[f],l=c[f],p=Le(u,l.hasContent);if(!r(p))continue;let g=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:g,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=et(),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 _r(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of yr(o)){let f=await gs(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=`${ge}${Pt()}`;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 g=new Error(`source session not found: ${e}`);throw g.code=I.SessionNotFound,g}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let m=new Error(`agent ${r} not found in registry`);throw m.code=I.AgentNotInstalled,m}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=kn(o,t.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw g.code=I.InvalidParams,g}d=t.forkAt}else{let g=ed(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),f=await _r(e),u={...s,lineageId:et(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},l=st({record:u,history:c,promptHistory:f.length>0?f:void 0,hydraVersion:G,machine:_t.hostname()}),p=`${ge}${Pt()}`;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 ms(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Me.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await Sr(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 rt(e),r=Le(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 Ws(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<Ar),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${Ar/1e3}s)`),await Ke(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 Ke(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 Ga(n,e){if(typeof n!="string"||n.length===0)return!1;let t=it.resolve(n),s=it.resolve(e);return t===s||t.startsWith(s+it.sep)}function Ya(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 Tn({sessionId:n.sessionId,lineageId:e?.lineageId??et(),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:$r(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,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function $r(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 Ka(n){return n?{...n}:void 0}function Xa(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function $t(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=Za(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function xr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>le(e.currentModelId)??le(e.currentModel)??le(e.modelId)??le(e.model),fromConfig:e=>le(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},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 Tt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function le(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Za(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 Cr(n){return n.length>0?n:void 0}function Mr(n){return $t(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ue(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ue(e.options);return t.length>0?t:void 0}})??[]}function Rr(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Xe(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Xe(e.options);return t.length>0?t:void 0}})??[]}function Er(n){return $t(n,{nestedKey:"modes",configId:"mode",fromObject:e=>le(e.currentModeId)??le(e.currentMode)??le(e.modeId)??le(e.mode),fromConfig:e=>le(e.currentValue)})}async function Pr(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 Tr(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 ed(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 _r(n){try{let e=await Me.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 rt(n){try{let e=await Me.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Le(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Mt?!1:e?!0:void 0}import{spawn as td}from"child_process";import*as Je from"fs";import*as be from"fs/promises";import*as Fr from"path";var Ft=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 nd=1e3,sd=6e4,jn=3e3,qe=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??nd,this.restartCapMs=r.restartCapMs??sd;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 be.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()},jn);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 at(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw at(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 at(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 at(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 at(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{}},jn);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 Ft(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await be.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=Fr.join(this.adapter.paths.dir(),t),r;try{let i=await be.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Hn(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+jn;for(;Date.now()<i&&Hn(r);)await new Promise(o=>setTimeout(o,50));if(Hn(r))try{process.kill(r,"SIGKILL")}catch{}}await be.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=Je.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
- `);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=td(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{Je.writeFileSync(this.adapter.paths.pidFile(r.name),`${l.pid}
90
+ `:"")}import{z as F}from"zod";var qa=F.object({method:F.string(),params:F.unknown(),recordedAt:F.number()}),Ja=F.object({sessionId:F.string(),lineageId:F.string(),upstreamSessionId:F.string().optional(),agentId:F.string(),cwd:F.string(),title:F.string().optional(),synopsis:Ze.optional(),summarizedThroughEntry:F.number().int().nonnegative().optional(),currentModel:F.string().optional(),currentMode:F.string().optional(),currentUsage:Pn.optional(),agentCommands:F.array(Rn).optional(),agentModes:F.array(En).optional(),interactive:F.boolean().optional(),originatingClient:Tn.optional(),priority:F.number().int().nonnegative().optional(),createdAt:F.string(),updatedAt:F.string()}),za=F.object({version:F.literal(1),exportedAt:F.string(),exportedFrom:F.object({hydraVersion:F.string(),machine:F.string(),hydraHost:F.string().optional()}),session:Ja,history:F.array(qa),promptHistory:F.array(F.string()).optional(),toolBlobs:F.record(F.string()).optional()});function st(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 Ar(n){return za.parse(n)}var xr=900*1e3,Qa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Tt=Wa(Qa,16),ot=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(i=>pe.spawn(i)),this.store=s??new xt,this.tombstones=r.tombstones??new Ct,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Pt({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 Et({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 Oe(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,forwardedEnv:e.forwardedEnv});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_${Tt()}`,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 xe({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,forwardedEnv:e.forwardedEnv,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 m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=I.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await se(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),i=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),o;try{let m=await i.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}});o=m.agentCapabilities,i.authMethods=_t(m.authMethods)}catch(m){throw await i.kill().catch(()=>{}),Ce(m,i)}let a;try{let m=Ka(e.agentId,e.currentModel);a=await i.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...m&&{_meta:m}})}catch(m){if(m&&typeof m=="object"&&m.code===I.AuthRequired)throw await i.kill().catch(()=>{}),Ce(m,i);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
91
+ `),await i.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let d=Pr(a??{}),c=e.agentModes??Mr(Er(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(d)} advertisedModes=${JSON.stringify(c?.map(m=>m.id))}`);let l=await Tr({agent:i,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:d,advertisedModes:c,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(l)} for sessionId=${e.hydraSessionId}`);let u=Cr(a??{}),f=Mr(Rr(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(u)} advertisedModels=${JSON.stringify(f?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let p=await _r({agent:i,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:u,logger:this.logger});if(e.pendingHistorySync!==!0){let m=i.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let g=new xe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:i,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:o,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:e.mcpServers??[]}),listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:p,currentMode:l,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:c,agentModels:f,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId)});return await this.attachManagerHooks(g),g}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,i=await Tr({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),o=e.agentModels??s.initialModels,a=await _r({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let d=new xe({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,forwardedEnv:e.forwardedEnv,extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(d.sessionId)});return await this.attachManagerHooks(d),d.seedFromImport().catch(()=>{}),d}async dirExists(e){try{return(await Me.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:Te(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 se(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:$t.homedir(),plan:s}),i;try{i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}})}catch(p){throw await r.kill().catch(()=>{}),Ce(p,r)}if(r.authMethods=_t(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 l=w.sessionsDir(),u=[],f=0;for(let p of a){let g=`${e}::${p.sessionId}`;if(d.has(g)){f+=1;continue}if(Va(p.cwd,l)){f+=1;continue}let m=await this.tombstones.read(e,p.sessionId).catch(()=>{});if(m){if(!rr(m,p.updatedAt)){f+=1;continue}await this.tombstones.remove(e,p.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${p.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}d.add(g);let h=`${ge}${Tt()}`,y=new Date().toISOString(),A=p.updatedAt??y,k={sessionId:h,lineageId:et(),upstreamSessionId:p.sessionId,agentId:e,cwd:p.cwd,pendingHistorySync:!0,interactive:!0,createdAt:A,updatedAt:A};p.title!==void 0&&(k.title=p.title);let b=_n(k);await this.store.write(b),u.push({version:1,...b})}return{synced:u,skipped:f}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let i=0;i<100;i+=1){let o={};s!==void 0&&(o.cursor=s);let a=await e.connection.request("session/list",o),d=Array.isArray(a.sessions)?a.sessions:[];for(let c of d){if(typeof c.sessionId!="string"||typeof c.cwd!="string")continue;let l={sessionId:c.sessionId,cwd:c.cwd};typeof c.title=="string"&&(l.title=c.title),typeof c.updatedAt=="string"&&(l.updatedAt=c.updatedAt),t.push(l)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(i){return this.logger?.warn(`${r} rejected by agent (${i.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let i=new Error(`agent ${e.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let s=await se(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let i=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra",version:G}}),o=i.agentCapabilities;r.authMethods=_t(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=Cr(a),l=Rr(a),u=e.model??this.defaultModels[e.agentId];if(u&&u!==c){let g=je(u,l),m=e.model!==void 0?`model=${JSON.stringify(u)}`:`defaultModels[${e.agentId}]=${JSON.stringify(u)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,d,u,m)&&(c=u);else if(g.kind==="resolved")(g.modelId===c||await this.applySeedModel(r,d,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(c=g.modelId);else if(g.kind==="ambiguous")this.logger?.warn(`${m} is ambiguous (trailing-segment matches [${g.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(c)}`);else{let h=l.map(y=>y.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(c)}`)}}let f=Er(a),p=Pr(a);return{agent:r,upstreamSessionId:d,agentMeta:a._meta,agentCapabilities:o,initialModel:c,initialModels:l.length>0?l:void 0,initialModes:f.length>0?f:void 0,initialMode:p}}catch(i){throw await r.kill().catch(()=>{}),Ce(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 se(r,[],{npmRegistry:this.npmRegistry}),o=t??Te(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:G}});a.authMethods=_t(d.authMethods)}catch(d){throw await a.kill().catch(()=>{}),Ce(d,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return se(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let s=Le({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:Fr(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=Ga(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 wt(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:Ya(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,forwardedEnv:t.forwardedEnv}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let i={...r,forwardedEnv:t};await this.store.write(i)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let i=Be(r.update.prompt),o=xn(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(ge))return;let t=ge+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 rt(t.sessionId),d=Le({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 rt(s.sessionId),i=Le(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=l=>e.includeNonInteractive?!0:l===!0,i=[...this.sessions.values()].filter(l=>!e.cwd||l.cwd===e.cwd),o=await Promise.all(i.map(l=>rt(l.sessionId)));for(let l=0;l<i.length;l+=1){let u=i[l],f=o[l];s.add(u.sessionId);let p=Le({interactive:u.interactive,...u.originatingClient?{originatingClient:u.originatingClient}:{}},f.hasContent);if(!r(p))continue;let g=f.mtime??new Date(u.updatedAt).toISOString();t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:u.attachedCount,status:"live",busy:u.turnStartedAt!==void 0,awaitingInput:u.awaitingInput})}let d=(await this.store.list().catch(l=>{throw this.logger?.warn(`session list: store.list() failed: ${l?.message??String(l)}`),l})).filter(l=>!s.has(l.sessionId)&&(!e.cwd||l.cwd===e.cwd)),c=await Promise.all(d.map(l=>rt(l.sessionId)));for(let l=0;l<d.length;l+=1){let u=d[l],f=c[l],p=Le(u,f.hasContent);if(!r(p))continue;let g=f.mtime??u.updatedAt;t.push({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,cwd:u.cwd,title:u.title,agentId:u.agentId,currentModel:u.currentModel,currentUsage:u.currentUsage?{...u.currentUsage,costAmount:(u.currentUsage.cumulativeCost??0)+(u.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:u.importedFromMachine,importedFromUpstreamSessionId:u.importedFromUpstreamSessionId,parentSessionId:u.parentSessionId,forkedFromSessionId:u.forkedFromSessionId,forkedFromMessageId:u.forkedFromMessageId,originatingClient:u.originatingClient,interactive:p,priority:u.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1})}return t.sort((l,u)=>l.updatedAt<u.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let c=et(),l={...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=l}let i=t.tools??"inline",o=await this.histories.load(e,i==="references"?{tools:"references"}:{}).catch(()=>[]),a=await $r(e);if(i!=="references")return{record:r,history:o,promptHistory:a};let d={};for(let c of wr(o)){let l=await ms(e,c);l&&(d[c]=l.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=`${ge}${Tt()}`;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 g=new Error(`source session not found: ${e}`);throw g.code=I.SessionNotFound,g}let r=t.agentId??s.agentId,i=r!==s.agentId;if(i&&!await this.registry.getAgent(r)){let m=new Error(`agent ${r} not found in registry`);throw m.code=I.AgentNotInstalled,m}let o=await this.histories.load(e).catch(()=>[]),a,d;if(t.forkAt!==void 0){if(a=An(o,t.forkAt),a<0){let g=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw g.code=I.InvalidParams,g}d=t.forkAt}else{let g=Za(o);g?(a=g.index,d=g.messageId):(a=-1,d="")}let c=o.slice(0,a+1),l=await $r(e),u={...s,lineageId:et(),agentId:r,interactive:!1,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...i?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{}},f=st({record:u,history:c,promptHistory:l.length>0?l:void 0,hydraVersion:G,machine:$t.hostname()}),p=`${ge}${Tt()}`;return await this.writeImportedRecord({sessionId:p,bundle:f,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 hs(e.sessionId,i,Buffer.from(o,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Me.utimes(w.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await kr(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 rt(e),r=Le(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 Qs(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),i=s.filter(d=>r-d.enqueuedAt<xr),o=s.length-i.length;if(o>0&&(this.logger?.info(`queue replay: dropping ${o} stale prompt(s) for ${t.sessionId} (TTL ${xr/1e3}s)`),await Ke(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 Ke(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 Va(n,e){if(typeof n!="string"||n.length===0)return!1;let t=it.resolve(n),s=it.resolve(e);return t===s||t.startsWith(s+it.sep)}function Ga(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(l=>l.description!==void 0?{name:l.name,description:l.description}:{name:l.name}):void 0)??e?.agentCommands,r=n.availableModes(),o=(r.length>0?r.map(l=>{let u={id:l.id};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModes,a=n.availableModels(),c=(a.length>0?a.map(l=>{let u={modelId:l.modelId};return l.name!==void 0&&(u.name=l.name),l.description!==void 0&&(u.description=l.description),u}):void 0)??e?.agentModels;return _n({sessionId:n.sessionId,lineageId:e?.lineageId??et(),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:Fr(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,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function Fr(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 Ya(n){return n?{...n}:void 0}function Ka(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Ft(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=Xa(n,e.configId);if(i){let o=e.fromConfig(i);if(o!==void 0)return o}}function Cr(n){return Ft(n,{nestedKey:"models",configId:"model",fromObject:e=>le(e.currentModelId)??le(e.currentModel)??le(e.modelId)??le(e.model),fromConfig:e=>le(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=c=>!!c&&typeof c=="object"&&!Array.isArray(c),r=s(t.data)?t.data:{},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 _t(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",i=s.type==="agent"||s.type==="terminal"?s.type:void 0,o=typeof s.name=="string"?s.name:void 0,a=s._meta,d=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...i&&{type:i},...o!==void 0&&{name:o},...d&&{_meta:d}})}return e.length>0?e:void 0}function le(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Xa(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 Mr(n){return n.length>0?n:void 0}function Rr(n){return Ft(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=Ue(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=Ue(e.options);return t.length>0?t:void 0}})??[]}function Er(n){return Ft(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=Xe(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=Xe(e.options);return t.length>0?t:void 0}})??[]}function Pr(n){return Ft(n,{nestedKey:"modes",configId:"mode",fromObject:e=>le(e.currentModeId)??le(e.currentMode)??le(e.modeId)??le(e.mode),fromConfig:e=>le(e.currentValue)})}async function Tr(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 _r(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 $r(n){try{let e=await Me.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 rt(n){try{let e=await Me.stat(w.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Le(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Rt?!1:e?!0:void 0}import{spawn as ed}from"child_process";import*as Je from"fs";import*as be from"fs/promises";import*as Or from"path";var Ot=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 td=1e3,nd=6e4,Hn=3e3,qe=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??td,this.restartCapMs=r.restartCapMs??nd;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 be.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()},Hn);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 at(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw at(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 at(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 at(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 at(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{}},Hn);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 Ot(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await be.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=Or.join(this.adapter.paths.dir(),t),r;try{let i=await be.readFile(s,"utf8"),o=Number.parseInt(i.trim(),10);Number.isInteger(o)&&o>0&&(r=o)}catch{}if(typeof r=="number"&&Bn(r)){try{process.kill(r,"SIGTERM")}catch{}let i=Date.now()+Hn;for(;Date.now()<i&&Bn(r);)await new Promise(o=>setTimeout(o,50));if(Bn(r))try{process.kill(r,"SIGKILL")}catch{}}await be.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=Je.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
+ `);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,...l]=i;if(c===void 0){o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
94
+ `),o.end();return}let u=[...l,...r.args],f;try{f=ed(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(f.stdout&&f.stdout.pipe(o,{end:!1}),f.stderr&&f.stderr.pipe(o,{end:!1}),typeof f.pid=="number")try{Je.writeFileSync(this.adapter.paths.pidFile(r.name),`${f.pid}
96
96
  `,{encoding:"utf8",mode:384})}catch(p){o.write(`[hydra-acp] failed to write pid file for ${r.name}: ${p.message}
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,g)=>{try{Je.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"null"}
97
+ `)}e.child=f,e.logStream=o,e.pid=typeof f.pid=="number"?f.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,f.on("error",p=>{o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${p.message}
98
+ `)}),f.on("exit",(p,g)=>{try{Je.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}o.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${p??"null"} signal=${g??"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 m=e.exitWaiters.splice(0);for(let y of m)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 Hn(n){try{return process.kill(n,0),!0}catch{return!1}}function at(n,e){return n.code=e,n}var rd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},Ot=class extends qe{constructor(e,t,s={}){super(e,rd,t,s)}};var id={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},Nt=class extends qe{connected=new Map;constructor(e,t,s={}){super(e,id,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 jt=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 ct from"fs/promises";import*as Ht from"path";var dt=n=>{process.stderr.write(n+`
101
- `)};function Bn(n){dt=n??(e=>process.stderr.write(e+`
102
- `))}async function Or(n,e){let t=ae();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=Ht.join(w.agentsDir(),t),a;try{a=await ct.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;dt(`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=Ht.join(o,c),p;try{p=await ct.readdir(l,{withFileTypes:!0})}catch(g){dt(`hydra-acp: prune: failed to read ${l}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===f||u.has(m)||m.includes(".partial-"))continue;let h=Ht.join(l,m);try{await ct.rm(h,{recursive:!0,force:!0}),dt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){dt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function Nr(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 mn(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 Un(n){let e=n.maxDeletions??200,t=(p,g)=>{n.logger&&n.logger[p](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.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(g){f+=1,t("warn",`delete ${p} failed: ${g.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 ${od(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 jr(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Un({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 od(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 ad}from"crypto";function Dn(n){if(Array.isArray(n))return n.map(Dn);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Dn(n[t]);return e}return n}function Hr(n){let{tui:e,...t}=n,s=JSON.stringify(Dn(t));return ad("sha256").update(s).digest("hex").slice(0,16)}import*as Dr from"path";import{createHash as dd,randomBytes as cd,timingSafeEqual as ud}from"crypto";var Lr="hydra_session_",ld=3600*24*30,Br=12,fd=32,pd=50;function gd(){return Dr.join(w.home(),"session-tokens.json")}function Ur(n){return dd("sha256").update(n).digest("hex")}function qr(n){return cd(n).toString("hex")}function md(){return qr(Br).slice(0,Br*2)}function hd(){return`${Lr}${qr(fd)}`}var Bt=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=gd(),s=await oe(t);s&&Array.isArray(s.records)&&(e=s.records.filter(yd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=hd(),s=Ur(t),r=md(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ld,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(Lr))return;let t=Ur(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||!ud(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(()=>{})},pd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ne(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 yd(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 Jr="Bearer ",Ut=class{constructor(e){this.token=e}token;async validate(e){return wd(e,this.token)?"service":void 0}},Dt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},Lt=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 zr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(Jr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(Jr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Wr(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 qt=class{tokens=new Map;mint(e,t){let s=gt();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 wd(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 Jt=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 ft from"os";import*as li from"path";import{posix as vd}from"path";import Id from"strip-ansi";function ut(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var bd=/[\x00-\x08\x0b-\x1f\x7f]/g;function ee(n){return Id(n).replace(bd,"")}function L(n){return ee(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Gr(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 Rd(t);case"agent_thought_chunk":case"agent_thought":return Ed(t);case"user_message_chunk":return Pd(t);case"prompt_received":return Td(t);case"tool_call":return _d(t,e);case"tool_call_update":return jd(t,e);case"plan":return Ud(t);case"current_mode_update":return Dd(t);case"current_model_update":return Ld(t);case"turn_complete":return qd(t);case"usage_update":return Md(t);case"available_commands_update":return xd(t);case"available_modes_update":return Cd(t);case"session_info_update":return kd(t);case"config_option_update":return Sd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function Sd(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 kd(n){let e=U(n,"title"),t=e!==void 0?L(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 Ad(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:L(r)};typeof s.description=="string"&&(i.description=L(s.description)),e.push(i)}return e}function xd(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:Ad(e)}:null}function Cd(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:L(r.id)};typeof r.name=="string"&&(i.name=L(r.name)),typeof r.description=="string"&&(i.description=L(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Md(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 Rd(n){let e=lt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ut(n)}}function Ed(n){let e=typeof n.text=="string"?ee(n.text):lt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ut(n)}}function Pd(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=lt(n.content);return t===null?null:{kind:"user-text",text:t}}function Td(n){let e=Jd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Yr(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 zt(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 Kr(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:ee(t)}function _d(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title")??U(n,"name")??U(n,"label")??"tool call",r=U(n,"name")??U(n,"title");if(Yr(r)){let g=Kr(n);if(g!==null){let m=U(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=ei(L(s),n,e),o=U(n,"status"),a=U(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=zt(n);c!==null&&(d.editDiff=c);let f=Zr(n);f!==void 0&&(d.detail=f);let u=Ln(n);u!==void 0&&(d.detailFull=u);let l=Xr(n);l!==void 0&&(d.locations=l);let p=ut(n);return p!==void 0&&(d.workerTaskId=p),d}function Xr(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Vr=64;function Zr(n){let e=Ln(n);if(e===void 0)return;let t=n.rawInput;return t&&typeof t.command=="string"?Od(e,Vr):Nd(e,Vr)}function Ln(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)return ee(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Ee(L(s))}var $d=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Fd(n){for(let e of $d)if(n.startsWith(e))return!0;return!1}function ei(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ee(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 Ee(o)}return Fd(n)?Ee(`/${n}`):t.cwd&&t.cwd.length>0?Ee(vd.resolve(t.cwd,n)):n}function Od(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Nd(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 jd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?ei(L(s),n,e):void 0,i=U(n,"status"),o=zt(n),a=Zr(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=U(n,"name")??s;if(Yr(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Kr(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let f={kind:"tool-call-update",toolCallId:t};r!==void 0&&(f.title=r),a!==void 0&&(f.detail=a);let u=Ln(n);u!==void 0&&(f.detailFull=u);let l=Xr(n);if(l!==void 0&&(f.locations=l),i!==void 0&&(f.status=i),o!==null&&(f.editDiff=o),i==="failed"){let g=Hd(n);g!==null&&(f.errorText=g),Bd(n,g)&&(f.upstreamInterrupted=!0)}let p=ut(n);return p!==void 0&&(f.workerTaskId=p),f}function Hd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=lt(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 ee(s)}return null}function Bd(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 Ud(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"?L(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 Dd(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Ld(n){let e=U(n,"currentModel")??U(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:L(e),...s&&s.length>0?{availableModels:s}:{}}}function qd(n){let e=U(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 lt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ee(e.text):null}function Jd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=lt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function U(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ti(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=Wd(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(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||l.push(p);if(l.length===0)continue;e.set(d,[...u,...l]),f=l}for(let u of f)zd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function ni(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 zd(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 Wd(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=zt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function si(n){let e=Qd(n),t=Vd(e),s=[];Gd(s,n),Yd(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 Bn(n){try{return process.kill(n,0),!0}catch{return!1}}function at(n,e){return n.code=e,n}var sd={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:w.extensionsDir,logFile:w.extensionLogFile,pidFile:w.extensionPidFile}},Nt=class extends qe{constructor(e,t,s={}){super(e,sd,t,s)}};var rd={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:w.transformersDir,logFile:w.transformerLogFile,pidFile:w.transformerPidFile}},jt=class extends qe{connected=new Map;constructor(e,t,s={}){super(e,rd,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 Ht=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 ct from"fs/promises";import*as Bt from"path";var dt=n=>{process.stderr.write(n+`
101
+ `)};function Un(n){dt=n??(e=>process.stderr.write(e+`
102
+ `))}async function Nr(n,e){let t=ae();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=Bt.join(w.agentsDir(),t),a;try{a=await ct.readdir(o,{withFileTypes:!0})}catch(d){let c=d;if(c.code==="ENOENT")return;dt(`hydra-acp: prune: failed to read ${o}: ${c.message}`);return}for(let d of a){if(!d.isDirectory())continue;let c=d.name,l=r.get(c);if(l===void 0)continue;let u=i.get(c)??new Set,f=Bt.join(o,c),p;try{p=await ct.readdir(f,{withFileTypes:!0})}catch(g){dt(`hydra-acp: prune: failed to read ${f}: ${g.message}`);continue}for(let g of p){if(!g.isDirectory())continue;let m=g.name;if(m===l||u.has(m)||m.includes(".partial-"))continue;let h=Bt.join(f,m);try{await ct.rm(h,{recursive:!0,force:!0}),dt(`hydra-acp: pruned stale ${c} ${m} (${h})`)}catch(y){dt(`hydra-acp: prune: failed to remove ${h}: ${y.message}`)}}}}function jr(n){let e,t=!1,s=0,r=(a,d)=>{n.logger&&n.logger[a](`agent-sync: ${d}`)},i=async()=>{let a=[];try{let l=await n.registry.load();for(let u of l.agents)await hn(u)==="yes"&&a.push(u.id)}catch(l){return r("warn",`registry load failed: ${l.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let d=s%a.length;s=(s+1)%a.length;let c=a[d];try{let{synced:l,skipped:u}=await n.manager.syncFromAgent(c);r("info",`${c}: synced ${l.length}, skipped ${u}`)}catch(l){r("warn",`${c}: ${l.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 Dn(n){let e=n.maxDeletions??200,t=(p,g)=>{n.logger&&n.logger[p](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,i=await n.manager.list({includeNonInteractive:!0}).catch(p=>(t("warn",`manager.list failed: ${p.message}`),[])),o=[];for(let p of i){if(p.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(p.interactive!==!1)continue}else if(p.interactive===!0)continue;let m=Date.parse(p.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||o.push({sessionId:p.sessionId,lastUsedMs:m}))}if(o.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};o.sort((p,g)=>p.lastUsedMs-g.lastUsedMs);let a=o.slice(0,e),d=a[0]?.lastUsedMs,c=0,l=0;for(let{sessionId:p}of a)try{await n.manager.deleteRecord(p)&&(c+=1)}catch(g){l+=1,t("warn",`delete ${p} failed: ${g.message}`)}let u=o.length-a.length;if(n.verbose||c>0||l>0){let p=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${c} ${p} session(s) older than ${id(n.maxAgeMs)}`+(l>0?`; ${l} failed`:"")+(u>0?`; ${u} deferred to next sweep`:""))}let f={considered:o.length,deleted:c,failed:l,deferred:u};return d!==void 0&&(f.oldestLastUsedMs=d),f}function Hr(n){let e,t=!1,s=!1,r=i=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await Dn({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 id(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 od}from"crypto";function Ln(n){if(Array.isArray(n))return n.map(Ln);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=Ln(n[t]);return e}return n}function Br(n){let{tui:e,...t}=n,s=JSON.stringify(Ln(t));return od("sha256").update(s).digest("hex").slice(0,16)}import*as Lr from"path";import{createHash as ad,randomBytes as dd,timingSafeEqual as cd}from"crypto";var qr="hydra_session_",ud=3600*24*30,Ur=12,ld=32,fd=50;function pd(){return Lr.join(w.home(),"session-tokens.json")}function Dr(n){return ad("sha256").update(n).digest("hex")}function Jr(n){return dd(n).toString("hex")}function gd(){return Jr(Ur).slice(0,Ur*2)}function md(){return`${qr}${Jr(ld)}`}var Ut=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=pd(),s=await oe(t);s&&Array.isArray(s.records)&&(e=s.records.filter(hd));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=md(),s=Dr(t),r=gd(),i=new Date,o=e.ttlSec&&e.ttlSec>0?e.ttlSec:ud,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(qr))return;let t=Dr(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||!cd(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(()=>{})},fd))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>ne(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 hd(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 zr="Bearer ",Dt=class{constructor(e){this.token=e}token;async validate(e){return yd(e,this.token)?"service":void 0}},Lt=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},qt=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 Wr(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(zr)){s.code(401).send({error:"Missing bearer token"});return}let i=r.slice(zr.length).trim(),o=await n.validator.validate(i);if(!o){s.code(403).send({error:"Invalid token"});return}t.authIdentity=o}}function Qr(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 Jt=class{tokens=new Map;mint(e,t){let s=mt();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 yd(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 zt=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 pt from"os";import*as fi from"path";import{posix as wd}from"path";import vd from"strip-ansi";function ut(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var Id=/[\x00-\x08\x0b-\x1f\x7f]/g;function ee(n){return vd(n).replace(Id,"")}function L(n){return ee(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function Yr(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 Rd(t);case"user_message_chunk":return Ed(t);case"prompt_received":return Pd(t);case"tool_call":return Td(t,e);case"tool_call_update":return Nd(t,e);case"plan":return Bd(t);case"current_mode_update":return Ud(t);case"current_model_update":return Dd(t);case"turn_complete":return Ld(t);case"usage_update":return Cd(t);case"available_commands_update":return Ad(t);case"available_modes_update":return xd(t);case"session_info_update":return Sd(t);case"config_option_update":return bd(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function bd(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 Sd(n){let e=U(n,"title"),t=e!==void 0?L(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 kd(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:L(r)};typeof s.description=="string"&&(i.description=L(s.description)),e.push(i)}return e}function Ad(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:kd(e)}:null}function xd(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:L(r.id)};typeof r.name=="string"&&(i.name=L(r.name)),typeof r.description=="string"&&(i.description=L(r.description)),t.push(i)}return{kind:"available-modes",modes:t}}function Cd(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=lt(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:ut(n)}}function Rd(n){let e=typeof n.text=="string"?ee(n.text):lt(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:ut(n)}}function Ed(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=lt(n.content);return t===null?null:{kind:"user-text",text:t}}function Pd(n){let e=qd(n.prompt);return e===null?null:{kind:"user-text",text:e}}function Kr(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Vr(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 Wt(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=Vr(r.oldText),o=Vr(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 Xr(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:ee(t)}function Td(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title")??U(n,"name")??U(n,"label")??"tool call",r=U(n,"name")??U(n,"title");if(Kr(r)){let g=Xr(n);if(g!==null){let m=U(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let i=ti(L(s),n,e),o=U(n,"status"),a=U(n,"kind"),d={kind:"tool-call",toolCallId:t,title:i};o!==void 0&&(d.status=o),a!==void 0&&(d.rawKind=a);let c=Wt(n);c!==null&&(d.editDiff=c);let l=ei(n);l!==void 0&&(d.detail=l);let u=qn(n);u!==void 0&&(d.detailFull=u);let f=Zr(n);f!==void 0&&(d.locations=f);let p=ut(n);return p!==void 0&&(d.workerTaskId=p),d}function Zr(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let i={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(i.line=Math.floor(r.line)),t.push(i)}return t.length>0?t:void 0}var Gr=64;function ei(n){let e=qn(n);if(e===void 0)return;let t=n.rawInput;return t&&typeof t.command=="string"?Fd(e,Gr):Od(e,Gr)}function qn(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)return ee(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Ee(L(s))}var _d=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function $d(n){for(let e of _d)if(n.startsWith(e))return!0;return!1}function ti(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Ee(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 Ee(o)}return $d(n)?Ee(`/${n}`):t.cwd&&t.cwd.length>0?Ee(wd.resolve(t.cwd,n)):n}function Fd(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Od(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 Nd(n,e={}){let t=U(n,"toolCallId")??U(n,"id");if(!t)return null;let s=U(n,"title"),r=s!==void 0?ti(L(s),n,e):void 0,i=U(n,"status"),o=Wt(n),a=ei(n);if(!(r!==void 0||o!==null||a!==void 0||i==="completed"||i==="failed"||i==="rejected"||i==="cancelled"))return null;let c=U(n,"name")??s;if(Kr(c)){let g={kind:"exit-plan-mode",toolCallId:t},m=Xr(n);return m!==null&&(g.plan=m),i!==void 0&&(g.status=i),g}let l={kind:"tool-call-update",toolCallId:t};r!==void 0&&(l.title=r),a!==void 0&&(l.detail=a);let u=qn(n);u!==void 0&&(l.detailFull=u);let f=Zr(n);if(f!==void 0&&(l.locations=f),i!==void 0&&(l.status=i),o!==null&&(l.editDiff=o),i==="failed"){let g=jd(n);g!==null&&(l.errorText=g),Hd(n,g)&&(l.upstreamInterrupted=!0)}let p=ut(n);return p!==void 0&&(l.workerTaskId=p),l}function jd(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let i=lt(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 ee(s)}return null}function Hd(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 Bd(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"?L(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 Ud(n){let e=U(n,"currentModeId")??U(n,"currentMode")??U(n,"mode");return e?{kind:"mode-changed",mode:L(e)}:null}function Dd(n){let e=U(n,"currentModel")??U(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:L(e),...s&&s.length>0?{availableModels:s}:{}}}function Ld(n){let e=U(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 lt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ee(e.text):null}function qd(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=lt(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function U(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ni(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=zd(o);if(c.length===0)continue;let l=c;if(d!==void 0){let u=e.get(d)??[],f=[];for(let p of c)u.some(g=>g.path===p.path&&g.oldText===p.oldText&&g.newText===p.newText)||f.push(p);if(f.length===0)continue;e.set(d,[...u,...f]),l=f}for(let u of l)Jd(t,u)}let s=[];for(let[r,i]of t)s.push({path:r,hunks:i.hunks,created:i.created});return s}function si(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 Jd(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 zd(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,l=typeof c.old_string=="string"?c.old_string:void 0,u=typeof c.new_string=="string"?c.new_string:void 0;l===void 0||u===void 0||e.push({path:o,oldText:l,newText:u})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let i of s){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="diff")continue;let a=typeof o.path=="string"?o.path:void 0;if(a===void 0)continue;let 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=Wt(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function ri(n){let e=Wd(n),t=Qd(e),s=[];Vd(s,n),Gd(s,e,t);let r=s.join(`
103
103
  `);return r.endsWith(`
104
104
  `)||(r+=`
105
- `),r}function Qd(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=Gr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Vd(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 Gd(n,e){let t=e.session,s=Zs(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Re(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?`${qn(a.size)}`:void 0;d.push(c?`${qn(a.used)} / ${c} tokens`:`${qn(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 Yd(n,e,t){if(!e.some(c=>Kd(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(`> ${Re(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(`> _${Re(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(`- ${Zd(f.status)} ${Xd(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} ${Re(f.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Re(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Re(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Kd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Xd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Re(n.title)}${t}`}function Zd(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 Re(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qn(n){return n.toLocaleString("en-US")}function ri(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function ec(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=>tc(f)).filter(f=>f.term.length>0);return{operator:i,terms:c}}function tc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:ii(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:ii(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function ii(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function nc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var sc=5,rc=200,oi=30;async function ci(n,e,t={}){let s=ec(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??sc,i=t.maxSessions??rc,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=ic(l,s,r);if(p.snippets.length===0)continue;let g={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(g.title=u.title),c.push(g)}return{query:e,truncated:f,results:c}}function ic(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=oc(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 oc(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=ac(a).filter(c=>nc(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),g={kind:c.kind,text:fc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function ac(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=Wt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ee(s.text):Wt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(uc(s))return[];let i=Wt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=lc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return dc(s);default:return[]}}function dc(n){let e=ai(n,"name"),t=ai(n,"title"),s=[];if(t!==void 0){let a=L(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=L(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=di(r);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=di(i);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=cc(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function cc(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=L(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=L(s);if(r.length>0)return r}}return null}function uc(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 Wt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ee(e.text):""}function lc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Wt(t);s.length>0&&e.push(s)}return e.join("")}function ai(n,e){let t=n[e];return typeof t=="string"?t:void 0}function di(n){try{return JSON.stringify(n)}catch{return""}}function fc(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-oi),d=Math.min(s.length,o+i.length+oi),c=a>0?"\u2026":"",f=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${f}`}function ui(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ri(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function fi(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 ci(e,o,{sessionIds:a})}),n.post("/v1/sessions",async(s,r)=>{let i=s.body??{},o=Te(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 Un({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=>li.join(ft.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":gr(a),c=await e.exportBundle(o,d==="references"?{tools:"references"}:{});if(!c){r.code(404).send({error:"session not found"});return}let f=st({record:c.record,history:d==="summary"?mr(c.history,"summary"):c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,...c.toolBlobs!==void 0?{toolBlobs:c.toolBlobs}:{},hydraVersion:G,machine:ft.hostname(),hydraHost:ui(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=ti(a.history);f&&(u=u.filter(l=>f.has(l.path))),c&&(u=u.map(l=>({...l,hunks:ni(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=st({record:a.record,history:a.history,promptHistory:a.promptHistory.length>0?a.promptHistory:void 0,hydraVersion:G,machine:ft.hostname(),hydraHost:ui(t)});r.header("Content-Type","text/markdown; charset=utf-8"),r.code(200).send(si(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=Te(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=kr(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,g=[];if(c){a&&(u=c.onBroadcast(h=>{r.raw.writableEnded||(l?r.raw.write(JSON.stringify(h)+`
109
- `):(g.push(h),g.length>p&&g.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 m=new Set;for(let h of f??[]){r.raw.write(JSON.stringify(h)+`
110
- `);let y=h;typeof y.recordedAt=="number"&&m.add(String(y.recordedAt))}for(;g.length>0;){let h=g.splice(0,g.length);for(let y of h){let k=y,S=typeof k.recordedAt=="number"?String(k.recordedAt):"";S&&m.has(S)||r.raw.write(JSON.stringify(y)+`
111
- `)}}return l=!0,u||r.raw.end(),r})}function pi(n,e,t,s={}){n.get("/v1/agents",async()=>Oe(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 se(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 gi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pc=/^[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=gc(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){pt(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){pt(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){pt(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){pt(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){pt(o,d)}})}function pt(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 gc(n){let e=n.name;if(typeof e!="string"||!pc.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 mi(n,e){Qt(n,"extension",e)}function hi(n,e){Qt(n,"transformer",e)}function yi(n,e){n.get("/v1/config",async()=>e)}import{z as We}from"zod";import*as ze from"fs/promises";import*as wi from"path";import{randomBytes as Gp,scrypt as mc,timingSafeEqual as hc}from"crypto";import{promisify as yc}from"util";var wc=yc(mc);function vi(){return wi.join(w.home(),"password-hash")}var vc=128*1024*1024;async function Ii(){try{return(await ze.readFile(vi(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ze.readFile(vi(),"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 wc(n,o,a.length,{N:s,r,p:i,maxmem:vc});return d.length!==a.length?!1:hc(d,a)}var Ic=We.object({password:We.string().min(1),label:We.string().min(1).max(256).optional(),ttlSec:We.number().int().positive().optional()}),bc=We.object({id:We.string().optional()}).optional();function Si(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Sc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ic.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await Ii())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await bi(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=bc.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 Sc(n){return n.ip||"unknown"}import{nanoid as Gn}from"nanoid";function Jn(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 Ai}from"crypto";import*as xi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Mc(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 ie(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function zn(n,e){let t=Mi(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),$c(s,n),s}function Ci(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Wr({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=Jn(t),a=new Ae(o),d={clientId:`hydra_client_${Gn(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=Rs.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)),_c()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async l=>{let p=l??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;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(m=>m!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.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??{},g=typeof p.instructions=="string"?p.instructions:void 0,m=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 k={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(k.outputSchema=y.outputSchema),k}).filter(h=>h!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,m),{ok:!0,registered:m.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(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}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,g=typeof l.method=="string"?l.method:void 0,m=l.envelope,h=l.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=ie(e.manager,p),k=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(k)return y.dischargeClaim(k,m),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,g,m)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,g,m)};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 ie(e.manager,p).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async u=>Pc(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,g=typeof l.cwd=="string"?l.cwd:void 0,m=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,k=y&&typeof y.title=="string"?y.title:void 0;if(!g&&m){let N=e.manager.get(m);N&&(g=N.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let S=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:S,transformChain:[],title:k})).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,g=typeof l.cwd=="string"?l.cwd:void 0,m=typeof l.agentId=="string"?l.agentId:void 0;return await e.manager.forkSession(l.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{}})}),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,g=e.manager.get(p);if(g)return await g.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,g=l.until==="idle"?"idle":"turn_complete",m=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=ie(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let A=[],N=[],H=0,X=!1,J,R,P=!1,j=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(X?{entries:A,truncated:!0}:{entries:A}))};J=h.onBroadcast(q=>{let D=Mc(q);for(A.push(q),N.push(D),H+=D;A.length>0&&(A.length>1e3||H>1048576);)A.shift(),H-=N.shift()??0,X=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&j()});let B=setTimeout(j,m);typeof B.unref=="function"&&B.unref(),R=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 g=e.manager.get(p);return g&&await g.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,g=typeof l.sessionId=="string"?l.sessionId:void 0,m=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,m),{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,g=await e.manager.loadToolBlob(p,l.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>Rc(u,e)),a.onRequest("session/new",async u=>{let l=Es.parse(u),p=Ye(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(R=>typeof R=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,k=l.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Ai(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}`}]};k=[...l.mcpServers??[],P]}let S=Mi(e);S!==void 0&&(k=[...k??[],...S.descriptors]);let A;try{A=await e.manager.create({cwd:l.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:k,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:ki(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),S!==void 0&&S.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,P=e.mcpTokenRegistry;y.complete(A),A.onClose(()=>{P.unbind(R)})}S!==void 0&&S.bindToSession(A);let N,H;try{N=Vt(a,A,d),{entries:H}=await A.attach(N,"full")}catch(R){throw await A.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(A.sessionId,{sessionId:A.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of H){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let X=Wn(A),J=Qn(A);return{sessionId:A.sessionId,...X?{modes:X}:{},...J?{models:J}:{},configOptions:A.buildConfigOptions(),_meta:Vn(e.manager,A,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let l=Ts.parse(u),p=l.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ye(l._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${l.sessionId} hasResumeHints=${!!m} readonly=${h}`);let k=m?l.sessionId:await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,S=e.manager.get(k);if(!S&&h){let P=await e.manager.loadFromDisk(k);if(!P)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);let j=await e.manager.loadHistory(k),B=l.clientId??`cli_${Gn(8)}`;d.attached.set(P.hydraSessionId,{sessionId:P.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${P.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${j.length}`);for(let q of j)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:j.length,_meta:Tc(P)}}if(!S){let P=await e.manager.loadFromDisk(k),j=P;if(m&&(j={...P,hydraSessionId:l.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!j)throw _(I.SessionNotFound,`session ${l.sessionId} not found and no resume hints provided`);let B=j.originatingClient?j:{...j,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;S=await zn(e,{...q,onInstallProgress:ki(a)})}let A=Vt(a,S,d,l.clientInfo,l.clientId),N=g.replayMode==="drip",{entries:H,appliedPolicy:X}=await S.attach(A,l.historyPolicy,{afterMessageId:l.afterMessageId,raw:N,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(S.sessionId,{sessionId:S.sessionId,clientId:A.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(S.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${S.sessionId} clientId=${A.clientId} attachedCount=${d.attached.size} requestedPolicy=${l.historyPolicy} appliedPolicy=${X} replayed=${H.length} readonly=${h}${N?" replayMode=drip":""}`),N){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,j=750;(async()=>{let B=null;for(let q of H){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let he=Math.min(j,Math.max(0,(D-B)/P));he>0&&await new Promise(Zt=>setTimeout(Zt,he))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<H.length&&!a.isClosed();P++){let j=H[P],B=a.notify(j.method,j.params).catch(()=>{});(P+1)%200===0&&await B}S.replayPendingPermissions(A);let J=Wn(S),R=Qn(S);return{sessionId:S.sessionId,clientId:A.clientId,connectedClients:S.connectedClients(A.clientId),historyPolicy:X,replayed:H.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:S.buildConfigOptions(),_meta:Vn(e.manager,S)}}),a.onRequest("session/detach",async u=>{let l=_s.parse(u),p=d.attached.get(l.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(l.sessionId);return g?.detach(p.clientId),d.attached.delete(l.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(l.sessionId),{sessionId:l.sessionId,_meta:{[Ge]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let l=$s.parse(u??{});return{sessions:(await e.manager.list({cwd:l.cwd})).filter(h=>h.originatingClient?.name!==Mt).map(Fs)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return Oe(e.registry)}),a.onRequest("session/prompt",async u=>{let l=Os.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 g=e.manager.get(l.sessionId);if(!g){let m=await e.manager.loadFromDisk(l.sessionId);if(!m)throw _(I.SessionNotFound,`session ${l.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${l.sessionId}`),g=await zn(e,m);let h=Vt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,l)});let f=u=>{let l;try{l=It.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.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 g=e.manager.get(l.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${l.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",f),a.onRequest("session/cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"session/cancel"),f(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let l=js.parse(u);return c(l.sessionId,"hydra-acp/prompt/cancel"),ie(e.manager,l.sessionId).cancelQueuedPrompt(l.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let l=It.parse(u);return c(l.sessionId,"hydra-acp/session/force_cancel"),ie(e.manager,l.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let l=Hs.parse(u);return c(l.sessionId,"hydra-acp/prompt/update"),ie(e.manager,l.sessionId).updateQueuedPrompt(l.messageId,l.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let l=Bs.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 ie(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 g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let A=await e.manager.loadFromDisk(g);if(!A)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await zn(e,A)}let h=Vt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let A of y){if(a.isClosed())break;await a.notify(A.method,A.params).catch(()=>{})}m.replayPendingPermissions(h);let k=Wn(m),S=Qn(m);return{sessionId:m.sessionId,...k?{modes:k}:{},...S?{models:S}:{},configOptions:m.buildConfigOptions(),_meta:Vn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let l=u?.sessionId;typeof l=="string"&&c(l,"session/set_model");let p=Ec(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:g}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),m}),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 g=ie(e.manager,l.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(l.modeId),m}),a.onRequest("session/set_config_option",async u=>{let l=u,p=y=>_(I.InvalidParams,y),g=l?.sessionId;if(typeof g=="string"&&c(g,"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 m=ie(e.manager,l.sessionId),h=m.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!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:l.sessionId,modelId:l.value}),m.applyModelChange(l.value);break}case"mode":{l.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:l.sessionId,modeId:l.value}),m.applyModeChange(l.value);break}case"agent":{l.value!==m.agentId&&await m.setAgent(l.value);break}default:throw p(`configId ${JSON.stringify(l.configId)} is not settable`)}return{configOptions:m.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),ie(e.manager,p).forwardRequest(l,u)})})}async function Rc(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 l=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let d=a.authMethods??[],c=d.find(l=>l.id===s);if(!c){let l=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(p=>JSON.stringify(p)).join(", ")}]`)}let f=c._meta?.type;if((c.type??(f==="agent"||f==="terminal"?f:"agent"))==="terminal"){let l=c._meta?.args,p=[];if(l!==void 0){if(!Array.isArray(l))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${l===null?"null":typeof l}`);for(let y of l)if(typeof y!="string")throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);p=l}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,k]of Object.entries(process.env))typeof k=="string"&&(m[y]=k);Object.assign(m,g.env);let h=xi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g.command,args:[...g.args,...p],env:m,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}function ki(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(Us,t).catch(()=>{})}}function Wn(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 Qn(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 Ec(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=je(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 Pc(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 ie(t.manager,r).addTransformer(i),{ok:!0}}function Tc(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{[Ge]:vt(e,t)}}function Vn(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 Ve(e.agentMeta,vt(s,r))}function _c(){return{protocolVersion:1,agentInfo:{name:"hydra",version:G},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:Ve(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function $c(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 Vt(n,e,t,s,r){return{clientId:r??`cli_${Gn(8)}`,connection:n,clientInfo:s}}function Mi(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=Ai(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 Gt=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 Fc}from"crypto";import{McpServer as Oc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Nc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Q}from"zod";var Ri="Bearer ";function Yt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Ri))return;let t=e.slice(Ri.length).trim();return t.length>0?t:void 0}function jc(n){let e=new Oc({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:Q.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:Q.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:Q.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:Q.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Q.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:Q.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Q.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:Q.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Q.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Q.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Q.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Q.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Q.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Q.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Q.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Q.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 Hc=1e4;function Ei(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=jc(a),f=new Nc({sessionIdGenerator:()=>Fc()});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=Yt(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(m=>{l=setTimeout(()=>m(void 0),Hc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(l!==void 0&&clearTimeout(l),g===void 0){a.code(503).send({error:"session not ready"});return}f=g}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 Kt=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 zc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Wc}from"crypto";import{Server as Bc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Uc,ListToolsRequestSchema as Dc}from"@modelcontextprotocol/sdk/types.js";var Lc=6e4;function Pi(n,e,t,s={}){let r=s.invokeTimeoutMs??Lc,i=typeof t=="function"?async()=>t():async()=>t,o=new Bc({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(Dc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Uc,async d=>{let c=d.params.name;if(!a.has(c))return Xt(`unknown tool: ${c}`);try{let f=await i(),u=await qc(e.connection,n,c,d.params.arguments??{},f,r);return Jc(u,c)}catch(f){return Xt(f instanceof Error?f.message:String(f))}}),o}async function qc(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 Jc(n,e){if(n===null||typeof n!="object")return Xt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Xt(`extension ${e} omitted content array`)}function Xt(n){return{content:[{type:"text",text:n}],isError:!0}}var Qc=1e4;function Ti(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 k=r.get(f);if(k!==void 0){r.delete(f);for(let S of k.values())await i(S)}}));let p=l.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Pi(u,g,async()=>{let k=e.lookup(f);if(k===void 0)throw new Error("mcp token no longer bound");if(k.session!==void 0)return k.session.sessionId;let S,A=new Promise(H=>{S=setTimeout(()=>H(void 0),Qc)}),N=await Promise.race([k.sessionReady.catch(()=>{}),A]);if(S!==void 0&&clearTimeout(S),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new zc({sessionIdGenerator:()=>Wc()});return await h.connect(y),l.set(u,{server:h,transport:y}),y}async function d(f,u){let l=Yt(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 g=f.params.name,m=await a(l,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.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 Kc(n,e){Zc(n);let t=n.daemon.tls?{key:await Se.readFile(n.daemon.tls.key),cert:await Se.readFile(n.daemon.tls.cert)}:void 0;await Se.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Xc(n.daemon.logLevel),i=Vc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Gc,{options:{handleProtocols:Zn}}),un(E=>{i.log.info(E)}),pn(E=>{i.log.info(E)});let o=await Bt.load(),a=new Jt,d=new qt,c=new Lt([new Ut(e),new Dt(o),d]),f=zr({validator:c});i.addHook("onRequest",async(E,fe)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await f(E,fe)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let l=setInterval(()=>{a.sweepExpired()},300*1e3);l.unref();let p=new Qe(n,{onFetched:()=>{Or(p,y)}});Bn(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>pe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});ps(n.compressToolContent);let h=new jt,y=new ot(p,m,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:g,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),k=new Ot(os(n),void 0,{tokenRegistry:d}),S=new Nt(as(n),void 0,{tokenRegistry:d});gi(i,G,Hr(n)),fi(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port}),pi(i,p,y,{npmRegistry:n.npmRegistry}),mi(i,k),hi(i,S),yi(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]}),Si(i,{store:o,rateLimiter:a});let A=new Gt,N=new Kt;Ei(i,A),Ti(i,A,N);let H,X=()=>{if(H!==void 0)return H;let E=i.server.address(),fe=E&&typeof E=="object"?E.port:n.daemon.port;return H=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${fe}`,H};Ci(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,fe)=>k.reportVersion(E,fe),onTransformerVersion:(E,fe)=>S.reportVersion(E,fe),transformers:S,extensionCommands:h,mcpTokenRegistry:A,extensionMcp:N,getDaemonOrigin:X,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let J=i.server.address(),R=J&&typeof J=="object"?J.port:n.daemon.port;await Se.mkdir(w.home(),{recursive:!0}),await Se.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
112
- `,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",j=n.daemon.tls?"wss":"ws",B={daemonUrl:`${P}://${n.daemon.host}:${R}`,daemonHost:n.daemon.host,daemonPort:R,serviceToken:e,daemonWsUrl:`${j}://${n.daemon.host}:${R}/acp`,hydraHome:w.home()};k.setContext(B),S.setContext(B),await k.start(),await S.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let q=n.daemon.agentSyncIntervalMinutes*60*1e3,D=q>0?Nr({registry:p,manager:y,intervalMs:q,logger:g}):void 0,he=n.daemon.sessionGcIntervalMinutes*60*1e3,Zt=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Yn=he>0?jr({manager:y,intervalMs:he,maxAgeMs:Zt,logger:g}):void 0;return{app:i,manager:y,registry:p,extensions:k,transformers:S,mcpTokenRegistry:A,extensionMcp:N,processRegistry:d,shutdown:async()=>{Yn&&Yn(),D&&D(),clearInterval(u),clearInterval(l);let E=async(fe,Kn)=>{try{await Kn()}catch(en){i.log.warn(`shutdown step ${fe} failed: ${en instanceof Error?en.message:String(en)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>k.stop()),await E("transformers.stop",()=>S.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()),un(null),pn(null),Bn(null),await E("app.close",()=>i.close());try{$i.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function Xc(n){let e=await Yc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=_i.destination(2);return{stream:_i.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function Zc(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{pe as AgentInstance,Ae as JsonRpcConnection,Qe as Registry,xe as Session,ot as SessionManager,eo as defaultConfig,ji as ensureServiceToken,gt as generateServiceToken,cs as loadConfig,Ni as loadServiceToken,yn as ndjsonStreamFromStdio,w as paths,se as planSpawn,Kc as startDaemon,Zi as writeConfig,Jn as wsToMessageStream};
105
+ `),r}function Wd(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=Yr(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function Qd(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 Vd(n,e){let t=e.session,s=er(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Re(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 Gd(n,e,t){if(!e.some(c=>Yd(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 l of c.text.split(`
107
+ `))n.push(`> ${Re(l)}`);n.push(""),n.push("**Assistant:**"),n.push(""),o=!0;break}case"agent-text":d(),i+=c.text;break;case"agent-thought":{d(),a();let l=c.text.split(`
108
+ `);for(let u of l)n.push(`> _${Re(u)}_`);n.push("");break}case"tool-call":{if(d(),a(),s.has(c.toolCallId))break;s.add(c.toolCallId);let l=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};n.push(`- ${Xd(l.status)} ${Kd(l)}`),n.push("");break}case"tool-call-update":break;case"plan":{d(),a(),n.push("**Plan:**"),n.push("");for(let l of c.entries){let u=l.status==="completed"?"[x]":"[ ]";n.push(`- ${u} ${Re(l.content)}`)}n.push("");break}case"mode-changed":d(),a(),n.push(`_mode: ${Re(c.mode)}_`),n.push("");break;case"model-changed":d(),a(),n.push(`_model: ${Re(c.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Yd(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Kd(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Re(n.title)}${t}`}function Xd(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 Re(n){return n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Jn(n){return n.toLocaleString("en-US")}function ii(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 l of s){let u=l.toUpperCase();u==="AND"?o=!0:u==="OR"?a=!0:d.push(l)}o?i="AND":a&&(i="OR");let c=d.map(l=>ec(l)).filter(l=>l.term.length>0);return{operator:i,terms:c}}function ec(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:oi(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:oi(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function oi(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function tc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var nc=5,sc=200,ai=30;async function ui(n,e,t={}){let s=Zd(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??nc,i=t.maxSessions??sc,o=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),d=o?a.filter(u=>o.has(u.sessionId)):a,c=[],l=!1;for(let u of d){if(c.length>=i){l=!0;break}let f=await n.loadHistory(u.sessionId).catch(()=>[]),p=rc(f,s,r);if(p.snippets.length===0)continue;let g={sessionId:u.sessionId,cwd:u.cwd,status:u.status,updatedAt:u.updatedAt,totalMatches:p.totalMatches,snippets:p.snippets};u.title!==void 0&&(g.title=u.title),c.push(g)}return{query:e,truncated:l,results:c}}function rc(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=ic(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 ic(n,e,t,s){let r=e.toLowerCase(),i=0,o=[];for(let a of n){let d=oc(a).filter(c=>tc(t,c.kind));for(let c of d){let l=c.text.toLowerCase(),u=l.indexOf(r);if(u===-1)continue;let f=0;for(;u!==-1;)f++,u=l.indexOf(r,u+r.length);if(i+=f,o.length<s){let p=l.indexOf(r),g={kind:c.kind,text:lc(c.text,p,r.length),recordedAt:a.recordedAt};c.toolName!==void 0&&(g.toolName=c.toolName),o.push(g)}}}return{totalMatches:i,snippets:o}}function oc(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=Qt(s.content);return i?[{kind:"agent",text:i}]:[]}case"agent_thought":case"agent_thought_chunk":{let i=typeof s.text=="string"?ee(s.text):Qt(s.content);return i?[{kind:"thought",text:i}]:[]}case"user_message_chunk":{if(cc(s))return[];let i=Qt(s.content);return i?[{kind:"user",text:i}]:[]}case"prompt_received":{let i=uc(s.prompt);return i?[{kind:"user",text:i}]:[]}case"tool_call":case"tool_call_update":return ac(s);default:return[]}}function ac(n){let e=di(n,"name"),t=di(n,"title"),s=[];if(t!==void 0){let a=L(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=L(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=ci(r);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let i=n.locations;if(Array.isArray(i)&&i.length>0){let a=ci(i);if(a.length>0){let d={kind:"tool-input",text:L(a)};e!==void 0&&(d.toolName=e),s.push(d)}}let o=dc(n);if(o!==null){let a={kind:"tool",text:o};e!==void 0&&(a.toolName=e),s.push(a)}return s}function dc(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=L(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=L(s);if(r.length>0)return r}}return null}function cc(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 Qt(n){if(typeof n=="string")return ee(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ee(e.text):""}function uc(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=Qt(t);s.length>0&&e.push(s)}return e.join("")}function di(n,e){let t=n[e];return typeof t=="string"?t:void 0}function ci(n){try{return JSON.stringify(n)}catch{return""}}function lc(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-ai),d=Math.min(s.length,o+i.length+ai),c=a>0?"\u2026":"",l=d<s.length?"\u2026":"";return`${c}${s.slice(a,d)}${l}`}import{randomBytes as fc}from"crypto";function ft(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=fc(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)}}function li(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!ii(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function pi(n,e,t,s={}){n.get("/v1/sessions",async r=>{let i=r.query,o=i?.includeNonInteractive==="1"||i?.includeNonInteractive==="true";return{sessions:await e.list({cwd:i?.cwd,includeNonInteractive:o})}}),n.get("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.getOne(a);return d||(i.code(404).send({error:"session not found"}),i)}),n.post("/v1/sessions/search",async(r,i)=>{let o=r.body??{},a=typeof o.q=="string"?o.q:"";if(a.trim().length===0)return i.code(400).send({error:"q is required"}),i;let d=Array.isArray(o.sessionIds)?o.sessionIds.filter(l=>typeof l=="string"&&l.length>0):void 0;return await ui(e,a,{sessionIds:d})}),n.post("/v1/sessions",async(r,i)=>{let o=r.body??{},a=Te(o.cwd??t.cwd),d=o.agentId??t.agentId,c=ft(s),l=c!==void 0?[...o.mcpServers??[],...c.descriptors]:o.mcpServers;try{let u=await e.create({cwd:a,agentId:d,mcpServers:l});c!==void 0&&c.bindToSession(u),i.code(201).send({sessionId:u.sessionId,agentId:u.agentId,cwd:u.cwd})}catch(u){c!==void 0&&c.abandon(u instanceof Error?u:void 0),i.code(500).send({error:u.message})}}),n.post("/v1/sessions/collect",async(r,i)=>{let o=r.body??{},a=typeof o.maxAgeDays=="number"&&o.maxAgeDays>0?o.maxAgeDays*24*60*60*1e3:0,d=typeof o.limit=="number"&&o.limit>0?o.limit:1e3,c=o.selection==="explicit"||o.selection==="unpromoted"?o.selection:"unpromoted";try{let l=await Dn({manager:e,maxAgeMs:a,maxDeletions:d,selection:c,verbose:!1});i.code(200).send(l)}catch(l){i.code(500).send({error:l.message})}}),n.post("/v1/sessions/:id/kill",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(d){d.close({deleteRecord:!1}).catch(()=>{}),i.code(202).send();return}if(!await e.hasRecord(a)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(!d)return i.code(404).send({error:"session not found"}),i;let c=r.body??{},l={};(c.mode==="memory"||c.mode==="file")&&(l.mode=c.mode),typeof c.capacityBytes=="number"&&(l.capacityBytes=c.capacityBytes),typeof c.fileCapBytes=="number"&&(l.fileCapBytes=c.fileCapBytes),(l.mode??"memory")==="file"&&(l.filePathFor=u=>fi.join(pt.tmpdir(),`hydra-acp-stdin-${u}.log`));try{return d.openStream(l)}catch(u){return i.code(409).send({error:u.message}),i}}),n.post("/v1/sessions/:id/stdin",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(!d)return i.code(404).send({error:"session not found"}),i;let c=r.body??{},l=typeof c.chunk=="string"?c.chunk:"",u=c.eof===!0;try{return d.streamWrite(l,u)}catch(f){return i.code(409).send({error:f.message}),i}}),n.patch("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.body??{};if(d.priority!==void 0){let l=d.priority,u;if(l===null||l===0)u=void 0;else if(typeof l=="number"&&Number.isInteger(l)&&l>0)u=l;else{i.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(a,u)){i.code(404).send({error:"session not found"});return}i.code(204).send();return}if(d.regen===!0){if(!(e.get(a)!==void 0||await e.hasRecord(a))){i.code(404).send({error:"session not found"});return}e.scheduleSynopsis(a),i.code(202).send();return}if(typeof d.title!="string"||d.title.trim().length===0){i.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(a,d.title)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.delete("/v1/sessions/:id",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=e.get(a);if(d){await d.close({deleteRecord:!0}),i.code(204).send();return}if(!await e.deleteRecord(a)){i.code(404).send({error:"session not found"});return}i.code(204).send()}),n.get("/v1/sessions/:id/export",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.query?.tools,c=d==="references"?"references":mr(d),l=await e.exportBundle(a,c==="references"?{tools:"references"}:{});if(!l){i.code(404).send({error:"session not found"});return}let u=st({record:l.record,history:c==="summary"?hr(l.history,"summary"):l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,...l.toolBlobs!==void 0?{toolBlobs:l.toolBlobs}:{},hydraVersion:G,machine:pt.hostname(),hydraHost:li(t)}),f=new Date().toISOString().replace(/[:.]/g,"-");i.header("Content-Disposition",`attachment; filename="${a}-${f}.hydra"`),i.code(200).send(u)}),n.get("/v1/sessions/:id/diff",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.exportBundle(a);if(!d){i.code(404).send({error:"session not found"});return}let c=r.query??{},l=c.fold==="true"||c.fold==="1",u=typeof c.paths=="string"&&c.paths.length>0?new Set(c.paths.split(",").map(p=>p.trim()).filter(p=>p.length>0)):void 0,f=ni(d.history);u&&(f=f.filter(p=>u.has(p.path))),l&&(f=f.map(p=>({...p,hunks:si(p.hunks)}))),i.code(200).send(f)}),n.get("/v1/sessions/:id/tools/:hash",async(r,i)=>{let o=r.params,a=await e.resolveCanonicalId(o.id)??o.id,d=await e.loadToolBlob(a,o.hash);if(d===null){i.code(404).send({error:"tool blob not found"});return}i.header("Content-Type","text/plain; charset=utf-8"),i.code(200).send(d)}),n.get("/v1/sessions/:id/transcript",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=await e.exportBundle(a);if(!d){i.code(404).send({error:"session not found"});return}let c=st({record:d.record,history:d.history,promptHistory:d.promptHistory.length>0?d.promptHistory:void 0,hydraVersion:G,machine:pt.hostname(),hydraHost:li(t)});i.header("Content-Type","text/markdown; charset=utf-8"),i.code(200).send(ri(c))}),n.post("/v1/sessions/:id/fork",async(r,i)=>{let o=r.params.id,a=await e.resolveCanonicalId(o)??o,d=r.body??{},c={};if(d.forkAt!==void 0){if(typeof d.forkAt!="string"||d.forkAt.length===0){i.code(400).send({error:"forkAt must be a non-empty string"});return}c.forkAt=d.forkAt}if(d.cwd!==void 0){if(typeof d.cwd!="string"||d.cwd.length===0){i.code(400).send({error:"cwd must be a non-empty string"});return}c.cwd=Te(d.cwd)}if(d.agentId!==void 0){if(typeof d.agentId!="string"||d.agentId.length===0){i.code(400).send({error:"agentId must be a non-empty string"});return}c.agentId=d.agentId}if(d.title!==void 0){if(typeof d.title!="string"){i.code(400).send({error:"title must be a string"});return}c.title=d.title}try{let l=await e.forkSession(a,c);i.code(201).send(l)}catch(l){let u=l;if(u.code===I.SessionNotFound){i.code(404).send({error:u.message});return}if(u.code===I.InvalidParams||u.code===I.AgentNotInstalled){i.code(400).send({error:u.message});return}i.code(500).send({error:u.message})}}),n.post("/v1/sessions/import",async(r,i)=>{let o=r.body??{};if(o.bundle===void 0){i.code(400).send({error:"missing bundle"});return}let a;if(o.cwd!==void 0){if(typeof o.cwd!="string"||o.cwd.length===0){i.code(400).send({error:"cwd must be a non-empty string"});return}a=o.cwd}let d;try{d=Ar(o.bundle)}catch(c){i.code(400).send({error:"invalid bundle",details:c.message});return}try{let c=await e.importBundle(d,{replace:o.replace===!0,...a!==void 0?{cwd:a}:{}});i.code(201).send(c)}catch(c){let l=c;if(l.code===I.BundleAlreadyImported){i.code(409).send({error:"bundle already imported",existingSessionId:l.existingSessionId});return}i.code(500).send({error:l.message})}}),n.get("/v1/sessions/:id/history",async(r,i)=>{let o=r.params.id,a=r.query,d=a?.follow==="1"||a?.follow==="true",c=await e.resolveCanonicalId(o)??o,l=e.get(c),u,f,p=!1,g=1e4,m=[];if(l){d&&(f=l.onBroadcast(y=>{i.raw.writableEnded||(p?i.raw.write(JSON.stringify(y)+`
109
+ `):(m.push(y),m.length>g&&m.shift()))})),r.raw.on("close",()=>{f?.(),i.raw.writableEnded||i.raw.end()});try{u=await l.getHistorySnapshot()}catch(y){throw f?.(),y}}else{let y=await e.getHistory(c);if(y===void 0)return i.code(404).send({error:"session not found"}),i;u=y}i.raw.setHeader("Content-Type","application/x-ndjson"),i.raw.setHeader("Cache-Control","no-cache"),i.raw.statusCode=200;let h=new Set;for(let y of u??[]){i.raw.write(JSON.stringify(y)+`
110
+ `);let A=y;typeof A.recordedAt=="number"&&h.add(String(A.recordedAt))}for(;m.length>0;){let y=m.splice(0,m.length);for(let A of y){let k=A,b=typeof k.recordedAt=="number"?String(k.recordedAt):"";b&&h.has(b)||i.raw.write(JSON.stringify(A)+`
111
+ `)}}return p=!0,f||i.raw.end(),i})}function gi(n,e,t,s={}){n.get("/v1/agents",async()=>Oe(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 se(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 mi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var pc=/^[A-Za-z0-9._-]+$/;function Vt(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=gc(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){gt(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){gt(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){gt(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){gt(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){gt(o,d)}})}function gt(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 gc(n){let e=n.name;if(typeof e!="string"||!pc.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 hi(n,e){Vt(n,"extension",e)}function yi(n,e){Vt(n,"transformer",e)}function wi(n,e){n.get("/v1/config",async()=>e)}import{z as We}from"zod";import*as ze from"fs/promises";import*as vi from"path";import{randomBytes as Zp,scrypt as mc,timingSafeEqual as hc}from"crypto";import{promisify as yc}from"util";var wc=yc(mc);function Ii(){return vi.join(w.home(),"password-hash")}var vc=128*1024*1024;async function bi(){try{return(await ze.readFile(Ii(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Si(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await ze.readFile(Ii(),"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 wc(n,o,a.length,{N:s,r,p:i,maxmem:vc});return d.length!==a.length?!1:hc(d,a)}var Ic=We.object({password:We.string().min(1),label:We.string().min(1).max(256).optional(),ttlSec:We.number().int().positive().optional()}),bc=We.object({id:We.string().optional()}).optional();function ki(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=Sc(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let i;try{i=Ic.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await bi())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await Si(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=bc.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 Sc(n){return n.ip||"unknown"}import{nanoid as Yn}from"nanoid";function zn(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 Mc}from"crypto";import*as xi from"os";function _(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Rc(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 ie(n,e,t){let s=n.get(e);if(!s)throw _(I.SessionNotFound,t??`session ${e} not found`);return s}async function Wn(n,e){let t=ft(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),Fc(s,n),s}function Ci(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=Qr({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=zn(t),a=new Ae(o),d={clientId:`hydra_client_${Yn(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,f)=>{if(d.attached.get(u)?.readonly)throw _(I.PermissionDenied,`${f} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async u=>{let f=Es.parse(u??{});f.clientInfo?.name&&(d.clientInfo={name:f.clientInfo.name,...f.clientInfo.version!==void 0?{version:f.clientInfo.version}:{}});let p=f.clientInfo?.version;return p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p)),$c()}),i&&e.extensionCommands){let u=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async f=>{let p=f??{},g=Array.isArray(p.commands)?p.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;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(m=>m!==void 0):[];return u.register(i.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{u.clear(i.name)})}if(i&&e.extensionMcp){let u=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async f=>{let p=f??{},g=typeof p.instructions=="string"?p.instructions:void 0,m=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 A={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(A.outputSchema=y.outputSchema),A}).filter(h=>h!==void 0):[];if(m.length===0)throw new Error("register_mcp_tools requires at least one tool");return u.register(i.name,a,g,m),{ok:!0,registered:m.length}}),a.onClose(()=>{u.clear(i.name)})}i?.kind==="transformer"&&(a.onRequest("hydra-acp/transformer/initialize",async u=>{let f=u??{},p=Array.isArray(f.intercepts)?f.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(i.name,a,p),e.manager?.defaultTransformers.includes(i.name))){let g=e.transformers.resolveChain([i.name])[0];if(g)for(let m of e.manager.liveSessions())m.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(i.name)}),a.onRequest("hydra-acp/message/emit",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0,g=typeof f.method=="string"?f.method:void 0,m=f.envelope,h=f.route;if(!p||!g)throw _(-32602,"emit_message requires sessionId and method");let y=ie(e.manager,p),A=typeof f.respondsTo=="string"?f.respondsTo:void 0;if(A)return y.dischargeClaim(A,m),{ok:!0};if(h==="chain")return{ok:!0,response:await y.emitToChain(i.name,g,m)};if(h==="daemon")return{ok:!0,response:await y.emitToChain(i.name,g,m)};throw _(-32602,`unsupported route: ${JSON.stringify(h)}`)}),a.onRequest("hydra-acp/session/request_permission",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw _(-32602,"hydra-acp/session/request_permission requires sessionId");return ie(e.manager,p).requestPermissionFromClients(f)}),a.onRequest("hydra-acp/transformer/attach",async u=>Tc(u,i.name,e)),a.onRequest("hydra-acp/child_session/spawn",async u=>{let f=u??{},p=typeof f.agentId=="string"?f.agentId:e.defaultAgent,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.parentSessionId=="string"?f.parentSessionId:void 0,h=f._meta&&typeof f._meta=="object"?f._meta:void 0,y=h&&h["hydra-acp"]&&typeof h["hydra-acp"]=="object"?h["hydra-acp"]:void 0,A=y&&typeof y.title=="string"?y.title:void 0,k=y&&typeof y.model=="string"?y.model:void 0;if(!g&&m){let j=e.manager.get(m);j&&(g=j.cwd)}if(!g)throw _(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let b=typeof f.interactive=="boolean"?f.interactive:!1;return{childSessionId:(await e.manager.create({agentId:p,cwd:g,parentSessionId:m,interactive:b,transformChain:[],title:A,model:k})).sessionId}}),a.onRequest("hydra-acp/session/fork",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw _(I.InvalidParams,"fork_session requires sessionId");let p=typeof f.forkAt=="string"?f.forkAt:void 0,g=typeof f.cwd=="string"?f.cwd:void 0,m=typeof f.agentId=="string"?f.agentId:void 0;return await e.manager.forkSession(f.sessionId,{...p!==void 0?{forkAt:p}:{},...g!==void 0?{cwd:g}:{},...m!==void 0?{agentId:m}:{}})}),a.onRequest("hydra-acp/session/delete",async u=>{let f=u??{};if(typeof f.sessionId!="string")throw _(I.InvalidParams,"hydra-acp/session/delete requires sessionId");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=e.manager.get(p);if(g)return await g.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 f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0,g=f.until==="idle"?"idle":"turn_complete",m=typeof f.timeoutMs=="number"?Math.min(f.timeoutMs,18e5):3e5;if(!p)throw _(-32602,"await_child requires childSessionId");let h=ie(e.manager,p,`child session ${p} not found`);return new Promise(y=>{let b=[],N=[],j=0,K=!1,J,R,P=!1,H=()=>{P||(P=!0,clearTimeout(B),J?.(),R?.(),y(K?{entries:b,truncated:!0}:{entries:b}))};J=h.onBroadcast(q=>{let D=Rc(q);for(b.push(q),N.push(D),j+=D;b.length>0&&(b.length>1e3||j>1048576);)b.shift(),j-=N.shift()??0,K=!0;g==="turn_complete"&&q.params?.update?.sessionUpdate==="turn_complete"&&H()});let B=setTimeout(H,m);typeof B.unref=="function"&&B.unref(),R=h.onClose(()=>H())})}),a.onRequest("hydra-acp/child_session/close",async u=>{let f=u??{},p=typeof f.childSessionId=="string"?f.childSessionId:void 0;if(!p)throw _(-32602,"close_child_session requires childSessionId");let g=e.manager.get(p);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/connection/keep_alive",async u=>{let f=u??{},p=typeof f.token=="string"?f.token:void 0,g=typeof f.sessionId=="string"?f.sessionId:void 0,m=typeof f.estimatedRemainingMs=="number"?f.estimatedRemainingMs:void 0;return p&&g&&e.manager.get(g)?.keepAliveClaim(p,m),{ok:!0}})),a.onRequest("hydra-acp/session/tool_content",async u=>{let f=u??{};if(typeof f.sessionId!="string"||typeof f.hash!="string")throw _(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let p=await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,g=await e.manager.loadToolBlob(p,f.hash);if(g===null)throw _(I.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async u=>Ec(u,e)),a.onRequest("session/new",async u=>{let f=Ps.parse(u),p=Ye(u?._meta),g=Array.isArray(p.transformers)&&p.transformers.every(R=>typeof R=="string")?p.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,y,A=f.mcpServers;if(p.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=Mc(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}`}]};A=[...f.mcpServers??[],P]}let k=ft(e);k!==void 0&&(A=[...A??[],...k.descriptors]);let b;try{b=await e.manager.create({cwd:f.cwd,agentId:p.agentId??e.defaultAgent,mcpServers:A,title:p.title,agentArgs:p.agentArgs,model:p.model,onInstallProgress:Ai(a),transformChain:m,originatingClient:d.clientInfo,...p.interactive!==void 0?{interactive:p.interactive}:{},...p.env!==void 0?{forwardedEnv:p.env}:{}})}catch(R){throw y!==void 0&&y.abandon(R instanceof Error?R:void 0),k!==void 0&&k.abandon(R instanceof Error?R:void 0),R}if(h!==void 0&&y!==void 0&&e.mcpTokenRegistry!==void 0){let R=h,P=e.mcpTokenRegistry;y.complete(b),b.onClose(()=>{P.unbind(R)})}k!==void 0&&k.bindToSession(b);let N,j;try{N=Gt(a,b,d),{entries:j}=await b.attach(N,"full")}catch(R){throw await b.close({deleteRecord:!1}).catch(()=>{}),R}d.attached.set(b.sessionId,{sessionId:b.sessionId,clientId:N.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let R of j){if(a.isClosed())break;await a.notify(R.method,R.params).catch(()=>{})}})()});let K=Qn(b),J=Vn(b);return{sessionId:b.sessionId,...K?{modes:K}:{},...J?{models:J}:{},configOptions:b.buildConfigOptions(),_meta:Gn(e.manager,b,{clientId:N.clientId})}}),a.onRequest("session/attach",async u=>{let f=_s.parse(u),p=f.clientInfo?.version;p&&i&&(i.kind==="extension"?e.onExtensionVersion?.(i.name,p):e.onTransformerVersion?.(i.name,p));let g=Ye(f._meta),m=g.resume,h=g.readonly===!0,y=g.env;n.log.info(`session/attach sessionId=${f.sessionId} hasResumeHints=${!!m} readonly=${h}`);let A=m?f.sessionId:await e.manager.resolveCanonicalId(f.sessionId)??f.sessionId,k=e.manager.get(A);if(!k&&h){let P=await e.manager.loadFromDisk(A);if(!P)throw _(I.SessionNotFound,`session ${f.sessionId} not found`);let H=await e.manager.loadHistory(A),B=f.clientId??`cli_${Yn(8)}`;d.attached.set(P.hydraSessionId,{sessionId:P.hydraSessionId,clientId:B,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${P.hydraSessionId} clientId=${B} attachedCount=${d.attached.size} replayed=${H.length}`);for(let q of H)await a.notify(q.method,q.params).catch(()=>{});return{sessionId:P.hydraSessionId,clientId:B,connectedClients:[B],historyPolicy:"full",replayed:H.length,_meta:_c(P)}}if(!k){let P=await e.manager.loadFromDisk(A),H=P;if(m&&(H={...P,hydraSessionId:f.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!H)throw _(I.SessionNotFound,`session ${f.sessionId} not found and no resume hints provided`);let B=H.originatingClient?H:{...H,originatingClient:d.clientInfo},q=y!==void 0?{...B,forwardedEnv:y}:B;k=await Wn(e,{...q,onInstallProgress:Ai(a)})}let b=Gt(a,k,d,f.clientInfo,f.clientId),N=g.replayMode==="drip",{entries:j,appliedPolicy:K}=await k.attach(b,f.historyPolicy,{afterMessageId:f.afterMessageId,raw:N,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(d.attached.set(k.sessionId,{sessionId:k.sessionId,clientId:b.clientId,readonly:h}),y!==void 0&&await e.manager.setForwardedEnv(k.sessionId,y).catch(()=>{}),n.log.info(`session/attach OK sessionId=${k.sessionId} clientId=${b.clientId} attachedCount=${d.attached.size} requestedPolicy=${f.historyPolicy} appliedPolicy=${K} replayed=${j.length} readonly=${h}${N?" replayMode=drip":""}`),N){let P=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,H=750;(async()=>{let B=null;for(let q of j){let D=typeof q.recordedAt=="number"?q.recordedAt:null;if(B!==null&&D!==null){let he=Math.min(H,Math.max(0,(D-B)/P));he>0&&await new Promise(en=>setTimeout(en,he))}D!==null&&(B=D);try{await a.notify(q.method,q.params)}catch{return}}})()}else for(let P=0;P<j.length&&!a.isClosed();P++){let H=j[P],B=a.notify(H.method,H.params).catch(()=>{});(P+1)%200===0&&await B}k.replayPendingPermissions(b);let J=Qn(k),R=Vn(k);return{sessionId:k.sessionId,clientId:b.clientId,connectedClients:k.connectedClients(b.clientId),historyPolicy:K,replayed:j.length,...J?{modes:J}:{},...R?{models:R}:{},configOptions:k.buildConfigOptions(),_meta:Gn(e.manager,k)}}),a.onRequest("session/detach",async u=>{let f=$s.parse(u),p=d.attached.get(f.sessionId);if(!p)throw _(I.SessionNotFound,"client not attached to that session");let g=e.manager.get(f.sessionId);return g?.detach(p.clientId),d.attached.delete(f.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(f.sessionId),{sessionId:f.sessionId,_meta:{[Ge]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async u=>{let f=Fs.parse(u??{});return{sessions:(await e.manager.list({cwd:f.cwd})).filter(h=>h.originatingClient?.name!==Rt).map(Os)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw _(I.InternalError,"agent registry unavailable");return Oe(e.registry)}),a.onRequest("session/prompt",async u=>{let f=Ns.parse(u);c(f.sessionId,"session/prompt");let p=d.attached.get(f.sessionId);if(!p)throw n.log.warn(`session/prompt rejected: not attached sessionId=${f.sessionId} attachedKeys=[${[...d.attached.keys()].join(",")}]`),_(I.SessionNotFound,"not attached to session");let g=e.manager.get(f.sessionId);if(!g){let m=await e.manager.loadFromDisk(f.sessionId);if(!m)throw _(I.SessionNotFound,`session ${f.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${f.sessionId}`),g=await Wn(e,m);let h=Gt(a,g,d,void 0,p.clientId);await g.attach(h,"none")}return g.prompt(p.clientId,f)});let l=u=>{let f;try{f=bt.parse(u)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let p=d.attached.get(f.sessionId);if(!p)return;if(p.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${f.sessionId}`);return}let g=e.manager.get(f.sessionId);g&&g.cancel(p.clientId).catch(m=>{n.log.warn(`session/cancel for ${f.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",l),a.onRequest("session/cancel",async u=>{let f=bt.parse(u);return c(f.sessionId,"session/cancel"),l(u),null}),a.onRequest("hydra-acp/prompt/cancel",async u=>{let f=Hs.parse(u);return c(f.sessionId,"hydra-acp/prompt/cancel"),ie(e.manager,f.sessionId).cancelQueuedPrompt(f.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async u=>{let f=bt.parse(u);return c(f.sessionId,"hydra-acp/session/force_cancel"),ie(e.manager,f.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async u=>{let f=Bs.parse(u);return c(f.sessionId,"hydra-acp/prompt/update"),ie(e.manager,f.sessionId).updateQueuedPrompt(f.messageId,f.prompt)}),a.onRequest("hydra-acp/prompt/amend",async u=>{let f=Us.parse(u);c(f.sessionId,"hydra-acp/prompt/amend");let p=d.attached.get(f.sessionId);if(!p)throw _(I.SessionNotFound,"not attached to session");return ie(e.manager,f.sessionId).amendPrompt(p.clientId,f)}),a.onRequest("session/load",async u=>{let f=u??{},p=typeof f.sessionId=="string"?f.sessionId:void 0;if(!p)throw _(I.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(p)??p,m=e.manager.get(g);if(!m){let b=await e.manager.loadFromDisk(g);if(!b)throw _(I.SessionNotFound,`session ${p} not found in memory or on disk`);m=await Wn(e,b)}let h=Gt(a,m,d),{entries:y}=await m.attach(h,"pending_only");d.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let b of y){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}m.replayPendingPermissions(h);let A=Qn(m),k=Vn(m);return{sessionId:m.sessionId,...A?{modes:A}:{},...k?{models:k}:{},configOptions:m.buildConfigOptions(),_meta:Gn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async u=>{let f=u?.sessionId;typeof f=="string"&&c(f,"session/set_model");let p=Pc(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:g}=p,m=await p.session.forwardRequest("session/set_model",{...u,modelId:g});return p.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async u=>{let f=u,p=f?.sessionId;if(typeof p=="string"&&c(p,"session/set_mode"),!f||typeof f.sessionId!="string")throw _(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof f.modeId!="string")throw _(I.InvalidParams,"session/set_mode requires string modeId");let g=ie(e.manager,f.sessionId),m=await g.forwardRequest("session/set_mode",u);return g.applyModeChange(f.modeId),m}),a.onRequest("session/set_config_option",async u=>{let f=u,p=y=>_(I.InvalidParams,y),g=f?.sessionId;if(typeof g=="string"&&c(g,"session/set_config_option"),!f||typeof f.sessionId!="string")throw p("session/set_config_option requires string sessionId");if(typeof f.configId!="string")throw p("session/set_config_option requires string configId");if(typeof f.value!="string")throw p("session/set_config_option requires string value");let m=ie(e.manager,f.sessionId),h=m.buildConfigOptions().find(y=>y.id===f.configId);if(!h)throw p(`unknown configId ${JSON.stringify(f.configId)} for this session`);if(!h.options.some(y=>y.value===f.value))throw p(`value ${JSON.stringify(f.value)} is not valid for configId ${JSON.stringify(f.configId)}`);switch(f.configId){case"model":{f.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:f.sessionId,modelId:f.value}),m.applyModelChange(f.value);break}case"mode":{f.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:f.sessionId,modeId:f.value}),m.applyModeChange(f.value);break}case"agent":{f.value!==m.agentId&&await m.setAgent(f.value);break}default:throw p(`configId ${JSON.stringify(f.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(u,f)=>{if(!f.startsWith("session/")||u===null||typeof u!="object")throw _(I.MethodNotFound,`Method not found: ${f}`);let p=u.sessionId;if(typeof p!="string")throw _(I.MethodNotFound,`Method not found: ${f}`);return c(p,f),ie(e.manager,p).forwardRequest(f,u)})})}async function Ec(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 f=o??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(f)}let d=a.authMethods??[],c=d.find(f=>f.id===s);if(!c){let f=d.map(p=>p.id);throw _(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${f.map(p=>JSON.stringify(p)).join(", ")}]`)}let l=c._meta?.type;if((c.type??(l==="agent"||l==="terminal"?l:"agent"))==="terminal"){let f=c._meta?.args,p=[];if(f!==void 0){if(!Array.isArray(f))throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be a string[]; got ${f===null?"null":typeof f}`);for(let y of f)if(typeof y!="string")throw _(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} _meta.args must be string[]; got non-string entry ${JSON.stringify(y)}`);p=f}let g=await e.manager.planSpawnForAgent(a.agentId),m={};for(let[y,A]of Object.entries(process.env))typeof A=="string"&&(m[y]=A);Object.assign(m,g.env);let h=xi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g.command,args:[...g.args,...p],env:m,cwd:h}}try{return await a.connection.request("authenticate",{methodId:s})}catch(f){throw Ce(f,a)}}function Ai(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(Ds,t).catch(()=>{})}}function Qn(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 Vn(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 Pc(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=je(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 Tc(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 ie(t.manager,r).addTransformer(i),{ok:!0}}function _c(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{[Ge]:It(e,t)}}function Gn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot()};return Ve(e.agentMeta,It(s,r))}function $c(){return{protocolVersion:1,agentInfo:{name:"hydra",version:G},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:Ve(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0}})}}function Fc(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 Gt(n,e,t,s,r){return{clientId:r??`cli_${Yn(8)}`,connection:n,clientInfo:s}}var Yt=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 Oc}from"crypto";import{McpServer as Nc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as jc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as Q}from"zod";var Mi="Bearer ";function Kt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(Mi))return;let t=e.slice(Mi.length).trim();return t.length>0?t:void 0}function Hc(n){let e=new Nc({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:Q.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:Q.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:Q.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:Q.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:Q.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:Q.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:Q.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:Q.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:Q.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:Q.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:Q.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:Q.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:Q.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:Q.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:Q.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:Q.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 Bc=1e4;function Ri(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=Hc(a),l=new jc({sessionIdGenerator:()=>Oc()});await c.connect(l);let u={server:c,transport:l};return t.set(o,u),e.addDisposer(o,async()=>{t.delete(o);try{await l.close()}catch{}try{await c.close()}catch{}}),l}async function r(o,a){let d=Kt(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 l;if(c.session!==void 0)l=c.session;else{let f,p=new Promise(m=>{f=setTimeout(()=>m(void 0),Bc)}),g=await Promise.race([c.sessionReady.catch(()=>{}),p]);if(f!==void 0&&clearTimeout(f),g===void 0){a.code(503).send({error:"session not ready"});return}l=g}let u=await s(d,l);a.hijack(),await u.handleRequest(o.raw,a.raw,o.body)}let i={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.get("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)}),n.delete("/mcp/hydra-acp-stdin",i,async(o,a)=>{await r(o,a)})}var Xt=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 Wc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Qc}from"crypto";import{Server as Uc}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Dc,ListToolsRequestSchema as Lc}from"@modelcontextprotocol/sdk/types.js";var qc=6e4;function Ei(n,e,t,s={}){let r=s.invokeTimeoutMs??qc,i=typeof t=="function"?async()=>t():async()=>t,o=new Uc({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(Lc,async()=>({tools:e.tools.map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.outputSchema!==void 0?{outputSchema:d.outputSchema}:{}}))})),o.setRequestHandler(Dc,async d=>{let c=d.params.name;if(!a.has(c))return Zt(`unknown tool: ${c}`);try{let l=await i(),u=await Jc(e.connection,n,c,d.params.arguments??{},l,r);return zc(u,c)}catch(l){return Zt(l instanceof Error?l.message:String(l))}}),o}async function Jc(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 zc(n,e){if(n===null||typeof n!="object")return Zt(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Zt(`extension ${e} omitted content array`)}function Zt(n){return{content:[{type:"text",text:n}],isError:!0}}var Vc=1e4;function Pi(n,e,t,s={}){let r=new Map;async function i(l){try{await l.transport.close()}catch{}try{await l.server.close()}catch{}}function o(l){for(let u of r.values()){let f=u.get(l);f!==void 0&&(u.delete(l),i(f))}}t.onChange(l=>{o(l)});async function a(l,u){let f=r.get(l);f===void 0&&(f=new Map,r.set(l,f),e.addDisposer(l,async()=>{let A=r.get(l);if(A!==void 0){r.delete(l);for(let k of A.values())await i(k)}}));let p=f.get(u);if(p!==void 0)return p.transport;let g=t.lookup(u);if(g===void 0)return;let h=Ei(u,g,async()=>{let A=e.lookup(l);if(A===void 0)throw new Error("mcp token no longer bound");if(A.session!==void 0)return A.session.sessionId;let k,b=new Promise(j=>{k=setTimeout(()=>j(void 0),Vc)}),N=await Promise.race([A.sessionReady.catch(()=>{}),b]);if(k!==void 0&&clearTimeout(k),N===void 0)throw new Error("session not ready");return N.sessionId},s.buildOptions),y=new Wc({sessionIdGenerator:()=>Qc()});return await h.connect(y),f.set(u,{server:h,transport:y}),y}async function d(l,u){let f=Kt(l);if(f===void 0){u.code(401).send({error:"missing bearer token"});return}if(e.lookup(f)===void 0){u.code(404).send({error:"unknown mcp token"});return}let g=l.params.name,m=await a(f,g);if(m===void 0){u.code(404).send({error:`unknown mcp server: ${g}`});return}u.hijack(),await m.handleRequest(l.raw,u.raw,l.body)}let c={config:{skipAuth:!0}};n.post("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.get("/mcp/:name",c,async(l,u)=>{await d(l,u)}),n.delete("/mcp/:name",c,async(l,u)=>{await d(l,u)})}async function Xc(n,e){eu(n);let t=n.daemon.tls?{key:await Se.readFile(n.daemon.tls.key),cert:await Se.readFile(n.daemon.tls.cert)}:void 0;await Se.mkdir(w.home(),{recursive:!0});let{stream:s,fileStream:r}=await Zc(n.daemon.logLevel),i=Gc({logger:{level:n.daemon.logLevel,stream:s},https:t??null,bodyLimit:256*1024*1024});await i.register(Yc,{options:{handleProtocols:es}}),ln(E=>{i.log.info(E)}),gn(E=>{i.log.info(E)});let o=await Ut.load(),a=new zt,d=new Jt,c=new qt([new Dt(e),new Lt(o),d]),l=Wr({validator:c});i.addHook("onRequest",async(E,fe)=>{E.routeOptions.config?.skipAuth||E.url==="/acp"||E.url?.startsWith("/acp?")||await l(E,fe)});let u=setInterval(()=>{o.sweepExpired()},300*1e3);u.unref();let f=setInterval(()=>{a.sweepExpired()},300*1e3);f.unref();let p=new Qe(n,{onFetched:()=>{Nr(p,y)}});Un(E=>i.log.info(E));let g={info:E=>i.log.info(E),warn:E=>i.log.warn(E)},m=E=>pe.spawn({...E,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});gs(n.compressToolContent);let h=new Ht,y=new ot(p,m,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:g,npmRegistry:n.npmRegistry,extensionCommands:h,defaultCwd:n.defaultCwd}),A=new Nt(as(n),void 0,{tokenRegistry:d}),k=new jt(ds(n),void 0,{tokenRegistry:d});mi(i,G,Br(n));let b=new Yt,N=new Xt,j,K=()=>{if(j!==void 0)return j;let E=i.server.address(),fe=E&&typeof E=="object"?E.port:n.daemon.port;return j=`${n.daemon.tls?"https":"http"}://${n.daemon.host}:${fe}`,j};pi(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port},{extensionMcp:N,mcpTokenRegistry:b,getDaemonOrigin:K}),gi(i,p,y,{npmRegistry:n.npmRegistry}),hi(i,A),yi(i,k),wi(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]}),ki(i,{store:o,rateLimiter:a}),Ri(i,b),Pi(i,b,N),Ci(i,{validator:c,manager:y,defaultAgent:n.defaultAgent,processRegistry:d,onExtensionVersion:(E,fe)=>A.reportVersion(E,fe),onTransformerVersion:(E,fe)=>k.reportVersion(E,fe),transformers:k,extensionCommands:h,mcpTokenRegistry:b,extensionMcp:N,getDaemonOrigin:K,registry:p}),await i.listen({host:n.daemon.host,port:n.daemon.port});let J=i.server.address(),R=J&&typeof J=="object"?J.port:n.daemon.port;await Se.mkdir(w.home(),{recursive:!0}),await Se.writeFile(w.pidFile(),JSON.stringify({pid:process.pid,host:n.daemon.host,port:R,startedAt:new Date().toISOString()})+`
112
+ `,{encoding:"utf8",mode:384});let P=n.daemon.tls?"https":"http",H=n.daemon.tls?"wss":"ws",B={daemonUrl:`${P}://${n.daemon.host}:${R}`,daemonHost:n.daemon.host,daemonPort:R,serviceToken:e,daemonWsUrl:`${H}://${n.daemon.host}:${R}/acp`,hydraHome:w.home()};A.setContext(B),k.setContext(B),await A.start(),await k.start(),y.resurrectPendingQueues().catch(E=>{i.log.warn(`queue replay scan failed: ${E.message}`)});let q=n.daemon.agentSyncIntervalMinutes*60*1e3,D=q>0?jr({registry:p,manager:y,intervalMs:q,logger:g}):void 0,he=n.daemon.sessionGcIntervalMinutes*60*1e3,en=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Kn=he>0?Hr({manager:y,intervalMs:he,maxAgeMs:en,logger:g}):void 0;return{app:i,manager:y,registry:p,extensions:A,transformers:k,mcpTokenRegistry:b,extensionMcp:N,processRegistry:d,shutdown:async()=>{Kn&&Kn(),D&&D(),clearInterval(u),clearInterval(f);let E=async(fe,Xn)=>{try{await Xn()}catch(tn){i.log.warn(`shutdown step ${fe} failed: ${tn instanceof Error?tn.message:String(tn)}`)}};await E("sessionTokenStore.flush",()=>o.flush()),await E("extensions.stop",()=>A.stop()),await E("transformers.stop",()=>k.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()),ln(null),gn(null),Un(null),await E("app.close",()=>i.close());try{_i.unlinkSync(w.pidFile())}catch{}await E("fileStream.flushSync",()=>r.flushSync())}}}async function Zc(n){let e=await Kc({file:w.logFile(),size:"10m",frequency:"daily",mkdir:!0,symlink:!0}),t=Ti.destination(2);return{stream:Ti.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function eu(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{pe as AgentInstance,Ae as JsonRpcConnection,Qe as Registry,xe as Session,ot as SessionManager,Zi as defaultConfig,Ni as ensureServiceToken,mt as generateServiceToken,us as loadConfig,Oi as loadServiceToken,wn as ndjsonStreamFromStdio,w as paths,se as planSpawn,Xc as startDaemon,Xi as writeConfig,zn as wsToMessageStream};