@hydra-acp/cli 0.1.106 → 0.1.107
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +281 -282
- package/dist/index.d.ts +19 -0
- package/dist/index.js +67 -68
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
`,{encoding:"utf8",mode:384})}async function
|
|
3
|
-
`),e}import*as Q from"fs/promises";import*as Fs from"fs";import*as ae from"path";import{randomBytes as
|
|
4
|
-
`;await
|
|
5
|
-
`)}async function Ls(){return await
|
|
6
|
-
`)};function En(n){
|
|
7
|
-
`))}async function Zs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${le()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=
|
|
1
|
+
import*as xi from"fs";import*as st from"fs/promises";import*as Mi from"net";import*as Ri from"tls";import tl from"fastify";import nl from"@fastify/websocket";var Ts="acp.v1";function _s(n,e){return n.has(Ts)?Ts:!1}import Ci from"pino";import sl from"pino-roll";import*as Ie from"fs/promises";import{homedir as kn}from"os";import{z as I}from"zod";import*as N from"path";import*as In from"os";var Ti="HYDRA_ACP_HOME";function Me(n){let e=In.homedir();return e?n===e?"~":n.startsWith(e+"/")?"~"+n.slice(e.length):n:n}function _i(){if(process.env.VITEST)return"vitest";if(process.versions.bun||typeof globalThis.Bun<"u")return"bun";if(process.env.JEST_WORKER_ID!==void 0)return"jest";if(process.env.NODE_TEST_CONTEXT!==void 0)return"node:test"}function B(){let n=process.env[Ti];if(n&&n.length>0)return N.resolve(n);let e=_i();if(e)throw new Error(`HYDRA_ACP_HOME is unset under a test runner (${e}); refusing to fall back to ~/.hydra-acp. The harness must set HYDRA_ACP_HOME \u2014 vitest.setup.ts does this, but \`bun test\` bypasses the vitest config and does not. Run the suite with \`npx vitest run\`, not \`bun test\`.`);return N.join(In.homedir(),".hydra-acp")}var k={home:B,config:()=>N.join(B(),"config.json"),authToken:()=>N.join(B(),"auth-token"),remotes:()=>N.join(B(),"remotes.json"),pidFile:()=>N.join(B(),"daemon.pid"),logFile:()=>N.join(B(),"daemon.log"),currentLogFile:()=>N.join(B(),"current.log"),registryCache:()=>N.join(B(),"registry.json"),agentsDir:()=>N.join(B(),"agents"),agentLogFile:n=>N.join(B(),"agents","logs",`${n}.log`),agentInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t),agentNpmInstallDir:(n,e,t)=>N.join(B(),"agents",e,n,t,`node${process.versions.modules}`),sessionsDir:()=>N.join(B(),"sessions"),sessionDir:n=>N.join(B(),"sessions",n),sessionFile:n=>N.join(B(),"sessions",n,"meta.json"),historyFile:n=>N.join(B(),"sessions",n,"history.jsonl"),toolsDir:n=>N.join(B(),"sessions",n,"tools"),toolBlobFile:(n,e)=>N.join(B(),"sessions",n,"tools",e),queueFile:n=>N.join(B(),"sessions",n,"queue.ndjson"),tombstonesDir:()=>N.join(B(),"sessions",".tombstones"),tombstoneAgentDir:n=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n)),tombstoneFile:(n,e)=>N.join(B(),"sessions",".tombstones",encodeURIComponent(n),encodeURIComponent(e)),extensionsDir:()=>N.join(B(),"extensions"),extensionLogDir:n=>N.join(B(),"extensions",n),extensionLogFile:n=>N.join(B(),"extensions",n,"current.log"),extensionPidFile:n=>N.join(B(),"extensions",n,"extension.pid"),transformersDir:()=>N.join(B(),"transformers"),transformerLogDir:n=>N.join(B(),"transformers",n),transformerLogFile:n=>N.join(B(),"transformers",n,"current.log"),transformerPidFile:n=>N.join(B(),"transformers",n,"transformer.pid"),transformerState:(n,e)=>N.join(B(),"sessions",n,"transformer-state",e),tuiHistoryFile:n=>N.join(B(),"sessions",n,"prompt-history"),globalTuiHistoryFile:()=>N.join(B(),"prompt-history"),tuiLogFile:()=>N.join(B(),"tui.log"),shimWireLogFile:()=>N.join(B(),"shim-wire.log")};import*as $e from"fs/promises";function Et(){let n=new Uint8Array(32);crypto.getRandomValues(n);let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`hydra_token_${e}`}async function $s(){try{let e=(await $e.readFile(k.authToken(),"utf8")).trim();return e.length>0?e:void 0}catch(n){if(n.code==="ENOENT")return;throw n}}async function $i(){let n=await $s();if(!n)throw new Error(`No service token found at ${k.authToken()}. Run \`hydra-acp init\` to create one.`);return n}async function Sn(n){await $e.mkdir(k.home(),{recursive:!0}),await $e.writeFile(k.authToken(),n+`
|
|
2
|
+
`,{encoding:"utf8",mode:384})}async function Fi(){let n=await $s();if(n)return n;let e=Et();return await Sn(e),process.stderr.write(`hydra-acp: initialized ${k.authToken()} with a fresh service token.
|
|
3
|
+
`),e}import*as Q from"fs/promises";import*as Fs from"fs";import*as ae from"path";import{randomBytes as Oi}from"crypto";async function de(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 Ni(n),r=ji(s);await Q.mkdir(r,{recursive:!0});let o=`${s}.tmp-${process.pid}-${Bi()}`;try{let i={encoding:"utf8"};t.mode!==void 0&&(i.mode=t.mode),await Q.writeFile(o,e,i),await Q.rename(o,s)}catch(i){throw await Q.unlink(o).catch(()=>{}),i}if(t.mode!==void 0)try{Fs.chmodSync(s,t.mode)}catch{}}async function Ni(n){let e;try{e=await Q.lstat(n)}catch(r){if(r.code==="ENOENT")return n;throw r}if(!e.isSymbolicLink())return n;let t=await Q.readlink(n),s=ae.isAbsolute(t)?t:ae.resolve(ae.dirname(n),t);try{let r=await Q.realpath(ae.dirname(s));return ae.join(r,ae.basename(s))}catch(r){if(r.code==="ENOENT")return s;throw r}}async function ue(n){let e;try{e=await Q.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}if(e.trim().length!==0)try{return JSON.parse(e)}catch{return}}function ji(n){let e=n.lastIndexOf("/");return e<=0?".":n.slice(0,e)}function Bi(){return Oi(4).toString("hex")}var Hs="https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",Ui=I.object({cert:I.string(),key:I.string()}),Ns=55514,Di=I.object({host:I.string().default("127.0.0.1"),port:I.number().int().positive().default(Ns),logLevel:I.enum(["debug","info","warn","error"]).default("info"),tls:Ui.optional(),sessionIdleTimeoutSeconds:I.number().int().nonnegative().default(3600),sessionHistoryMaxEntries:I.number().int().positive().default(1e4),agentStderrTailBytes:I.number().int().positive().default(4096),publicHost:I.string().optional(),agentSyncIntervalMinutes:I.number().nonnegative().default(60),sessionGcIntervalMinutes:I.number().nonnegative().default(60),sessionGcMaxAgeDays:I.number().positive().default(2)}),Li=I.object({url:I.string().url().default(Hs),ttlHours:I.number().positive().default(24),pinned:I.boolean().default(!1)}),qi=I.object({name:I.string().optional(),description:I.string().optional(),command:I.string().optional(),args:I.array(I.string()).optional(),env:I.record(I.string()).optional()}),zi=I.object({packageSpec:I.string().optional()}),Ji=I.enum(["enter","alt-enter","shift-enter","ctrl-enter","alt-b","alt-f","alt-n","alt-tab","shift-tab","tab","up","down","left","right","home","end","backspace","alt-backspace","delete","ctrl-a","ctrl-b","ctrl-c","ctrl-d","ctrl-e","ctrl-f","ctrl-g","ctrl-k","ctrl-l","ctrl-n","ctrl-o","ctrl-p","ctrl-q","ctrl-r","ctrl-s","ctrl-u","ctrl-v","ctrl-t","ctrl-w","ctrl-x","ctrl-y","ctrl-underscore","alt-underscore","escape"]),Wi=I.object({repaintThrottleMs:I.number().int().nonnegative().default(1e3),maxScrollbackLines:I.number().int().positive().default(1e4),mouse:I.boolean().default(!0),inAppSelection:I.boolean().optional(),selectionClipboard:I.enum(["primary","clipboard","both"]).default("both"),openFileCommand:I.union([I.string(),I.array(I.string())]).optional(),logMaxBytes:I.number().int().positive().default(5*1024*1024),cwdColumnMaxWidth:I.number().int().positive().default(32),progressIndicator:I.boolean().default(!0),defaultEnterAction:I.enum(["enqueue","amend"]).default("amend"),showThoughts:I.boolean().default(!0),ambiguousWidth:I.enum(["auto","narrow","wide"]).default("auto"),toolContent:I.enum(["inline","references"]).default("references"),diffContextLines:I.number().int().min(0).default(3),promptHistoryMaxEntries:I.number().int().positive().default(2e3),maxToolItems:I.number().int().nonnegative().default(5),maxPlanItems:I.number().int().nonnegative().default(5),showFileUpdates:I.enum(["none","edit","diff"]).default("edit"),sessionColumns:I.array(I.enum(["session","upstream","host","state","agent","model","age","cwd","title","cost"])).nonempty().optional(),hotkeys:I.record(Ji,I.object({command:I.union([I.string(),I.array(I.string())])})).default({})}),Os=I.string().min(1).regex(/^[A-Za-z0-9._-]+$/,"extension name must be filename-safe"),Qi=I.object({command:I.array(I.string()).default([]),args:I.array(I.string()).default([]),env:I.record(I.string()).default({}),enabled:I.boolean().default(!0)}),Vi=I.object({command:I.array(I.string()).default([]),args:I.array(I.string()).default([]),env:I.record(I.string()).default({}),enabled:I.boolean().default(!0)}),js=I.object({daemon:Di.default({}),registry:Li.default({url:Hs,ttlHours:24,pinned:!1}),agents:I.record(I.string(),qi).default({}),agentOverrides:I.record(I.string(),zi).default({}),defaultAgent:I.string().default("opencode"),defaultModels:I.record(I.string(),I.string()).default({}),synopsisAgent:I.string().optional(),synopsisModel:I.string().optional(),compaction:I.object({agent:I.string().optional(),model:I.string().optional(),tailK:I.number().int().nonnegative().default(20),maxIterations:I.number().int().positive().default(3),contextFraction:I.number().min(0).max(1).default(.5),hardCeilingFraction:I.number().min(0).max(1).default(.85),absoluteFallback:I.number().int().positive().default(12e4),idleBeforePromptMs:I.number().int().nonnegative().default(3e5),modelContextWindows:I.record(I.string(),I.number().int().positive()).default({})}).default({}),defaultCwd:I.string().default("~"),compressToolContent:I.boolean().default(!0),sessionListColdLimit:I.number().int().nonnegative().default(20),extensions:I.record(Os,Qi).default({}),transformers:I.record(Os,Vi).default({}),defaultTransformers:I.array(I.string()).default([]),npmRegistry:I.string().url().optional(),tui:Wi.default({repaintThrottleMs:1e3,maxScrollbackLines:1e4,mouse:!0,logMaxBytes:5*1024*1024,cwdColumnMaxWidth:32,progressIndicator:!0,defaultEnterAction:"amend",showThoughts:!0,ambiguousWidth:"auto",toolContent:"references",diffContextLines:3,promptHistoryMaxEntries:2e3,maxToolItems:5,maxPlanItems:5,showFileUpdates:"edit",selectionClipboard:"both"})});function Bs(n){return Object.entries(n.extensions).map(([e,t])=>({name:e,...t}))}function Us(n){return Object.entries(n.transformers).map(([e,t])=>({name:e,...t}))}async function Ds(){return await Ki(),await ue(k.config())??{}}async function Ki(){let n;try{n=await Ie.lstat(k.config())}catch(e){if(e.code==="ENOENT")return;throw e}if(n.isSymbolicLink())try{await Ie.stat(k.config())}catch(e){if(e.code!=="ENOENT")throw e;let t=await Ie.readlink(k.config()).catch(()=>"<unknown>");throw new Error(`config.json at ${k.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 Gi(){let n=await Ds(),e=n.daemon,t=e&&typeof e.authToken=="string"?e.authToken:void 0;if(!t)return;let s=!1;try{await Ie.access(k.authToken()),s=!0}catch(r){if(r.code!=="ENOENT")throw r}if(s)throw new Error(`Auth token present in both ${k.authToken()} and ${k.config()} (daemon.authToken). Remove daemon.authToken from config.json to resolve.`);await Sn(t),delete e.authToken,Object.keys(e).length===0&&delete n.daemon,await de(k.config(),n,{mode:384}),process.stderr.write(`hydra-acp: migrated auth token from ${k.config()} to ${k.authToken()}.
|
|
5
|
+
`)}async function Ls(){return await Gi(),js.parse(await Ds())}async function Yi(n){await de(k.config(),n,{mode:384})}function Xi(){return js.parse({})}function Y(n){return n==="~"||n==="$HOME"?kn():n.startsWith("~/")?kn()+n.slice(1):n.startsWith("$HOME/")?kn()+n.slice(5):n}import*as V from"fs/promises";import{createHash as Zi}from"crypto";import{gzip as ea,gunzip as ta}from"zlib";import{promisify as qs}from"util";var zs=qs(ea),na=qs(ta),Js=/^[A-Za-z0-9_-]+$/,sa=/^[a-f0-9]{64}$/,An=!0;function Ws(n){An=n}function Pt(n,e){return Js.test(n)?e===void 0||sa.test(e):!1}function Tt(n,e){return`${k.toolBlobFile(n,e)}.gz`}async function Cn(n,e){if(!Pt(n))return null;let t=Zi("sha256").update(e,"utf8").digest("hex"),s=Tt(n,t),r=k.toolBlobFile(n,t);for(let a of[s,r])try{return await V.access(a),t}catch{}await V.mkdir(k.toolsDir(n),{recursive:!0});let o=An?s:r,i=An?await zs(Buffer.from(e,"utf8")):Buffer.from(e,"utf8");return await V.writeFile(o,i,{mode:384,flag:"wx"}).catch(async a=>{if(a.code!=="EEXIST")throw a}),t}async function _t(n,e){if(!Pt(n,e))return null;try{let t=await V.readFile(Tt(n,e));return(await na(t)).toString("utf8")}catch{}try{return await V.readFile(k.toolBlobFile(n,e),"utf8")}catch{return null}}async function Qs(n,e){if(!Pt(n,e))return null;try{return await V.readFile(Tt(n,e))}catch{}try{let t=await V.readFile(k.toolBlobFile(n,e));return await zs(t)}catch{return null}}async function Vs(n,e,t){if(!Pt(n,e))return;let s=Tt(n,e);try{await V.access(s);return}catch{}await V.mkdir(k.toolsDir(n),{recursive:!0}),await V.writeFile(s,t,{mode:384,flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r})}async function Ks(n){Js.test(n)&&await V.rm(k.toolsDir(n),{recursive:!0,force:!0}).catch(()=>{})}import*as ir from"fs/promises";import*as $t from"path";import{z as F}from"zod";import*as Ys from"fs";import*as X from"fs/promises";import*as Se from"path";import{spawn as Xs}from"child_process";import{Readable as ra}from"stream";function le(){let n=process.platform==="darwin"?"darwin":process.platform==="linux"?"linux":process.platform==="win32"?"windows":void 0,e=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":void 0;if(!(!n||!e))return`${n}-${e}`}function Rn(n,e=le()){if(e)return n[e]}var Fe=n=>{process.stderr.write(n+`
|
|
6
|
+
`)};function En(n){Fe=n??(e=>process.stderr.write(e+`
|
|
7
|
+
`))}async function Zs(n){if(!n.target.archive)throw new Error(`Agent ${n.agentId} has no archive URL for ${le()??"this platform"}`);if(!n.target.cmd)throw new Error(`Agent ${n.agentId} has no cmd in its binary target`);let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=k.agentInstallDir(n.agentId,e,n.version),s=Se.resolve(t,n.target.cmd);if(await Mn(s))return s;if(await oa({agentId:n.agentId,version:n.version,archiveUrl:n.target.archive,installDir:t,onProgress:n.onProgress}),!await Mn(s))throw new Error(`Agent ${n.agentId}: extracted archive did not contain ${n.target.cmd} (looked in ${t})`);return process.platform!=="win32"&&await X.chmod(s,493).catch(()=>{}),s}async function oa(n){await X.mkdir(Se.dirname(n.installDir),{recursive:!0});let e=await X.mkdtemp(`${n.installDir}.partial-`);try{Fe(`hydra-acp: downloading ${n.agentId} from ${n.archiveUrl}`);let t=await ia({url:n.archiveUrl,dir:e,agentId:n.agentId,version:n.version,onProgress:n.onProgress});Fe(`hydra-acp: extracting ${n.agentId}`),Oe(n.onProgress,{phase:"extract",agentId:n.agentId,version:n.version}),await da(t,e),await X.unlink(t).catch(()=>{});try{await X.rename(e,n.installDir)}catch(s){let r=s;if((r.code==="EEXIST"||r.code==="ENOTEMPTY")&&await Mn(n.installDir)){await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw s}Fe(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Oe(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await X.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Oe(n,e){if(n)try{n(e)}catch{}}async function ia(n){let e=aa(n.url),t=Se.join(n.dir,e),s=await fetch(n.url,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`Failed to download ${n.url}: HTTP ${s.status} ${s.statusText}`);let r=Number(s.headers.get("content-length")??"0"),o=Ys.createWriteStream(t),i=ra.fromWeb(s.body);Oe(n.onProgress,{phase:"download_start",agentId:n.agentId,version:n.version,totalBytes:r});let a=0,u=Date.now(),l=0,d=2e3,f=150;return i.on("data",p=>{a+=p.length;let c=Date.now();c-l>=f&&(l=c,Oe(n.onProgress,{phase:"download_progress",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r})),c-u>=d&&(u=c,Fe(Gs(n.agentId,a,r)))}),await new Promise((p,c)=>{i.on("error",c),o.on("error",c),o.on("finish",()=>p()),i.pipe(o)}),Fe(Gs(n.agentId,a,r,!0)),Oe(n.onProgress,{phase:"download_done",agentId:n.agentId,version:n.version,receivedBytes:a,totalBytes:r}),t}function Gs(n,e,t,s=!1){let r=(e/1e6).toFixed(1);if(t>0){let i=(t/1e6).toFixed(1),a=Math.min(100,Math.floor(e/t*100));return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r}/${i} MB (${a}%)`}return`hydra-acp: ${s?"downloaded":"downloading"} ${n} ${r} MB`}function aa(n){let e=new URL(n);return Se.posix.basename(e.pathname)||"archive"}async function da(n,e){let t=n.toLowerCase();if(t.endsWith(".tar.gz")||t.endsWith(".tgz")||t.endsWith(".tar")){await xn("tar",["-xf",n,"-C",e]);return}if(t.endsWith(".zip")){if(await ca("unzip")){await xn("unzip",["-q",n,"-d",e]);return}await xn("tar",["-xf",n,"-C",e]);return}throw new Error(`Unsupported archive format: ${n}`)}function xn(n,e){return new Promise((t,s)=>{let r=Xs(n,e,{stdio:["ignore","ignore","inherit"]});r.on("error",s),r.on("exit",(o,i)=>{if(o===0){t();return}s(new Error(`${n} ${e.join(" ")} exited with ${o!==null?`code ${o}`:`signal ${i}`}`))})})}async function ca(n){return new Promise(e=>{let t=process.platform==="win32"?"where":"which",s=Xs(t,[n],{stdio:"ignore"});s.on("error",()=>e(!1)),s.on("exit",r=>e(r===0))})}async function Mn(n){try{return await X.access(n),!0}catch{return!1}}import*as ee from"fs/promises";import*as fe from"path";import{spawn as ua}from"child_process";var Tn=n=>{process.stderr.write(n+`
|
|
8
8
|
`)};function _n(n){Tn=n??(e=>process.stderr.write(e+`
|
|
9
|
-
`))}async function tr(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=
|
|
10
|
-
stderr: ${d}`:`npm install ${n.packageSpec} failed (${u})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<ua)return await new Promise(r=>setTimeout(r,la*(e+1))),nr(n,e+1);throw t}}function pa(n){if(n.startsWith("@")){let t=n.indexOf("/");if(t===-1)return n;let r=n.slice(t+1).indexOf("@");return r===-1?n:n.slice(0,t+1+r)}let e=n.indexOf("@");return e<=0?n:n.slice(0,e)}function ma(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function sr(n,e){let t=fe.join(n,"node_modules",e,"package.json");try{let s=await ee.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function er(n){let e=fe.join(n.installDir,"node_modules",".bin"),t=fe.join(e,n.hint);if(await Re(t))return{binName:n.hint,binPath:t};let s=await sr(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[n.hint,n.basename])if(r.includes(o)){let i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let r=fe.join(e,n.basename);if(await Re(r))return{binName:n.basename,binPath:r}}}async function Re(n){try{return await ee.access(n),!0}catch{return!1}}var ga=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Ne=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),ha=F.object({"darwin-aarch64":Ne.optional(),"darwin-x86_64":Ne.optional(),"linux-aarch64":Ne.optional(),"linux-x86_64":Ne.optional(),"windows-x86_64":Ne.optional(),"windows-aarch64":Ne.optional()}),ya=F.object({package:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),wa=F.object({command:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),va=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),ba=F.object({npx:ga.optional(),binary:ha.optional(),uvx:ya.optional(),exec:wa.optional()}),Ia=F.object({id:F.string(),name:F.string(),version:F.string().optional(),description:F.string().optional(),authors:F.array(F.string()).optional(),license:F.string().optional(),icon:F.string().optional(),repository:F.string().optional(),website:F.string().optional(),distribution:ba,onboarding:va.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),rr=F.object({version:F.string(),agents:F.array(Ia),extensions:F.array(F.unknown()).optional()}),rt=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(a=>$n(a)===e);if(o)return this.applyOverride(o);let i=e.toLowerCase();if(i.length>0){let a=s.agents.filter(c=>c.id.toLowerCase().startsWith(i));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:Y(t.command??e),args:t.args?.map(Y),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:Sa(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=rr.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(S.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=rr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await de(S.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Sa(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function $n(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function je(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await Fn(i),source:s.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function Fn(n){let e=le();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Rn(n.distribution.binary,e);if(s?.cmd){let r=$t.resolve(S.agentInstallDir(n.id,e,t),s.cmd);if(await or(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??$n(n)??s.package,o=S.agentNpmInstallDir(n.id,e,t),i=$t.join(o,"node_modules",".bin",r);if(await or(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function or(n){try{return await ir.access(n),!0}catch{return!1}}async function te(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??$n(n)??r.package,a=t.onInstallProgress;return{command:await tr({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?u=>a({source:"npm",...u}):void 0}),args:o,env:r.env??{},version:s}}if(n.distribution.binary){let r=Rn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${le()??"this platform"}.`);let o=t.onInstallProgress,i=await Zs({agentId:n.id,version:s,target:r,onProgress:o?c=>o({source:"binary",...c}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Ma}from"child_process";import*as Ht from"fs";import*as br from"path";var I={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as L}from"zod";var ar=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),ka=L.enum(["full","pending_only","none","after_message"]),dr=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),cr=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),ur=L.object({sessionId:L.string(),historyPolicy:ka.default("full"),afterMessageId:L.string().optional(),clientId:L.string().optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional(),_meta:L.record(L.unknown()).optional()});import{z as H}from"zod";var lr=H.object({sessionId:H.string()}),fr=H.object({cwd:H.string().optional(),cursor:H.string().optional()}),On=H.object({used:H.number().optional(),size:H.number().optional(),costAmount:H.number().optional(),costCurrency:H.string().optional()}),zl=H.object({sessionId:H.string(),upstreamSessionId:H.string().optional(),cwd:H.string(),title:H.string().optional(),agentId:H.string().optional(),currentModel:H.string().optional(),currentUsage:On.optional(),importedFromMachine:H.string().optional(),importedFromUpstreamSessionId:H.string().optional(),parentSessionId:H.string().optional(),forkedFromSessionId:H.string().optional(),forkedFromMessageId:H.string().optional(),originatingClient:H.object({name:H.string(),version:H.string().optional()}).optional(),interactive:H.boolean().optional(),priority:H.number().int().nonnegative().optional(),updatedAt:H.string(),attachedClients:H.number().int().nonnegative(),status:H.enum(["warm","cold"]).default("warm"),busy:H.boolean().default(!1),awaitingInput:H.boolean().default(!1),compactionState:H.any().optional(),forkSynthesisState:H.enum(["running","failed"]).optional(),_meta:H.record(H.unknown()).optional()}),Aa=H.object({sessionId:H.string(),cwd:H.string(),title:H.string().optional(),updatedAt:H.string().optional(),_meta:H.record(H.unknown()).optional()}),Jl=H.object({sessions:H.array(Aa),nextCursor:H.string().optional()});function Ft(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function pr(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ot(n._meta,Ft(n))};return n.title!==void 0&&(e.title=n.title),e}var it="hydra-acp";function Ca(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function at(n){if(!n)return{};let e=n[it];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=cr.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=On.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let c={clientId:a.clientId};typeof a.name=="string"&&(c.name=a.name),typeof a.version=="string"&&(c.version=a.version),r.push({messageId:i.messageId,originator:c,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Ca(t.env);r!==void 0&&(s.env=r)}return s}function ot(n,e){return{...n??{},[it]:e}}import{z as M}from"zod";var mr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ot=M.object({sessionId:M.string()}),gr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Yl=M.object({sessionId:M.string(),messageId:M.string(),originator:gr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),Xl=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),Zl=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),hr=M.object({sessionId:M.string(),messageId:M.string()}),ef=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),yr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),tf=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),wr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),nf=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),sf=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:gr,amendedAt:M.number()});import{z as ke}from"zod";var af=ke.object({agentId:ke.string(),version:ke.string(),source:ke.enum(["binary","npm"]),phase:ke.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ke.number().optional(),totalBytes:ke.number().optional(),packageSpec:ke.string().optional()}),vr="hydra-acp/agents/install_progress",Be={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function Hn(n,e){let t="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let c of r)c(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let c=t.indexOf(`
|
|
11
|
-
`);for(;
|
|
12
|
-
`)}}),n.on("end",()=>i()),n.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let
|
|
13
|
-
`;await new Promise((
|
|
9
|
+
`))}async function tr(n){let e=le();if(!e)throw new Error(`Agent ${n.agentId}: cannot determine platform key for ${process.platform}/${process.arch}`);let t=k.agentNpmInstallDir(n.agentId,e,n.version),s=ma(n.packageSpec),r=ha(s),o={installDir:t,packageName:s,hint:n.bin,basename:r},i=fe.join(t,"node_modules",".bin",n.bin);if(await Re(i))return i;if(await Re(t)){let f=await er(o);if(f)return f.binPath}await la({agentId:n.agentId,version:n.version,packageSpec:n.packageSpec,installDir:t,registry:n.registry,onProgress:n.onProgress});let a=await er(o);if(a)return a.binPath;let u=await sr(t,s),l=typeof u=="object"&&u!==null?Object.keys(u):typeof u=="string"?[r]:[],d=l.length>0?` (package declares bins: ${l.join(", ")})`:"";throw new Error(`Agent ${n.agentId}: npm install of ${n.packageSpec} did not produce bin ${n.bin} (looked in ${t}/node_modules/.bin/)${d}`)}async function la(n){await ee.mkdir(fe.dirname(n.installDir),{recursive:!0});let e=await ee.mkdtemp(`${n.installDir}.partial-`);try{Tn(`hydra-acp: installing ${n.packageSpec} for ${n.agentId} into ${e}`),Pn(n.onProgress,{phase:"install_start",agentId:n.agentId,version:n.version,packageSpec:n.packageSpec}),await ga({packageSpec:n.packageSpec,cwd:e,registry:n.registry});try{await ee.rename(e,n.installDir)}catch(t){let s=t;if((s.code==="EEXIST"||s.code==="ENOTEMPTY")&&await Re(n.installDir)){await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),Pn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version});return}throw t}Tn(`hydra-acp: installed ${n.agentId} to ${n.installDir}`),Pn(n.onProgress,{phase:"installed",agentId:n.agentId,version:n.version})}catch(t){throw await ee.rm(e,{recursive:!0,force:!0}).catch(()=>{}),t}}function Pn(n,e){if(n)try{n(e)}catch{}}var fa=5,pa=25;function ga(n){return nr(n,0)}async function nr(n,e){try{await new Promise((t,s)=>{let r=n.registry?["--registry",n.registry]:[],o;try{o=ua("npm",["install","--no-audit","--no-fund","--silent",...r,n.packageSpec],{cwd:n.cwd,stdio:["ignore","pipe","pipe"]})}catch(a){s(a);return}let i="";o.stdout?.on("data",a=>{}),o.stderr?.setEncoding("utf8"),o.stderr?.on("data",a=>{i=(i+a).slice(-4096)}),o.on("error",a=>{if(a.code==="ENOENT"){s(new Error("npm not found on PATH (install Node.js / npm, or use a binary-distributed agent)"));return}s(a)}),o.on("exit",(a,u)=>{if(a===0){t();return}let l=a!==null?`exit code ${a}`:`signal ${u??"unknown"}`,d=i.trim();s(new Error(d?`npm install ${n.packageSpec} failed (${l})
|
|
10
|
+
stderr: ${d}`:`npm install ${n.packageSpec} failed (${l})`))})})}catch(t){if(t.code==="ETXTBSY"&&e<fa)return await new Promise(r=>setTimeout(r,pa*(e+1))),nr(n,e+1);throw t}}function ma(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 ha(n){let e=n.lastIndexOf("/");return e===-1?n:n.slice(e+1)}async function sr(n,e){let t=fe.join(n,"node_modules",e,"package.json");try{let s=await ee.readFile(t,"utf8"),r=JSON.parse(s);return typeof r.bin=="string"||typeof r.bin=="object"&&r.bin!==null&&!Array.isArray(r.bin)?r.bin:void 0}catch{return}}async function er(n){let e=fe.join(n.installDir,"node_modules",".bin"),t=fe.join(e,n.hint);if(await Re(t))return{binName:n.hint,binPath:t};let s=await sr(n.installDir,n.packageName);if(typeof s=="object"&&s!==null){let r=Object.keys(s);if(r.length===1){let o=r[0],i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}else if(r.length>1){for(let o of[n.hint,n.basename])if(r.includes(o)){let i=fe.join(e,o);if(await Re(i))return{binName:o,binPath:i}}}}if(n.basename!==n.hint){let r=fe.join(e,n.basename);if(await Re(r))return{binName:n.basename,binPath:r}}}async function Re(n){try{return await ee.access(n),!0}catch{return!1}}var ya=F.object({package:F.string(),bin:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),He=F.object({archive:F.string().url().optional(),cmd:F.string().optional(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),wa=F.object({"darwin-aarch64":He.optional(),"darwin-x86_64":He.optional(),"linux-aarch64":He.optional(),"linux-x86_64":He.optional(),"windows-x86_64":He.optional(),"windows-aarch64":He.optional()}),va=F.object({package:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),ba=F.object({command:F.string(),args:F.array(F.string()).optional(),env:F.record(F.string()).optional()}),Ia=F.object({command:F.string().optional(),url:F.string().optional(),description:F.string().optional()}),Sa=F.object({npx:ya.optional(),binary:wa.optional(),uvx:va.optional(),exec:ba.optional()}),ka=F.object({id:F.string(),name:F.string(),version:F.string().optional(),description:F.string().optional(),authors:F.array(F.string()).optional(),license:F.string().optional(),icon:F.string().optional(),repository:F.string().optional(),website:F.string().optional(),distribution:Sa,onboarding:Ia.optional(),requiredEnv:F.array(F.string().min(1)).optional()}),rr=F.object({version:F.string(),agents:F.array(ka),extensions:F.array(F.unknown()).optional()}),rt=class{constructor(e,t={}){this.config=e;this.options=t}config;options;cache;async load(){if(this.cache&&(this.isPinned()||this.isFresh(this.cache.fetchedAt)))return this.cache.data;let e=await this.readDiskCache();if(e&&(this.isPinned()||this.isFresh(e.fetchedAt)))return this.cache=e,e.data;try{let t=await this.fetchFromNetwork();return this.cache=t,await this.writeDiskCache(t),t.data}catch(t){if(e)return this.cache=e,e.data;throw t}}async refresh(){let e=await this.fetchFromNetwork();return this.cache=e,await this.writeDiskCache(e),e.data}lastFetchedAt(){return this.cache?.fetchedAt}async getAgent(e){let t=this.localAgents().find(a=>a.id===e);if(t)return t;let s=await this.load(),r=s.agents.find(a=>a.id===e);if(r)return this.applyOverride(r);let o=s.agents.find(a=>$n(a)===e);if(o)return this.applyOverride(o);let i=e.toLowerCase();if(i.length>0){let a=s.agents.filter(u=>u.id.toLowerCase().startsWith(i));if(a.length===1)return this.applyOverride(a[0])}}localAgents(){return Object.entries(this.config.agents??{}).map(([e,t])=>({id:e,name:t.name??e,description:t.description,version:"local",distribution:{exec:{command:Y(t.command??e),args:t.args?.map(Y),env:t.env}}}))}applyOverride(e){let t=this.config.agentOverrides?.[e.id];return!t?.packageSpec||!e.distribution.npx?e:{...e,version:Aa(t.packageSpec),distribution:{...e.distribution,npx:{...e.distribution.npx,package:t.packageSpec}}}}isPinned(){return this.config.registry?.pinned===!0}isFresh(e){let t=Date.now()-e,s=this.config.registry.ttlHours*60*60*1e3;return t<s}async fetchFromNetwork(){let e=await fetch(this.config.registry.url);if(!e.ok)throw new Error(`Registry fetch failed: HTTP ${e.status}`);let t=await e.json(),s=rr.parse(t),r={fetchedAt:Date.now(),raw:t,data:s},o=this.options.onFetched;return o&&Promise.resolve().then(()=>o(s)).catch(()=>{}),r}async readDiskCache(){let e=await ue(k.registryCache());if(!(!e||typeof e.fetchedAt!="number"||e.data===void 0))try{let t=rr.parse(e.data);return{fetchedAt:e.fetchedAt,raw:e.data,data:t}}catch{return}}async writeDiskCache(e){await de(k.registryCache(),{fetchedAt:e.fetchedAt,data:e.raw})}};function Aa(n){let e=n.lastIndexOf("@"),s=(e>0?n.slice(e+1):"").replace(/[^a-zA-Z0-9._-]/g,"_");return s.length>0?`pin-${s}`:"pinned"}function $n(n){let e=n.distribution.npx?.package;if(!e)return;let t=e.lastIndexOf("/"),s=t===-1?e:e.slice(t+1),r=s.lastIndexOf("@");return r<=0?s:s.slice(0,r)}async function Ne(n){let e=typeof n.localAgents=="function"?n.localAgents():[],t;try{t=await n.load()}catch(i){if(e.length===0)throw i;t={version:"local-only",agents:[]}}let s=new Set(e.map(i=>i.id)),r=[...e,...t.agents.filter(i=>!s.has(i.id))],o=await Promise.all(r.map(async i=>({id:i.id,name:i.name,version:i.version,description:i.description,distributions:Object.keys(i.distribution),installed:await Fn(i),source:s.has(i.id)?"local":"registry",...i.onboarding?{onboarding:i.onboarding}:{}})));return{version:t.version,fetchedAt:n.lastFetchedAt(),agents:o}}async function Fn(n){let e=le();if(!e)return"no";let t=n.version??"current";if(n.distribution.exec)return"yes";if(n.distribution.binary){let s=Rn(n.distribution.binary,e);if(s?.cmd){let r=$t.resolve(k.agentInstallDir(n.id,e,t),s.cmd);if(await or(r))return"yes"}}if(n.distribution.npx){let s=n.distribution.npx,r=s.bin??$n(n)??s.package,o=k.agentNpmInstallDir(n.id,e,t),i=$t.join(o,"node_modules",".bin",r);if(await or(i))return"yes"}return!n.distribution.npx&&!n.distribution.binary&&n.distribution.uvx?"lazy":"no"}async function or(n){try{return await ir.access(n),!0}catch{return!1}}async function te(n,e=[],t={}){let s=n.version??"current";if(n.distribution.npx){let r=n.distribution.npx,o=e.length>0?e:r.args??[];if(process.env.HYDRA_ACP_SKIP_NPM_PREFETCH)return{command:"npx",args:["-y",r.package,...o],env:r.env??{},version:s};let i=r.bin??$n(n)??r.package,a=t.onInstallProgress;return{command:await tr({agentId:n.id,version:s,packageSpec:r.package,bin:i,registry:t.npmRegistry,onProgress:a?l=>a({source:"npm",...l}):void 0}),args:o,env:r.env??{},version:s}}if(n.distribution.binary){let r=Rn(n.distribution.binary);if(!r)throw new Error(`Agent ${n.id} has no binary distribution for ${le()??"this platform"}.`);let o=t.onInstallProgress,i=await Zs({agentId:n.id,version:s,target:r,onProgress:o?u=>o({source:"binary",...u}):void 0}),a=e.length>0?e:r.args??[];return{command:i,args:a,env:r.env??{},version:s}}if(n.distribution.uvx){let r=n.distribution.uvx,o=e.length>0?e:r.args??[];return{command:"uvx",args:[r.package,...o],env:r.env??{},version:s}}if(n.distribution.exec){let r=n.distribution.exec,o=e.length>0?e:r.args??[];return{command:r.command,args:o,env:r.env??{},version:s}}throw new Error(`Agent ${n.id} has no usable distribution method.`)}import{spawn as Ea}from"child_process";import*as Ht from"fs";import*as br from"path";var S={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,AuthRequired:-32e3,SessionNotFound:-32001,NotAuthorisedToAttach:-32002,MultiClientNotSupported:-32003,AgentNotInstalled:-32005,BundleAlreadyImported:-32010,PermissionDenied:-32011,AlreadyAttached:-32012,StreamNotEnabled:-32013,SessionClosing:-32014};import{z as L}from"zod";var ar=L.object({protocolVersion:L.number().optional(),clientCapabilities:L.record(L.unknown()).optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional()}),Ca=L.enum(["full","pending_only","none","after_message"]),dr=L.object({cwd:L.string(),mcpServers:L.array(L.unknown()).optional(),_meta:L.record(L.unknown()).optional()}),cr=L.object({upstreamSessionId:L.string(),agentId:L.string(),cwd:L.string(),title:L.string().optional(),agentArgs:L.array(L.string()).optional()}),ur=L.object({sessionId:L.string(),historyPolicy:Ca.default("full"),afterMessageId:L.string().optional(),clientId:L.string().optional(),clientInfo:L.object({name:L.string(),version:L.string().optional()}).optional(),_meta:L.record(L.unknown()).optional()});import{z as H}from"zod";var lr=H.object({sessionId:H.string()}),fr=H.object({cwd:H.string().optional(),cursor:H.string().optional()}),On=H.object({used:H.number().optional(),size:H.number().optional(),costAmount:H.number().optional(),costCurrency:H.string().optional()}),Wl=H.object({sessionId:H.string(),upstreamSessionId:H.string().optional(),cwd:H.string(),title:H.string().optional(),agentId:H.string().optional(),currentModel:H.string().optional(),currentUsage:On.optional(),importedFromMachine:H.string().optional(),importedFromUpstreamSessionId:H.string().optional(),parentSessionId:H.string().optional(),forkedFromSessionId:H.string().optional(),forkedFromMessageId:H.string().optional(),originatingClient:H.object({name:H.string(),version:H.string().optional()}).optional(),interactive:H.boolean().optional(),priority:H.number().int().nonnegative().optional(),updatedAt:H.string(),attachedClients:H.number().int().nonnegative(),status:H.enum(["warm","cold"]).default("warm"),busy:H.boolean().default(!1),awaitingInput:H.boolean().default(!1),compactionState:H.any().optional(),forkSynthesisState:H.enum(["running","failed"]).optional(),_meta:H.record(H.unknown()).optional()}),xa=H.object({sessionId:H.string(),cwd:H.string(),title:H.string().optional(),updatedAt:H.string().optional(),_meta:H.record(H.unknown()).optional()}),Ql=H.object({sessions:H.array(xa),nextCursor:H.string().optional()});function Ft(n,e){let t={attachedClients:n.attachedClients,status:n.status,busy:n.busy,awaitingInput:n.awaitingInput};return n.cwd!==void 0&&(t.cwd=n.cwd),n.title!==void 0&&(t.title=n.title),n.agentId!==void 0&&(t.agentId=n.agentId),n.upstreamSessionId!==void 0&&(t.upstreamSessionId=n.upstreamSessionId),n.currentModel!==void 0&&(t.currentModel=n.currentModel),n.currentUsage!==void 0&&(t.currentUsage=n.currentUsage),n.importedFromMachine!==void 0&&(t.importedFromMachine=n.importedFromMachine),n.importedFromUpstreamSessionId!==void 0&&(t.importedFromUpstreamSessionId=n.importedFromUpstreamSessionId),n.parentSessionId!==void 0&&(t.parentSessionId=n.parentSessionId),n.forkedFromSessionId!==void 0&&(t.forkedFromSessionId=n.forkedFromSessionId),n.forkedFromMessageId!==void 0&&(t.forkedFromMessageId=n.forkedFromMessageId),n.originatingClient!==void 0&&(t.originatingClient=n.originatingClient),n.interactive!==void 0&&(t.interactive=n.interactive),n.priority!==void 0&&n.priority>0&&(t.priority=n.priority),n.compactionState!==void 0&&(t.compactionState=n.compactionState),n.forkSynthesisState!==void 0&&(t.forkSynthesisState=n.forkSynthesisState),e&&(e.clientId!==void 0&&(t.clientId=e.clientId),e.currentMode!==void 0&&(t.currentMode=e.currentMode),e.agentArgs!==void 0&&e.agentArgs.length>0&&(t.agentArgs=e.agentArgs),e.availableCommands!==void 0&&e.availableCommands.length>0&&(t.availableCommands=e.availableCommands),e.availableModes!==void 0&&e.availableModes.length>0&&(t.availableModes=e.availableModes),e.availableModels!==void 0&&e.availableModels.length>0&&(t.availableModels=e.availableModels),e.turnStartedAt!==void 0&&(t.turnStartedAt=e.turnStartedAt),e.agentCapabilities!==void 0&&(t.agentCapabilities=e.agentCapabilities),e.queue!==void 0&&e.queue.length>0&&(t.queue=e.queue),e.resurrected===!0&&(t.resurrected=!0)),t}function pr(n){let e={sessionId:n.sessionId,cwd:n.cwd,updatedAt:n.updatedAt,_meta:ot(n._meta,Ft(n))};return n.title!==void 0&&(e.title=n.title),e}var it="hydra-acp";function Ma(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e={};for(let[t,s]of Object.entries(n)){if(typeof t!="string"||t.length===0||typeof s!="string")return;e[t]=s}return e}function at(n){if(!n)return{};let e=n[it];if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,s={};if(typeof t.upstreamSessionId=="string"&&(s.upstreamSessionId=t.upstreamSessionId),typeof t.agentId=="string"&&(s.agentId=t.agentId),typeof t.cwd=="string"&&(s.cwd=t.cwd),typeof t.clientId=="string"&&(s.clientId=t.clientId),typeof t.readonly=="boolean"&&(s.readonly=t.readonly),(t.replayMode==="instant"||t.replayMode==="drip")&&(s.replayMode=t.replayMode),typeof t.dripSpeed=="number"&&t.dripSpeed>0&&(s.dripSpeed=t.dripSpeed),(t.toolContent==="inline"||t.toolContent==="references")&&(s.toolContent=t.toolContent),t.detachStatus==="detached"&&(s.detachStatus=t.detachStatus),typeof t.title=="string"&&(s.title=t.title),Array.isArray(t.agentArgs)&&t.agentArgs.every(r=>typeof r=="string")&&(s.agentArgs=t.agentArgs),Array.isArray(t.transformers)&&t.transformers.every(r=>typeof r=="string")&&(s.transformers=t.transformers),t.resume){let r=cr.safeParse(t.resume);r.success&&(s.resume=r.data)}if(typeof t.model=="string"&&(s.model=t.model),typeof t.currentModel=="string"&&(s.currentModel=t.currentModel),typeof t.currentMode=="string"&&(s.currentMode=t.currentMode),t.currentUsage){let r=On.safeParse(t.currentUsage);r.success&&(s.currentUsage=r.data)}if(typeof t.turnStartedAt=="number"&&t.turnStartedAt>0&&(s.turnStartedAt=t.turnStartedAt),Array.isArray(t.availableCommands)){let r=[];for(let o of t.availableCommands){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.name!="string")continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableCommands=r)}if(t.prompt&&typeof t.prompt=="object"&&!Array.isArray(t.prompt)){let r=t.prompt,o={};typeof r.queueing=="boolean"&&(o.queueing=r.queueing),typeof r.cancelling=="boolean"&&(o.cancelling=r.cancelling),typeof r.updating=="boolean"&&(o.updating=r.updating),typeof r.amending=="boolean"&&(o.amending=r.amending),typeof r.pipelining=="boolean"&&(o.pipelining=r.pipelining),s.prompt=o}if(t.agents&&typeof t.agents=="object"&&!Array.isArray(t.agents)){let r=t.agents,o={};typeof r.list=="boolean"&&(o.list=r.list),typeof r.installProgress=="boolean"&&(o.installProgress=r.installProgress),s.agents=o}if(typeof t.mcpStdin=="boolean"&&(s.mcpStdin=t.mcpStdin),typeof t.interactive=="boolean"&&(s.interactive=t.interactive),typeof t.ancillary=="boolean"&&(s.ancillary=t.ancillary),Array.isArray(t.queue)){let r=[];for(let o of t.queue){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o,a=i.originator;if(typeof i.messageId!="string"||!a||typeof a.clientId!="string"||!Array.isArray(i.prompt)||typeof i.position!="number"||typeof i.enqueuedAt!="number")continue;let u={clientId:a.clientId};typeof a.name=="string"&&(u.name=a.name),typeof a.version=="string"&&(u.version=a.version),r.push({messageId:i.messageId,originator:u,prompt:i.prompt,position:i.position,enqueuedAt:i.enqueuedAt})}r.length>0&&(s.queue=r)}if(Array.isArray(t.availableModes)){let r=[];for(let o of t.availableModes){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.id!="string")continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModes=r)}if(Array.isArray(t.availableModels)){let r=[];for(let o of t.availableModels){if(!o||typeof o!="object"||Array.isArray(o))continue;let i=o;if(typeof i.modelId!="string")continue;let a={modelId:i.modelId};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}r.length>0&&(s.availableModels=r)}if((t.status==="warm"||t.status==="cold")&&(s.status=t.status),typeof t.busy=="boolean"&&(s.busy=t.busy),typeof t.awaitingInput=="boolean"&&(s.awaitingInput=t.awaitingInput),typeof t.attachedClients=="number"&&(s.attachedClients=t.attachedClients),typeof t.resurrected=="boolean"&&(s.resurrected=t.resurrected),typeof t.importedFromMachine=="string"&&(s.importedFromMachine=t.importedFromMachine),typeof t.importedFromUpstreamSessionId=="string"&&(s.importedFromUpstreamSessionId=t.importedFromUpstreamSessionId),typeof t.parentSessionId=="string"&&(s.parentSessionId=t.parentSessionId),typeof t.forkedFromSessionId=="string"&&(s.forkedFromSessionId=t.forkedFromSessionId),typeof t.forkedFromMessageId=="string"&&(s.forkedFromMessageId=t.forkedFromMessageId),t.originatingClient&&typeof t.originatingClient=="object"&&!Array.isArray(t.originatingClient)&&typeof t.originatingClient.name=="string"){let r=t.originatingClient;s.originatingClient={name:r.name,...typeof r.version=="string"?{version:r.version}:{}}}if(t.agentCapabilities!==void 0&&(s.agentCapabilities=t.agentCapabilities),t.env!==void 0){let r=Ma(t.env);r!==void 0&&(s.env=r)}return s}function ot(n,e){return{...n??{},[it]:e}}import{z as M}from"zod";var gr=M.object({sessionId:M.string(),prompt:M.array(M.unknown()),_meta:M.record(M.unknown()).optional()}),Ot=M.object({sessionId:M.string()}),mr=M.object({clientId:M.string(),name:M.string().optional(),version:M.string().optional()}),Zl=M.object({sessionId:M.string(),messageId:M.string(),originator:mr,prompt:M.array(M.unknown()),position:M.number().int().nonnegative(),queueDepth:M.number().int().positive(),enqueuedAt:M.number()}),ef=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),tf=M.object({sessionId:M.string(),messageId:M.string(),reason:M.enum(["started","cancelled","abandoned"])}),hr=M.object({sessionId:M.string(),messageId:M.string()}),nf=M.object({cancelled:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),yr=M.object({sessionId:M.string(),messageId:M.string(),prompt:M.array(M.unknown())}),sf=M.object({updated:M.boolean(),reason:M.enum(["ok","not_found","already_running"])}),wr=M.object({sessionId:M.string(),targetMessageId:M.string(),prompt:M.array(M.unknown()),replaceQueue:M.boolean().optional(),onTargetCompleted:M.enum(["reject","send_anyway"]).optional()}),rf=M.object({amended:M.boolean(),reason:M.enum(["ok","target_completed","target_cancelled","target_not_found"]),messageId:M.string().optional()}),of=M.object({sessionId:M.string(),cancelledMessageId:M.string(),newMessageId:M.string(),prompt:M.array(M.unknown()),originator:mr,amendedAt:M.number()});import{z as ke}from"zod";var cf=ke.object({agentId:ke.string(),version:ke.string(),source:ke.enum(["binary","npm"]),phase:ke.enum(["download_start","download_progress","download_done","extract","install_start","installed"]),receivedBytes:ke.number().optional(),totalBytes:ke.number().optional(),packageSpec:ke.string().optional()}),vr="hydra-acp/agents/install_progress",je={auth:{terminal:!0},_meta:{"terminal-auth":!0}};function Hn(n,e){let t="",s=[],r=[],o=!1,i=a=>{if(!o){o=!0;for(let u of r)u(a)}};return n.setEncoding("utf8"),n.on("data",a=>{t+=a;let u=t.indexOf(`
|
|
11
|
+
`);for(;u!==-1;){let l=t.slice(0,u).trim();if(t=t.slice(u+1),l.length>0)try{let d=JSON.parse(l);for(let f of s)f(d)}catch(d){for(let f of s)f({jsonrpc:"2.0",id:null,error:{code:S.ParseError,message:`Failed to parse ndjson line: ${d.message}`}})}u=t.indexOf(`
|
|
12
|
+
`)}}),n.on("end",()=>i()),n.on("error",a=>i(a)),e.on("error",a=>i(a)),{async send(a){if(o)throw new Error("stream is closed");let u=JSON.stringify(a)+`
|
|
13
|
+
`;await new Promise((l,d)=>{e.write(u,f=>{if(f){d(f);return}l()})})},onMessage(a){s.push(a)},onClose(a){r.push(a)},async close(){e.end(),i()}}}import{nanoid as Ra}from"nanoid";var Nn=class extends Error{code="ERR_CONNECTION_CLOSED";constructor(e="connection is closed"){super(e),this.name="ConnectionClosedError"}},Ee=class n{constructor(e){this.stream=e;this.stream.onMessage(t=>this.handleIncoming(t)),this.stream.onClose(t=>this.handleClose(t))}stream;requestHandlers=new Map;defaultRequestHandler;notificationHandlers=new Map;bufferedNotifications=new Map;static MAX_BUFFERED_PER_METHOD=64;static MAX_BUFFERED_METHODS=256;pending=new Map;closed=!1;closeHandlers=[];orphanErrorHandlers=[];onRequest(e,t){this.requestHandlers.set(e,t)}setDefaultHandler(e){this.defaultRequestHandler=e}onNotification(e,t){this.notificationHandlers.set(e,t);let s=this.bufferedNotifications.get(e);if(s){this.bufferedNotifications.delete(e);for(let r of s)try{t(r.params,r.method)}catch{}}}drainBuffered(e){let s=this.bufferedNotifications.get(e)?.length??0;return this.bufferedNotifications.delete(e),s}onClose(e){this.closeHandlers.push(e)}isClosed(){return this.closed}onOrphanError(e){this.orphanErrorHandlers.push(e)}async request(e,t){return this.requestWithId(e,t).response}requestWithId(e,t){if(this.closed)throw new Nn;let s=Ra(),r={jsonrpc:"2.0",id:s,method:e,params:t},o=new Promise((i,a)=>{this.pending.set(s,{resolve:u=>i(u),reject:a}),this.stream.send(r).catch(u=>{this.pending.delete(s),a(u)})});return{id:s,response:o}}notify(e,t){if(this.closed)return Promise.resolve();let s={jsonrpc:"2.0",method:e,params:t};return this.stream.send(s)}async close(){this.closed||await this.stream.close()}fail(e){this.handleClose(e)}handleIncoming(e){"method"in e?"id"in e&&e.id!==void 0?this.handleRequest(e).catch(()=>{}):this.handleNotification(e):"id"in e?this.handleResponse(e):"error"in e&&this.handleResponse(e)}async handleRequest(e){let t=this.requestHandlers.get(e.method)??this.defaultRequestHandler;if(!t){await this.sendError(e.id,{code:S.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??S.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 Pa=4096,he=class n{agentId;version;cwd;connection;authMethods;child;get pid(){return this.child.pid}exited=!1;killed=!1;stderrTail="";stderrTailBytes;killEscalationMs;logger;fileLog;exitHandlers=[];constructor(e,t){if(this.agentId=e.agentId,this.version=e.plan.version,this.cwd=e.cwd,this.child=t,this.stderrTailBytes=e.stderrTailBytes??Pa,this.killEscalationMs=e.killEscalationMs??Ta,this.logger=e.logger,this.fileLog=_a(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
14
|
`),!t.stdout||!t.stdin)throw new Error("agent subprocess missing stdio");let s=Hn(t.stdout,t.stdin);this.connection=new Ee(s),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{if(this.stderrTail=(this.stderrTail+r).slice(-this.stderrTailBytes),this.writeLog(r),this.logger)for(let o of r.split(/\r?\n/))o.length>0&&this.logger.info(`[${e.agentId}] ${o}`);else process.stderr.write(`[${e.agentId}] ${r}`)}),t.on("error",r=>{let o=this.formatFailure(r.message);this.writeLog(`--- spawn error: ${r.message} time=${new Date().toISOString()} ---
|
|
15
15
|
`),this.connection.fail(new Error(o))}),t.on("exit",(r,o)=>{if(this.exited=!0,this.writeLog(`--- exit code=${r} signal=${o} ${this.killed?"(after kill) ":""}time=${new Date().toISOString()} ---
|
|
16
16
|
`),this.fileLog?.end(),this.fileLog=void 0,this.killed)this.logger?.info(`agent ${e.agentId} pid=${t.pid} exited after kill code=${r} signal=${o}`);else{let i=`agent ${e.agentId} exited before responding (code=${r} signal=${o})`;this.connection.fail(new Error(this.formatFailure(i))),this.logger?.warn(`agent ${e.agentId} pid=${t.pid} exited unexpectedly code=${r} signal=${o}`)}for(let i of this.exitHandlers)i(r,o)})}writeLog(e){if(this.fileLog)try{this.fileLog.write(e)}catch{}}formatFailure(e){let t=this.stderrTail.trim();return t?`${e}
|
|
17
|
-
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=
|
|
17
|
+
stderr: ${t}`:e}stderrTailText(){return this.stderrTail.trim()}static spawn(e){let t={...process.env,...e.plan.env,...e.extraEnv??{}},s=Ea(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)})}},Ea=2e3;function Pa(n){try{let e=S.agentLogFile(n);Ht.mkdirSync(br.dirname(e),{recursive:!0});let t=Ht.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Te from"fs/promises";import*as Qt from"os";import*as wt from"path";import{customAlphabet as Dd}from"nanoid";async function Ue(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=n;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(c=>c.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function De(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:o}=n;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as Fr}from"nanoid";import*as Sr from"fs/promises";var Ta=64*1024*1024,_a=1*1024*1024,Le=64*1024,$a=6e4,Fa=100,Oa=1e3,Ha=64*1024,Na=256*1024,Ir=20;function ja(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Nt=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??Ta,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(_a,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,Le));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}let c=Math.min(a,s),d={bytes:this.sliceFromRing(r,c),nextCursor:r+c};return o>0&&(d.gap=o),this.closed&&r+c>=this.writeCursor&&(d.eof=!0),d}tail(e){let t=Math.max(0,Math.min(e,Le)),s=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,Le)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,$a));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,o=0;s!==void 0&&s<t&&(o=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,c=e.caseInsensitive===!0?"i":"",u=a?new RegExp(e.pattern,c):new RegExp(ja(e.pattern),c),d=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Fa,Oa)),p=Math.max(1,Math.min(e.maxBytes??Ha,Na)),l=Math.max(0,Math.min(e.contextBefore??0,Ir)),m=Math.max(0,Math.min(e.contextAfter??0,Ir)),g=[],h=[],v=[],y=0,w=!1,b=0,A=0,x=(_,U)=>{for(let z of v)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:_,line:U}),z.remaining--,y+=U.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(u.test(U)!==d&&g.length<f){let z={cursor:_,line:U};if(l>0&&h.length>0){z.before=h.slice();for(let oe of z.before)y+=oe.line.length}y+=U.length,g.push(z),m>0&&v.push({match:z,remaining:m})}if(l>0)for(h.push({cursor:_,line:U});h.length>l;)h.shift();let P=g.length>=f&&v.length===0,j=y>=p;return P||j};for(let _=0;_<i.length;_++){if(i[_]!==10)continue;let U=i.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,x($,U)){w=!0;break}}if(!w&&b<i.length&&this.closed){let _=i.subarray(b).toString("utf8"),U=r+b;x(U,_)&&(w=!0),A=i.length}let C=Math.min(r+A,this.writeCursor),T={matches:g,truncated:w,nextCursor:C,scannedBytes:A};return o>0&&(T.gap=o),this.closed&&C>=this.writeCursor&&(T.eof=!0),T}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<t&&this.storage.copy(s,o,0,t-o),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Sr.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var qe=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],Rf=new Map(qe.map(n=>[n.verb,n]));function kr(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function ze(n,e){return jn(n,e.map(t=>t.modelId))}function jn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=kr(n),s=e.filter(o=>kr(o)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}function Ar(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let u=Bn(c);if(u?.sessionUpdate!=="tool_call_update")continue;let d=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(d!==void 0&&(e.set(d,a),u.rawInput&&typeof u.rawInput=="object"&&!Array.isArray(u.rawInput)&&Object.keys(u.rawInput).length>0&&s.set(d,u.rawInput),Array.isArray(u.content)&&u.content.length>0)){let f=t.get(d);f?f.push(...u.content):t.set(d,[...u.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let c=n[a];if(c===void 0)continue;let u=Bn(c);if(!u||typeof u.sessionUpdate!="string"){r.push(c),o=null;continue}let d=u.sessionUpdate;if(d==="agent_message_chunk"||d==="agent_thought_chunk"||d==="user_message_chunk"){o&&o.kind===d?Ua(r,o.outIndex,Ba(u.content)):(r.push(c),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let f=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let p=f!==void 0&&t.has(f)?Da(c,t.get(f)??[]):c;f!==void 0&&s.has(f)&&!La(p)&&(p=qa(p,s.get(f))),r.push(p);continue}if(d==="plan"){i!==null?r[i]=c:(r.push(c),i=r.length-1);continue}(d==="prompt_received"||d==="turn_complete")&&(i=null),r.push(c)}return r}function Bn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ba(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function Ua(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...s,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function Da(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function La(n){let t=Bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function qa(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Cr=`[older history truncated]
|
|
20
|
-
`,
|
|
21
|
-
`),t)}function Un(n){let e=
|
|
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)})}},Ta=2e3;function _a(n){try{let e=k.agentLogFile(n);Ht.mkdirSync(br.dirname(e),{recursive:!0});let t=Ht.createWriteStream(e,{flags:"a"});return t.on("error",()=>{}),t}catch{return}}import*as Te from"fs/promises";import*as Qt from"os";import*as wt from"path";import{customAlphabet as qd}from"nanoid";async function Be(n){let{agent:e,upstreamSessionId:t,persistedMode:s,agentReportedMode:r,advertisedModes:o,logger:i}=n;if(!s)return r;if(s===r)return s;if(o&&o.length>0&&!o.some(a=>a.id===s)){let a=o.map(u=>u.id).join(", ");return i?.warn(`resurrect: persisted currentMode=${JSON.stringify(s)} not in agent's availableModes ([${a}]); skipping session/set_mode, session will use ${JSON.stringify(r)}`),r}try{return i?.info(`resurrect: pushing persisted modeId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_mode",{sessionId:t,modeId:s}),i?.info(`resurrect: session/set_mode accepted, effectiveMode=${JSON.stringify(s)}`),s}catch(a){return i?.warn(`resurrect: session/set_mode rejected by agent for modeId=${JSON.stringify(s)} (${a.message}); session will use ${JSON.stringify(r)}`),r}}async function Ue(n){let{agent:e,upstreamSessionId:t,persistedModel:s,agentReportedModel:r,logger:o}=n;if(!s)return r;if(s===r)return s;try{return o?.info(`resurrect: pushing persisted modelId=${JSON.stringify(s)} to agent (agentReported=${JSON.stringify(r)})`),await e.connection.request("session/set_model",{sessionId:t,modelId:s}),o?.info(`resurrect: session/set_model accepted, effectiveModel=${JSON.stringify(s)}`),s}catch(i){return o?.warn(`resurrect: session/set_model rejected by agent for modelId=${JSON.stringify(s)} (${i.message}); session will use ${JSON.stringify(r)}`),r}}import{customAlphabet as Fr}from"nanoid";import*as Sr from"fs/promises";var $a=64*1024*1024,Fa=1*1024*1024,De=64*1024,Oa=6e4,Ha=100,Na=1e3,ja=64*1024,Ba=256*1024,Ir=20;function Ua(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Nt=class{storage;maxCapacityBytes;currentCapacityBytes;writeCursor=0;closed=!1;waiters=[];filePath;fileCapBytes;fileBytesWritten=0;fileCapReached=!1;onFileCapReached;logWriteError;fileWriteChain=Promise.resolve();constructor(e={}){if(this.maxCapacityBytes=e.capacityBytes??$a,this.maxCapacityBytes<=0)throw new Error("capacityBytes must be > 0");this.currentCapacityBytes=Math.min(Fa,this.maxCapacityBytes),this.storage=Buffer.alloc(this.currentCapacityBytes),this.filePath=e.filePath,this.fileCapBytes=e.fileCapBytes??Number.POSITIVE_INFINITY,this.onFileCapReached=e.onFileCapReached,this.logWriteError=e.logWriteError}get capacity(){return this.maxCapacityBytes}get allocatedBytes(){return this.currentCapacityBytes}get writeCursorPos(){return this.writeCursor}get oldestAvailable(){return Math.max(0,this.writeCursor-this.currentCapacityBytes)}get isClosed(){return this.closed}append(e){this.closed||e.length===0||(this.writeRing(e),this.writeCursor+=e.length,this.filePath!==void 0&&this.scheduleFileWrite(e),this.wakeWaiters("data"))}close(){this.closed||(this.closed=!0,this.wakeWaiters("eof"))}read(e,t){let s=Math.max(0,Math.min(t,De));if(s===0){let f={bytes:Buffer.alloc(0),nextCursor:e};return this.closed&&e>=this.writeCursor&&(f.eof=!0),f}let r=e,o=0,i=this.oldestAvailable;r<i&&(o=i-r,r=i);let a=this.writeCursor-r;if(a<=0){let f={bytes:Buffer.alloc(0),nextCursor:r};return o>0&&(f.gap=o),this.closed&&(f.eof=!0),f}let u=Math.min(a,s),d={bytes:this.sliceFromRing(r,u),nextCursor:r+u};return o>0&&(d.gap=o),this.closed&&r+u>=this.writeCursor&&(d.eof=!0),d}tail(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=this.writeCursor-t,o=Math.max(s,r),i=r<s;return{bytes:this.sliceFromRing(o,this.writeCursor-o),startCursor:o,endCursor:this.writeCursor,truncated:i}}head(e){let t=Math.max(0,Math.min(e,De)),s=this.oldestAvailable,r=s>0,o=s,i=Math.min(this.writeCursor,o+t);return{bytes:this.sliceFromRing(o,i-o),startCursor:o,endCursor:i,truncated:r}}waitForData(e,t){if(e<this.writeCursor)return Promise.resolve("data");if(this.closed)return Promise.resolve("eof");let s=Math.max(0,Math.min(t,Oa));return s===0?Promise.resolve("timeout"):new Promise(r=>{let o={resolve:i=>{o.timer!==void 0&&(clearTimeout(o.timer),o.timer=void 0),r(i)},timer:setTimeout(()=>{let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),o.timer=void 0,r("timeout")},s)};this.waiters.push(o)})}grep(e){let t=this.oldestAvailable,s=e.cursor,r=s??t,o=0;s!==void 0&&s<t&&(o=t-s,r=t),r>this.writeCursor&&(r=this.writeCursor);let i=this.sliceFromRing(r,this.writeCursor-r),a=e.regex??!0,u=e.caseInsensitive===!0?"i":"",l=a?new RegExp(e.pattern,u):new RegExp(Ua(e.pattern),u),d=e.invert??!1,f=Math.max(1,Math.min(e.maxMatches??Ha,Na)),p=Math.max(1,Math.min(e.maxBytes??ja,Ba)),c=Math.max(0,Math.min(e.contextBefore??0,Ir)),g=Math.max(0,Math.min(e.contextAfter??0,Ir)),m=[],h=[],v=[],y=0,w=!1,b=0,A=0,x=(_,U)=>{for(let z of v)z.remaining>0&&(z.match.after===void 0&&(z.match.after=[]),z.match.after.push({cursor:_,line:U}),z.remaining--,y+=U.length);for(;v.length>0&&v[0].remaining===0;)v.shift();if(l.test(U)!==d&&m.length<f){let z={cursor:_,line:U};if(c>0&&h.length>0){z.before=h.slice();for(let oe of z.before)y+=oe.line.length}y+=U.length,m.push(z),g>0&&v.push({match:z,remaining:g})}if(c>0)for(h.push({cursor:_,line:U});h.length>c;)h.shift();let P=m.length>=f&&v.length===0,j=y>=p;return P||j};for(let _=0;_<i.length;_++){if(i[_]!==10)continue;let U=i.subarray(b,_).toString("utf8"),$=r+b;if(b=_+1,A=b,x($,U)){w=!0;break}}if(!w&&b<i.length&&this.closed){let _=i.subarray(b).toString("utf8"),U=r+b;x(U,_)&&(w=!0),A=i.length}let C=Math.min(r+A,this.writeCursor),T={matches:m,truncated:w,nextCursor:C,scannedBytes:A};return o>0&&(T.gap=o),this.closed&&C>=this.writeCursor&&(T.eof=!0),T}wakeWaiters(e){if(this.waiters.length===0)return;let t=this.waiters;this.waiters=[];for(let s of t)s.resolve(e)}growIfNeeded(e){if(this.currentCapacityBytes>=this.maxCapacityBytes)return;let t=this.writeCursor+e;if(t<=this.currentCapacityBytes)return;let s=this.currentCapacityBytes;for(;s<t&&s<this.maxCapacityBytes;)s=Math.min(this.maxCapacityBytes,s*2);if(s===this.currentCapacityBytes)return;let r=Buffer.alloc(s);this.storage.copy(r,0,0,this.writeCursor),this.storage=r,this.currentCapacityBytes=s}writeRing(e){let t=e.length;if(this.growIfNeeded(t),t>=this.currentCapacityBytes){let o=t-this.currentCapacityBytes;e.copy(this.storage,0,o,t);return}let s=this.writeCursor%this.currentCapacityBytes,r=this.currentCapacityBytes-s;t<=r?e.copy(this.storage,s,0,t):(e.copy(this.storage,s,0,r),e.copy(this.storage,0,r,t))}sliceFromRing(e,t){if(t<=0)return Buffer.alloc(0);let s=Buffer.alloc(t),r=e%this.currentCapacityBytes,o=Math.min(t,this.currentCapacityBytes-r);return this.storage.copy(s,0,r,r+o),o<t&&this.storage.copy(s,o,0,t-o),s}scheduleFileWrite(e){let t=this.filePath;if(t===void 0||this.fileCapReached)return;let s=this.fileCapBytes-this.fileBytesWritten;if(s<=0){this.fileCapReached=!0,this.onFileCapReached?.();return}let r=e.length<=s?e:e.subarray(0,s);this.fileBytesWritten+=r.length;let o=this.fileBytesWritten>=this.fileCapBytes;this.fileWriteChain=this.fileWriteChain.then(()=>Sr.appendFile(t,r)).catch(i=>{this.logWriteError?.(i)}),o&&!this.fileCapReached&&(this.fileCapReached=!0,this.onFileCapReached?.())}async drainFileWrites(){await this.fileWriteChain.catch(()=>{})}};var Le=[{verb:"title",name:"hydra title",description:"Regenerate the session title + synopsis via the agent (or set title manually with an arg)"},{verb:"agent",name:"hydra agent",argsHint:"<agent | status>",description:"Schedule a swap to a different agent (synthesizes a brief in the target's idiom, rotates on idle); `status` reports any pending swap"},{verb:"kill",name:"hydra kill",description:"Close this session (kills the agent; record is kept so it can be resumed later)"},{verb:"restart",name:"hydra restart",description:"Restart the agent with a fresh session/new while preserving conversation history (useful when the proxy has changed available models)"},{verb:"compact",name:"hydra compact",description:"Compact this session's history. Use '/hydra compact status' to inspect current compaction state without triggering."},{verb:"uncompact",name:"hydra uncompact",description:"Roll back the most recent compaction swap (only available immediately after a swap, before any new turns)"},{verb:"config",name:"hydra config",argsHint:"[<id> [<value>]]",description:"List or set an agent-advertised configOption (model, mode, effort, etc.). With no args, lists all options; with <id>, shows its choices; with <id> <value>, applies it."}],Pf=new Map(Le.map(n=>[n.verb,n]));function kr(n){let e=n.lastIndexOf("/");return(e===-1?n:n.slice(e+1)).toLowerCase()}function qe(n,e){return jn(n,e.map(t=>t.modelId))}function jn(n,e){if(e.length===0)return{kind:"none",requested:n};if(e.includes(n))return{kind:"exact",modelId:n};let t=kr(n),s=e.filter(o=>kr(o)===t);if(s.length===1)return{kind:"resolved",modelId:s[0],requested:n};if(s.length>1)return{kind:"ambiguous",requested:n,candidates:s};let r=n.toLowerCase();if(r.length>0){let o=e.filter(i=>i.toLowerCase().includes(r));if(o.length===1)return{kind:"resolved",modelId:o[0],requested:n};if(o.length>1)return{kind:"ambiguous",requested:n,candidates:o}}return{kind:"unknown",requested:n}}function Ar(n){if(n.length===0)return n;let e=new Map,t=new Map,s=new Map;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let l=Bn(u);if(l?.sessionUpdate!=="tool_call_update")continue;let d=typeof l.toolCallId=="string"?l.toolCallId:void 0;if(d!==void 0&&(e.set(d,a),l.rawInput&&typeof l.rawInput=="object"&&!Array.isArray(l.rawInput)&&Object.keys(l.rawInput).length>0&&s.set(d,l.rawInput),Array.isArray(l.content)&&l.content.length>0)){let f=t.get(d);f?f.push(...l.content):t.set(d,[...l.content])}}let r=[],o=null,i=null;for(let a=0;a<n.length;a++){let u=n[a];if(u===void 0)continue;let l=Bn(u);if(!l||typeof l.sessionUpdate!="string"){r.push(u),o=null;continue}let d=l.sessionUpdate;if(d==="agent_message_chunk"||d==="agent_thought_chunk"||d==="user_message_chunk"){o&&o.kind===d?La(r,o.outIndex,Da(l.content)):(r.push(u),o={outIndex:r.length-1,kind:d});continue}if(o=null,d==="tool_call_update"){let f=typeof l.toolCallId=="string"?l.toolCallId:void 0;if(f!==void 0&&e.get(f)!==a)continue;let p=f!==void 0&&t.has(f)?qa(u,t.get(f)??[]):u;f!==void 0&&s.has(f)&&!za(p)&&(p=Ja(p,s.get(f))),r.push(p);continue}if(d==="plan"){i!==null?r[i]=u:(r.push(u),i=r.length-1);continue}(d==="prompt_received"||d==="turn_complete")&&(i=null),r.push(u)}return r}function Bn(n){if(n.method!=="session/update")return;let t=n.params?.update;if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Da(n){if(!n||typeof n!="object")return"";let e=n;return typeof e.text=="string"?e.text:""}function La(n,e,t){if(t.length===0)return;let s=n[e];if(s===void 0)return;let r=s.params??{},o=r.update??{},i=o.content??{},a=typeof i.text=="string"?i.text:"";n[e]={...s,params:{...r,update:{...o,content:{...i,text:a+t}}}}}function qa(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,content:e}}}}function za(n){let t=Bn(n)?.rawInput;return!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0}function Ja(n,e){let t=n.params??{},s=t.update??{};return{...n,params:{...t,update:{...s,rawInput:e}}}}var Cr=`[older history truncated]
|
|
20
|
+
`,Wa=["file_path","filePath","path","command","pattern","query"];function ze(n,e={}){let t=e.maxChars??4e5,s=[],r="",o=()=>{r.length!==0&&(s.push(`Assistant: ${r}`),r="")};for(let i of n){if(i.method!=="session/update")continue;let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let l=u.sessionUpdate;if(l==="prompt_received"){o();let d=Dn(u.prompt).trim();d.length>0&&s.push(`User: ${d}`)}else if(l==="agent_message_chunk"){let d=Ln(u.content);d.length>0&&(r+=d)}else l==="tool_call"?(o(),s.push(Un(u))):l==="turn_complete"&&o()}return o(),Ga(s.join(`
|
|
21
|
+
`),t)}function Un(n){let e=Qa(n),t=Va(n.rawInput);return t.length===0?`Tool: ${e}`:`Tool: ${e}(${t.join(", ")})`}function Qa(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Va(n){if(!n||typeof n!="object"||Array.isArray(n))return[];let e=n,t=[];for(let s of Wa){let r=e[s];typeof r=="string"&&r.length>0&&t.push(`${s}=${Ka(r,200)}`)}return t}function Dn(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(e&&typeof e=="object"){let t=e.text;if(typeof t=="string")return t}return""}).join(""):""}function Ln(n){if(!n||typeof n!="object")return"";let e=n.text;return typeof e=="string"?e:""}function Ka(n,e){return n.length<=e?n:n.slice(0,e-1)+"\u2026"}function Ga(n,e){if(n.length<=e)return n;let t=n.split(`
|
|
22
22
|
`);for(;t.length>0;){let s=Cr+t.join(`
|
|
23
|
-
`);if(s.length<=e)return s;t.shift()}return Cr}var xr="(untitled)";function qn(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??xr}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let i=dt("Open threads",t.open_threads);i.length>0&&e.push(i);let a=dt("Decisions",t.decisions);a.length>0&&e.push(a);let
|
|
23
|
+
`);if(s.length<=e)return s;t.shift()}return Cr}var xr="(untitled)";function qn(n){let e=[],t=n.synopsis;if(t!==void 0){e.push("--- begin prior session compaction ---"),e.push(`[Title] ${n.title??xr}`),t.goal!==void 0&&t.goal.trim().length>0&&e.push(`[Goal] ${t.goal}`),t.outcome!==void 0&&t.outcome.trim().length>0&&e.push(`[Outcome] ${t.outcome}`);let i=dt("Open threads",t.open_threads);i.length>0&&e.push(i);let a=dt("Decisions",t.decisions);a.length>0&&e.push(a);let u=dt("File edit intentions",t.file_edit_intentions);u.length>0&&e.push(u);let l=dt("Unresolved errors",t.unresolved_errors);l.length>0&&e.push(l);let d=dt("Tool state",t.tool_state);d.length>0&&e.push(d);let f=Mr(t.files_touched);f.length>0&&e.push(`[Files previously touched] ${f}`);let p=Mr(t.tools_used);p.length>0&&e.push(`[Tools previously used] ${p}`),e.push("--- end prior session compaction ---")}else e.push(`[Title] ${n.title??xr}`);let{closedText:s,openText:r,keptCount:o}=Ya(n.tail,n.tailK,n.watermark??0,n.tailFloor??0);return e.push("--- begin recent turns (verbatim, last "+o+") ---"),s.length>0&&e.push(s),e.push("--- end recent turns ---"),r.length>0&&(e.push("--- begin current in-flight turn (no completion yet) ---"),e.push(r),e.push("--- end current in-flight turn ---")),e.push(""),t!==void 0?e.push("(Hydra has compacted earlier conversation. Do NOT call any tools yet. Do NOT read any files, run any commands, or invoke hydra-recall. Reply with the single word 'OK' and wait for the next user message \u2014 at that point you can use the hydra-recall tools to look up specifics on demand if needed.)"):e.push("(This is a side conversation forked from another session. The turns above are the most recent; earlier history is available on demand via the hydra-recall tools. Do NOT call any tools yet. Do NOT read any files or run any commands. Reply with the single word 'OK' and wait for the next user message.)"),e.join(`
|
|
24
24
|
`)}function dt(n,e){if(!e||!Array.isArray(e))return"";let t=e.filter(r=>typeof r=="string"&&r.trim().length>0);if(t.length===0)return"";let s=t.map(r=>"- "+r.trim());return`[${n}] ${s.join(`
|
|
25
|
-
`)}`}function Mr(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function
|
|
26
|
-
`)}function
|
|
25
|
+
`)}`}function Mr(n){if(!n||!Array.isArray(n))return"";let e=n.filter(t=>typeof t=="string"&&t.trim().length>0);return e.length===0?"":e.map(t=>t.trim()).join(", ")}function Ya(n,e,t,s){if(n.length===0)return{closedText:"",openText:"",keptCount:0};let{closed:r,open:o}=Xa(n),i=0,a=[];if(e>0&&r.length>0){let d=r.filter(c=>c.startEntryIndex>=t).length,f=Math.max(d,s),p=Math.min(f,e,r.length);i=p,a=p>0?r.slice(-p):[]}let u=a.length>0?Rr(a):"",l=o?Rr([o]):"";return{closedText:u,openText:l,keptCount:i}}function Rr(n){let e=[];for(let t of n){t.user.length>0&&e.push("User: "+t.user),t.agent.length>0&&e.push("Assistant: "+t.agent);for(let s of t.tools)e.push(s)}return e.join(`
|
|
26
|
+
`)}function Xa(n){let e=[],t=null;for(let r=0;r<n.length;r++){let o=n[r];if(o.method!=="session/update")continue;let a=o.params?.update;if(!a||typeof a.sessionUpdate!="string")continue;let u=a.sessionUpdate;if(u==="prompt_received")t!==null&&t.user.length>0&&e.push(t),t={user:Dn(a.prompt).trim(),agent:"",tools:[],startEntryIndex:r};else if(u==="agent_message_chunk"&&t!==null){let l=Ln(a.content);l.length>0&&(t.agent+=l)}else u==="tool_call"&&t!==null?t.tools.push(Un(a)):u==="turn_complete"&&t!==null&&(e.push(t),t=null)}let s=t!==null&&t.user.length>0?t:null;return{closed:e,open:s}}import*as pe from"fs/promises";async function ct(n,e){let t=k.queueFile(n);if(e.length===0){await pe.unlink(t).catch(()=>{});return}await pe.mkdir(k.sessionDir(n),{recursive:!0});let s=e.map(r=>JSON.stringify(r)).join(`
|
|
27
27
|
`)+`
|
|
28
|
-
`;await pe.writeFile(t,s,"utf8")}async function Er(n){let e=
|
|
29
|
-
`))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Pr(n){let e=S.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as jr from"fs/promises";var Or="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hr=Fr(Or,16),zn=Fr(Or,16),Ya=20,Xa=20,Za=5,ye="hydra_session_";function Ae(){return`m_${Hr()}`}function Nr(n){return n.startsWith(ye)?n.slice(ye.length):n}var ed=1e3,jt=300*1e3,td=64,Pe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${ye}${Hr()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??ed,this.compactEvery=Math.max(1,Math.floor(this.historyMaxEntries*.2)),this.updatedAt=Date.now(),this.createdAt=e.createdAt??this.updatedAt,this.lastRecordedAt=this.updatedAt,this.wireAgent(this.agent),this.scheduleIdleCheck(),this.notifyChain("session.opened",{})}broadcastMergedCommands(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_commands_update",availableCommands:this.mergedAvailableCommands()}})}broadcastAvailableModes(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"available_modes_update",availableModes:this.agentAdvertisedModes}})}broadcastAvailableModels(){let e={sessionUpdate:"current_model_update",availableModels:[...this.agentAdvertisedModels]};this.currentModel!==void 0&&this.currentModel.length>0&&(e.currentModel=this.currentModel),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:e})}wireAgent(e){e.connection.onNotification("session/update",t=>{if(this.internalPromptCapture){ad(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=_r(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let o=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let d=s;d<this.transformChain.length;d++){let f=this.transformChain[d];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${zn()}`,l;try{l=await f.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(g){this.logger?.warn(`transformer ${f.name} error on ${a}: ${g.message}`);continue}let m=l?.action??"continue";if(m==="stop")return;if(m==="processing"){let g=d,h=i,v=new Set(t),y=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:f.name}),this.runResponseChain(h,new Set([...v,f.name]),g+1,y).then(()=>w()).catch(()=>w()))},jt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:y,envelope:h,chainIdx:g,originatedBy:v,side:"response"})});return}l?.payload&&typeof l.payload=="object"&&(i=l.payload),t.add(f.name)}if(r!=="session/update")return;let c=dd(i);if(c!==null){this.setAgentAdvertisedCommands(c);return}let u=id(i);if(u!==null){this.setAgentAdvertisedModes(u);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,o=r!==this.agentId,i=this.cwd,a=this.agentArgs,c=this.forwardedEnv,u=this.currentModel,d=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],l=await f({agentId:r,cwd:i,agentArgs:a,...c?{forwardedEnv:c}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(l.agent),o||(await De({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedModel:u,agentReportedModel:l.initialModel,logger:this.logger}),await Ue({agent:l.agent,upstreamSessionId:l.upstreamSessionId,persistedMode:d,agentReportedMode:l.initialMode,logger:this.logger})),l.agent.connection.drainBuffered("session/update");let m=[];if(this.historyStore)try{m=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let g=qn({synopsis:e.artifact,title:e.title,tail:m,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await l.agent.connection.request("session/prompt",{sessionId:l.upstreamSessionId,prompt:[{type:"text",text:g}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${g.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let h=this.upstreamSessionId,v=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=l.agent,this.upstreamSessionId=l.upstreamSessionId,this.agentMeta=l.agentMeta,this.agentCapabilities=l.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=l.initialModel,this.currentMode=l.initialMode,this.setAgentAdvertisedModels(l.initialModels??[]),this.setAgentAdvertisedModes(l.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(x){this.logger?.warn(`swapUpstream: agentChange handler failed: ${x.message}`)}if(!o&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...v!==void 0?{previousSummarizedThroughEntry:v}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await y.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),o||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),o&&this.broadcastAgentSwitch(s,r);let w=o?`
|
|
28
|
+
`;await pe.writeFile(t,s,"utf8")}async function Er(n){let e=k.queueFile(n),t;try{t=await pe.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t.split(`
|
|
29
|
+
`))if(r.trim())try{let o=JSON.parse(r);o&&typeof o.messageId=="string"&&Array.isArray(o.prompt)&&typeof o.enqueuedAt=="number"&&s.push(o)}catch{}return s}async function Pr(n){let e=k.queueFile(n);await pe.unlink(e).catch(()=>{})}import*as jr from"fs/promises";var Or="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Hr=Fr(Or,16),zn=Fr(Or,16),Za=20,ed=20,td=5,ye="hydra_session_";function Ae(){return`m_${Hr()}`}function Nr(n){return n.startsWith(ye)?n.slice(ye.length):n}var nd=1e3,jt=300*1e3,sd=64,Pe=class n{sessionId;cwd;agentId;agent;upstreamSessionId;agentMeta;agentCapabilities;agentArgs;parentSessionId;forkedFromSessionId;forkedFromMessageId;forkSynthesisState;originatingClient;_interactive;get interactive(){return this._interactive}_priority;get priority(){return this._priority}title;_summarizedThroughEntry;get summarizedThroughEntry(){return this._summarizedThroughEntry}set summarizedThroughEntry(e){this._summarizedThroughEntry=e}currentModel;currentMode;compactionState;_currentUsage;updatedAt;createdAt;clients=new Map;historyStore;promptQueue=[];currentEntry;promptInFlight=!1;modeChangeInFlight=!1;modelChangeInFlight=!1;queueWriteChain=Promise.resolve();closed=!1;closing=!1;closeInFlight;deleteRecordIntent=!1;closeHandlers=[];titleHandlers=[];scheduleSynopsisHook;scheduleCompactionHook;resolveAgentIdHook;getCompactionStateHook;getPendingAgentSwapHook;_liveCompactionPhase;broadcastHandlers=[];lastCancelAt=0;static CANCEL_ERROR_WINDOW_MS=2e3;forceCancelling=!1;_firstPromptSeeded=!1;get firstPromptSeeded(){return this._firstPromptSeeded}promptStartedAt;appendCount=0;historyMaxEntries;compactEvery;permissionCallbacks=new Map;attentionFlags=new Map;get hasPermissionFlag(){for(let e of this.attentionFlags.values())if(e.source==="daemon"&&e.reason.startsWith("permission:"))return!0;return!1}attentionFlagsChangeHandlers=[];internalPromptCapture;idleTimeoutMs;idleTimer;idleEventTimeoutMs;idleHandlers=[];lastRecordedAt;spawnReplacementAgent;mintMcpServersForSwap;loadExistingAgentSession;clearRollbackBreadcrumbHook;onCompactionSwapHook;uncompactHook;mcpServersConfig;forwardedEnv;listSessions;logger;transformChain;extensionCommands;extensionCommandsUnsub;pendingClaims=new Map;toolCompletionSeen=new Map;toolCallKind=new Map;filesEditedSeen=new Set;agentChangeHandlers=[];agentAdvertisedCommands=[];agentAdvertisedModes=[];agentAdvertisedModels=[];agentAdvertisedConfigOptions=[];agentCommandsHandlers=[];agentModesHandlers=[];agentModelsHandlers=[];availableAgentsFn;modelHandlers=[];modeHandlers=[];interactiveHandlers=[];priorityHandlers=[];usageHandlers=[];cumulativeCost=0;get currentUsage(){if(!this._currentUsage&&!this.cumulativeCost)return;let e=this._currentUsage??{},t=this.cumulativeCost+(e.costAmount??0);return{...e,costAmount:t||void 0,cumulativeCost:void 0}}amendInProgress;inFlightExtensionDispatches=new Map;recentlyTerminal=new Map;streamBuffer;streamFilePath;constructor(e){if(this.sessionId=e.sessionId??`${ye}${Hr()}`,this.cwd=e.cwd,this.agentId=e.agentId,this.agent=e.agent,this.upstreamSessionId=e.upstreamSessionId,this.agentMeta=e.agentMeta,this.agentCapabilities=e.agentCapabilities,this.agentArgs=e.agentArgs,this.parentSessionId=e.parentSessionId,this.forkedFromSessionId=e.forkedFromSessionId,this.forkedFromMessageId=e.forkedFromMessageId,this.forkSynthesisState=e.forkSynthesisState,this.originatingClient=e.originatingClient,this.title=e.title,this.scheduleSynopsisHook=e.scheduleSynopsis,this.scheduleCompactionHook=e.scheduleCompaction,this.resolveAgentIdHook=e.resolveAgentId,this.getCompactionStateHook=e.getCompactionState,this.getPendingAgentSwapHook=e.getPendingAgentSwap,this.currentModel=e.currentModel,this.currentMode=e.currentMode,this._currentUsage=e.currentUsage,this.cumulativeCost=e.currentUsage?.cumulativeCost??0,e.agentCommands&&e.agentCommands.length>0&&(this.agentAdvertisedCommands=[...e.agentCommands]),e.agentModes&&e.agentModes.length>0&&(this.agentAdvertisedModes=[...e.agentModes]),e.agentModels&&e.agentModels.length>0&&(this.agentAdvertisedModels=[...e.agentModels]),this.idleTimeoutMs=e.idleTimeoutMs??0,this.idleEventTimeoutMs=e.idleEventTimeoutMs??3e4,this.idleEventTimeoutMs>0&&this.onIdle(t=>t.notifyChain("session.idle",{}),{debounceMs:this.idleEventTimeoutMs}),this.spawnReplacementAgent=e.spawnReplacementAgent,this.mintMcpServersForSwap=e.mintMcpServersForSwap,this.loadExistingAgentSession=e.loadExistingAgentSession,this.clearRollbackBreadcrumbHook=e.clearRollbackBreadcrumbHook,this.onCompactionSwapHook=e.onCompactionSwapHook,this.uncompactHook=e.uncompactHook,this.mcpServersConfig=e.mcpServers,this.forwardedEnv=e.forwardedEnv,this.availableAgentsFn=e.availableAgents,this.listSessions=e.listSessions,this.logger=e.logger,this.transformChain=e.transformChain??[],this.extensionCommands=e.extensionCommands,this.extensionCommands&&(this.extensionCommandsUnsub=this.extensionCommands.onChange(()=>{this.closed||this.broadcastMergedCommands()})),e.firstPromptSeeded&&(this._firstPromptSeeded=!0),this._interactive=e.interactive,this._priority=e.priority,this._summarizedThroughEntry=e.summarizedThroughEntry,this.compactionState=e.compactionState,e.compactionState){let t=e.compactionState;(t.status==="requested"||t.status==="running"||t.status==="swap_pending"||t.status==="swap_deferred")&&(t.status==="swap_deferred"?this._liveCompactionPhase={phase:"deferred",attempts:t.attempts}:this._liveCompactionPhase={phase:t.status==="requested"?"started":"iteration",iter:t.iter})}if(e.attentionFlags&&e.attentionFlags.length>0)for(let t of e.attentionFlags)this.attentionFlags.set(`${t.source}::${t.reason}`,t);this.historyStore=e.historyStore,this.historyMaxEntries=e.historyMaxEntries??nd,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){cd(this.internalPromptCapture,t);return}this.maybeEmitToolEdges(t),this.runResponseChain(t)}),e.connection.onRequest("session/request_permission",async t=>{let s=await this.runAgentRequestChain("session/request_permission",t),r=_r(s.shortCircuit?t:s.envelope);if(s.shortCircuit)return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:s.payload,sourceWasTransformer:!0}),s.payload;let o=await this.handlePermissionRequest(s.envelope);return this.notifyChain("permission.replied",{toolCallId:r??null,outcome:o,sourceWasTransformer:!1}),o}),typeof e.connection.onOrphanError=="function"&&e.connection.onOrphanError(t=>{this.handleOrphanError(t)}),e.onExit(()=>{this.agent===e&&this.markClosed({deleteRecord:!1})})}handleOrphanError(e){let t=Date.now()-this.lastCancelAt;if(this.lastCancelAt===0||t>n.CANCEL_ERROR_WINDOW_MS){this.logger?.warn(`agent ${this.agentId} sent uncorrelated error frame code=${e.code} message=${e.message}`);return}this.lastCancelAt=0,this.logger?.warn(`agent ${this.agentId} rejected session/cancel code=${e.code} message=${e.message}`),this.broadcastQueueNotification("hydra-acp/cancel_failed",{sessionId:this.sessionId,code:e.code,message:e.message})}async runResponseChain(e,t=new Set,s=0,r="session/update"){let o=e,i=r==="session/update"?this.injectCumulativeCost(e):e,a=`response:${r}`;for(let d=s;d<this.transformChain.length;d++){let f=this.transformChain[d];if(t.has(f.name)||!f.intercepts.has(a))continue;let p=`t_${zn()}`,c;try{c=await f.connection.request("hydra-acp/transformer/message",{token:p,phase:"response",method:r,direction:"agent\u2192client",sessionId:this.sessionId,envelope:i})}catch(m){this.logger?.warn(`transformer ${f.name} error on ${a}: ${m.message}`);continue}let g=c?.action??"continue";if(g==="stop")return;if(g==="processing"){let m=d,h=i,v=new Set(t),y=r;await new Promise(w=>{let b=setTimeout(()=>{this.pendingClaims.delete(p)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:p,transformerName:f.name}),this.runResponseChain(h,new Set([...v,f.name]),m+1,y).then(()=>w()).catch(()=>w()))},jt);typeof b.unref=="function"&&b.unref(),this.pendingClaims.set(p,{resolve:()=>w(),timer:b,transformerName:f.name,method:y,envelope:h,chainIdx:m,originatedBy:v,side:"response"})});return}c?.payload&&typeof c.payload=="object"&&(i=c.payload),t.add(f.name)}if(r!=="session/update")return;let u=ud(i);if(u!==null){this.setAgentAdvertisedCommands(u);return}let l=dd(i);if(l!==null){this.setAgentAdvertisedModes(l);return}if(this.maybeApplyAgentModel(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentMode(i)){this.recordAndBroadcast("session/update",i);return}if(this.maybeApplyAgentConfigOption(i)){this.recordAndBroadcast("session/update",this.mergeAgentOptionIntoEnvelope(i));return}if(this.maybeApplyAgentUsage(o)){this.recordAndBroadcast("session/update",i);return}this.maybeApplyAgentSessionInfo(i),this.recordAndBroadcast("session/update",i)}onAgentChange(e){this.agentChangeHandlers.push(e)}get attachedCount(){return this.clients.size}connectedClients(e){let t=[];for(let s of this.clients.values()){if(e&&s.clientId===e)continue;let r={clientId:s.clientId};s.clientInfo?.name&&(r.name=s.clientInfo.name),s.clientInfo?.version&&(r.version=s.clientInfo.version),t.push(r)}return t}get turnStartedAt(){return this.promptStartedAt}get awaitingInput(){return this.attentionFlags.size>0}async isQuiescedForSwap(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight||await this._hasOpenToolCall())}isQuiescedSync(){return!(this.promptInFlight||this.modeChangeInFlight||this.modelChangeInFlight)}async swapUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for swap \u2014 wait for in-flight work to complete");this.notifyChain("agent.swap",{phase:"pre",previousUpstreamSessionId:this.upstreamSessionId,agentId:this.agentId});let s=this.agentId,r=e.newAgentId??this.agentId,o=r!==this.agentId,i=this.cwd,a=this.agentArgs,u=this.forwardedEnv,l=this.currentModel,d=this.currentMode,f=this.spawnReplacementAgent;if(!f)throw new Error("agent spawning not configured for this session");let p=this.mintMcpServersForSwap?await this.mintMcpServersForSwap(this):this.mcpServersConfig??[],c=await f({agentId:r,cwd:i,agentArgs:a,...u?{forwardedEnv:u}:{},mcpServers:p});this.accumulateAndResetCost(),this.wireAgent(c.agent),o||(await Ue({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedModel:l,agentReportedModel:c.initialModel,logger:this.logger}),await Be({agent:c.agent,upstreamSessionId:c.upstreamSessionId,persistedMode:d,agentReportedMode:c.initialMode,logger:this.logger})),c.agent.connection.drainBuffered("session/update");let g=[];if(this.historyStore)try{g=await this.historyStore.load(this.sessionId)}catch(A){this.logger?.warn(`swapUpstream: historyStore.load failed: ${A.message}`)}let m=qn({synopsis:e.artifact,title:e.title,tail:g,tailK:e.tailK,tailFloor:e.tailFloor,...e.summarizedThroughEntry!==void 0?{watermark:e.summarizedThroughEntry}:{}});if(this.internalPromptCapture)throw new Error("swapUpstream: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await c.agent.connection.request("session/prompt",{sessionId:c.upstreamSessionId,prompt:[{type:"text",text:m}]});let A=this.internalPromptCapture;this.logger?.info(`swapUpstream: seed processed sessionId=${this.sessionId} seedChars=${m.length} toolCalls=${A.toolCalls} thinkingChars=${A.thinkingChars} messageChars=${A.messageChars} used=${A.lastUsed??"?"} size=${A.lastSize??"?"} reply=${JSON.stringify(A.chunks.join("").slice(0,200))}`)}finally{this.internalPromptCapture=void 0}let h=this.upstreamSessionId,v=this._summarizedThroughEntry;e.summarizedThroughEntry!==void 0&&(this._summarizedThroughEntry=e.summarizedThroughEntry);let y=this.agent;this.agent=c.agent,this.upstreamSessionId=c.upstreamSessionId,this.agentMeta=c.agentMeta,this.agentCapabilities=c.agentCapabilities,o&&(this.agentId=r,this.agentAdvertisedCommands=[],this.currentModel=c.initialModel,this.currentMode=c.initialMode,this.setAgentAdvertisedModels(c.initialModels??[]),this.setAgentAdvertisedModes(c.initialModes??[])),this.broadcastMergedCommands(),this.broadcastConfigOptions();for(let A of this.agentChangeHandlers)try{A({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(x){this.logger?.warn(`swapUpstream: agentChange handler failed: ${x.message}`)}if(!o&&this.onCompactionSwapHook)try{this.onCompactionSwapHook({previousUpstreamSessionId:h,...v!==void 0?{previousSummarizedThroughEntry:v}:{}})}catch(A){this.logger?.warn(`swapUpstream: onCompactionSwapHook failed: ${A.message}`)}await y.kill().catch(()=>{}),this.notifyChain("agent.swap",{phase:"post",previousUpstreamSessionId:h,upstreamSessionId:this.upstreamSessionId,agentId:this.agentId}),o||this.broadcastCompactionPhase({phase:"swapped",...this.title!==void 0?{title:this.title}:{},summarizedThroughEntry:e.summarizedThroughEntry??this._summarizedThroughEntry??0}),o&&this.broadcastAgentSwitch(s,r);let w=o?`
|
|
30
30
|
Switched to ${r}.
|
|
31
31
|
`:`
|
|
32
32
|
Compaction completed.
|
|
33
|
-
`,b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:w},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",b).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,c=this.currentModel,u=this.currentMode,d=await s(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(d.agent),await De({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:c,agentReportedModel:d.initialModel,logger:this.logger}),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:u,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let p of this.agentChangeHandlers)try{p({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(l){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${l.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Ya){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of s){let c=i.params?.update;if(!c||typeof c.sessionUpdate!="string")continue;let u=c.sessionUpdate,d=typeof c.toolCallId=="string"?c.toolCallId:void 0;if(d){if(u==="tool_call")r.add(d);else if(u==="tool_call_update"){let f=c.status;(f==="completed"||f==="failed")&&o.add(d)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw ne(new Error("session is closed"),I.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),I.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Ar(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Tr(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Wn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...s(o)],appliedPolicy:"full"}:{entries:[...i,...s(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),I.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),I.SessionClosing);let r=Ae();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(at((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let i of this.interactiveHandlers)try{i(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=We(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Ae()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>td;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),I.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let c=this.promptQueue.find(d=>d.messageId===r&&d.kind==="user");if(c&&c.kind==="user"&&!c.cancelled)return c.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let u=this.recentlyTerminal.get(r);return u?u.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let o=Ae(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let c=[];for(let u of this.promptQueue){if(u.kind==="user"&&!u.cancelled){u.cancelled=!0,this.broadcastQueueRemoved(u.messageId,"cancelled"),u.resolve({stopReason:"cancelled"});continue}c.push(u)}this.promptQueue=c}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let s=Ae(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw ne(new Error("client not attached"),I.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name))continue;let u=`request:${e}`;if(!c.intercepts.has(u))continue;let d=`t_${zn()}`,f;try{f=await c.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(l){this.logger?.warn(`transformer ${c.name} error on ${u}: ${l.message}`);continue}let p=f?.action??"continue";if(p==="stop")return o==="notification"?void 0:f?.payload??Jn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(i=f.payload),s.add(c.name);continue}if(p==="processing"){let l=a,m=i,g=new Set(s);return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:c.name}),this.forwardRequest(e,m,new Set([...g,c.name]),l+1,o).then(h).catch(()=>h(o==="notification"?void 0:Jn(e))))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(d,{resolve:h,timer:v,transformerName:c.name,method:e,envelope:m,chainIdx:l,originatedBy:g,side:"request",tailKind:o})})}s.add(c.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async runAgentRequestChain(e,t,s=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let c=this.transformChain[a];if(s.has(c.name)||!c.intercepts.has(i))continue;let u=`t_${zn()}`,d;try{d=await c.connection.request("hydra-acp/transformer/message",{token:u,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${c.name} error on ${i}: ${p.message}`);continue}let f=d?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:d?.payload??pd(e)};if(f==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(c.name);continue}if(f==="processing"){let p=a,l=o,m=new Set(s),g=e;return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(u)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:u,transformerName:c.name}),this.runAgentRequestChain(g,l,new Set([...m,c.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:l})))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(u,{resolve:y=>h({shortCircuit:!0,payload:y}),timer:v,transformerName:c.name,method:g,envelope:l,chainIdx:p,originatedBy:m,side:"agent-request"})})}s.add(c.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):jt,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let i=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,i).then(s.resolve).catch(()=>s.resolve(i==="notification"?void 0:Jn(s.method)))}},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(t,s,i,o)}async emitToQueue(e,t){let s=this.transformChain.findIndex(u=>u.name===e),r=s>=0?s+1:0,o=(t??{}).prompt??[],i=Ae(),a=`transformer:${e}`,c={clientId:a,name:e};return new Promise((u,d)=>{let f={kind:"user",messageId:i,originator:c,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:u,reject:d},p=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{position:p}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=We((e??{}).prompt),r=Qn(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=Qe(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=Qe(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let c=i.currentValue;if(typeof c=="string"){let u=c.trim();u&&u!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(u)}`),this.applyModelChange(u))}}else if(i.id==="mode"){let a=ut(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let c=i.currentValue;if(typeof c=="string"){let u=c.trim();u&&u!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(u)}`),this.applyModeChange(u))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),c=Qe(i.options);if(c.length>0){let u=ut(i.options),d=u.length>0?u.map(h=>({value:h.id,name:h.name??h.id})):c.map(h=>({value:h.modelId,name:h.name??h.modelId})),f=i.name,p=typeof f=="string"&&f.trim()?f.trim():a,l=i.currentValue,m=typeof l=="string"&&l.trim()?l.trim():d[0]?.value??"",g=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(g>=0){let h={...this.agentAdvertisedConfigOptions[g]};h.options=d,typeof l=="string"&&l.trim()&&(h.currentValue=l.trim()),this.agentAdvertisedConfigOptions[g]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:m,options:d})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let o={};typeof s.costAmount=="number"&&(o.amount=s.costAmount),typeof s.costCurrency=="string"&&(o.currency=s.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(sd(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(rd(this.agentAdvertisedModes,e)){this.broadcastAvailableModes();return}this.agentAdvertisedModes=e;for(let t of this.agentModesHandlers)try{t(e)}catch{}this.broadcastAvailableModes()}setAgentAdvertisedModels(e){if(this.logger?.info(`setAgentAdvertisedModels: sessionId=${this.sessionId} currentModel=${JSON.stringify(this.currentModel)} newList=[${e.map(t=>t.modelId).join(",")}]`),od(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of qe){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let c=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&c.length>0){let u=r.verb?`hydra ${c} ${r.verb}`:`hydra ${c}`,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}if(c.length>0&&t.get(c)===s){let u=r.verb?`${c} ${r.verb}`:c,f={name:r.argsHint?`${u} ${r.argsHint}`:u};r.description&&(f.description=r.description),e.push(f)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name);a&&e.add(a)}let s=new Map;for(let i of qe)e.has(i.verb)||s.set(i.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||s.has(a))continue;let c=r.get(a);c===void 0?r.set(a,i):c!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&s.set(i,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(qe.some(f=>f.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return a?this.runAgentCommandInline(i):this.runAgentCommand(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${o}`);throw f.code=I.InternalError,f}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let c=`hydra-acp-${o}`;if(this.extensionCommands?.has(c))return a?this.runExtensionCommandInline(c,i,t):this.runExtensionCommand(c,i);let u=qe.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:p}of this.extensionCommands.list())f.has(p)||(u.push(p),f.add(p))}let d=new Error(`unknown /hydra verb: ${o} (known: ${u.join(", ")})`);throw d.code=I.InvalidParams,d}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(m=>m.verb===i)){let m=r.commands.map(g=>g.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${m||"(none)"})`)}let c={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(c.messageId=s);let u=()=>{},d=new Promise(m=>{u=m});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:m=>u({stopReason:"cancelled",reason:m})});let f,p=!1;try{let m=r.connection.request("hydra-acp/commands/invoke",c),g=await Promise.race([m,d]);if(g&&typeof g=="object"&&g.stopReason==="cancelled"&&"reason"in g)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=g}catch(m){return this.emitExtensionReply(`${e} ${i}: ${m.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let l=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return l.length>0?this.emitExtensionReply(l):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
33
|
+
`,b=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:w},_meta:{"hydra-acp":{synthetic:!0}}}});for(let A of this.clients.values())A.connection.notify("session/update",b).catch(()=>{});this.updatedAt=Date.now()}async rollbackToUpstream(e){if(!await this.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");let s=this.loadExistingAgentSession;if(!s)throw new Error("loadExistingAgentSession not configured for this session");let r=this.agentId,o=this.cwd,i=this.agentArgs,a=this.forwardedEnv,u=this.currentModel,l=this.currentMode,d=await s(e.previousUpstreamSessionId,{agentId:r,cwd:o,agentArgs:i,...a?{forwardedEnv:a}:{},mcpServers:this.mcpServersConfig??[]});this.accumulateAndResetCost(),this.wireAgent(d.agent),await Ue({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedModel:u,agentReportedModel:d.initialModel,logger:this.logger}),await Be({agent:d.agent,upstreamSessionId:d.upstreamSessionId,persistedMode:l,agentReportedMode:d.initialMode,logger:this.logger}),d.agent.connection.drainBuffered("session/update");let f=this.agent;this.agent=d.agent,this.upstreamSessionId=d.upstreamSessionId,this.agentMeta=d.agentMeta,this.agentCapabilities=d.agentCapabilities,this.broadcastMergedCommands(),this.broadcastConfigOptions(),await f.kill().catch(()=>{}),this._summarizedThroughEntry=e.previousSummarizedThroughEntry,this.broadcastCompactionPhase({phase:"rolled_back",summarizedThroughEntry:e.previousSummarizedThroughEntry??0});for(let p of this.agentChangeHandlers)try{p({agentId:this.agentId,upstreamSessionId:this.upstreamSessionId})}catch(c){this.logger?.warn(`rollbackToUpstream: agentChange handler failed: ${c.message}`)}this.updatedAt=Date.now()}async _hasOpenToolCall(e=Za){if(!this.historyStore)return!1;let t=await this.historyStore.load(this.sessionId),s=t.length>e?t.slice(-e):t,r=new Set,o=new Set;for(let i of s){let u=i.params?.update;if(!u||typeof u.sessionUpdate!="string")continue;let l=u.sessionUpdate,d=typeof u.toolCallId=="string"?u.toolCallId:void 0;if(d){if(l==="tool_call")r.add(d);else if(l==="tool_call_update"){let f=u.status;(f==="completed"||f==="failed")&&o.add(d)}}}for(let i of r)if(!o.has(i))return!0;return!1}async getHistorySnapshot(e="inline"){return this.historyStore?this.historyStore.load(this.sessionId,{tools:e}).catch(()=>[]):[]}onBroadcast(e){return this.broadcastHandlers.push(e),()=>{let t=this.broadcastHandlers.indexOf(e);t>=0&&this.broadcastHandlers.splice(t,1)}}broadcastClientUpdate(e){let t=this.rewriteForClient({sessionId:this.upstreamSessionId,update:e});for(let s of this.clients.values())s.connection.notify("session/update",t).catch(()=>{})}broadcastCompactionPhase(e){let t=e.phase;t==="swapped"||t==="failed"||t==="rolled_back"?this._liveCompactionPhase=void 0:this._liveCompactionPhase=e;let s=this.rewriteForClient({sessionId:this.upstreamSessionId,update:{sessionUpdate:"hydra_compaction",...e}});for(let r of this.broadcastHandlers)try{r({method:"session/update",params:s,recordedAt:Date.now()})}catch{}for(let r of this.clients.values())r.connection.notify("session/update",s).catch(()=>{});this.notifyChain("compaction",{...e})}attach(e,t,s={}){if(this.closed)throw ne(new Error("session is closed"),S.SessionNotFound);if(this.clients.has(e.clientId))throw ne(new Error(`client ${e.clientId} is already attached`),S.AlreadyAttached);return this.clients.set(e.clientId,e),this.updatedAt=Date.now(),t==="none"?Promise.resolve({entries:[],appliedPolicy:t}):t==="pending_only"?Promise.resolve({entries:this.buildStateSnapshotReplay(),appliedPolicy:t}):this.loadReplay(t,s)}async loadReplay(e,t){let s=a=>t.raw?a:Ar(a),o=(await this.getHistorySnapshot(t.toolContent??"inline")).filter(a=>!Tr(a.method,a.params)),i=this.buildStateSnapshotReplay();if(e==="after_message"){let a=t.afterMessageId?Wn(o,t.afterMessageId):-1;return a<0?{entries:[...i,...s(o)],appliedPolicy:"full"}:{entries:[...i,...s(o.slice(a+1))],appliedPolicy:"after_message"}}return{entries:[...i,...s(o)],appliedPolicy:"full"}}buildStateSnapshotReplay(){let e=[],t=this.sessionId,s=Date.now();if(this.title!==void 0&&this.title.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"session_info_update",title:this.title}},recordedAt:s}),this.currentModel!==void 0&&this.currentModel.length>0||this.agentAdvertisedModels.length>0){let o={sessionUpdate:"current_model_update"};this.currentModel!==void 0&&this.currentModel.length>0&&(o.currentModel=this.currentModel),this.agentAdvertisedModels.length>0&&(o.availableModels=[...this.agentAdvertisedModels]),e.push({method:"session/update",params:{sessionId:t,update:o},recordedAt:s})}this.currentMode!==void 0&&this.currentMode.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"current_mode_update",currentModeId:this.currentMode}},recordedAt:s});let r=this.mergedAvailableCommands();if(r.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_commands_update",availableCommands:r}},recordedAt:s}),this.agentAdvertisedModes.length>0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"available_modes_update",availableModes:[...this.agentAdvertisedModes]}},recordedAt:s}),this.currentUsage!==void 0){let o=this.currentUsage,i={sessionUpdate:"usage_update"};if(typeof o.used=="number"&&(i.used=o.used),typeof o.size=="number"&&(i.size=o.size),typeof o.costAmount=="number"||typeof o.costCurrency=="string"){let a={};typeof o.costAmount=="number"&&(a.amount=o.costAmount),typeof o.costCurrency=="string"&&(a.currency=o.costCurrency),i.cost=a}Object.keys(i).length>1&&e.push({method:"session/update",params:{sessionId:t,update:i},recordedAt:s})}return this._liveCompactionPhase!==void 0&&e.push({method:"session/update",params:{sessionId:t,update:{sessionUpdate:"hydra_compaction",...this._liveCompactionPhase}},recordedAt:s}),e}replayPendingPermissions(e){for(let t of this.attentionFlags.values()){if(t.source!=="daemon"||!t.reason.startsWith("permission:"))continue;let s=t.reason.slice(11),r=this.permissionCallbacks.get(s);r&&r(e)}}detach(e){let t=this.clients.get(e);t&&(this.clients.delete(e),this.updatedAt=Date.now(),this.broadcastClientDisconnected(t))}broadcastClientDisconnected(e){let t={clientId:e.clientId};e.clientInfo?.name&&(t.name=e.clientInfo.name),e.clientInfo?.version&&(t.version=e.clientInfo.version);let s={sessionUpdate:"client_disconnected",client:t,timestamp:new Date().toISOString()};for(let r of this.clients.values())r.connection.notify("session/update",{sessionId:this.sessionId,update:s}).catch(()=>{})}async prompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),S.SessionNotFound);if(this.closing)throw ne(new Error("session is closing; new prompts cannot be accepted"),S.SessionClosing);let r=Ae();if(this.maybeSeedTitleFromPrompt(t),this._firstPromptSeeded=!0,!(at((t??{})._meta).ancillary===!0)&&this._interactive!==!0){this._interactive=!0;for(let i of this.interactiveHandlers)try{i(!0)}catch{}}return this.enqueueUserPrompt(s,t,r)}broadcastPromptReceived(e){let t={clientId:e.originator.clientId};e.originator.name&&(t.name=e.originator.name),e.originator.version&&(t.version=e.originator.version),this.promptStartedAt=Date.now(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"prompt_received",messageId:e.messageId,prompt:e.prompt,sentBy:t}},e.clientId);let s=Je(e.prompt);s.length>0&&this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"user_message_chunk",content:{type:"text",text:s},_meta:{"hydra-acp":{compatFor:"prompt_received"}}}},e.clientId)}recordCurrentUsageSnapshot(){if(this.historyStore===void 0)return;let e=this.currentUsage;if(e===void 0)return;let t={sessionUpdate:"usage_update"};if(typeof e.used=="number"&&(t.used=e.used),typeof e.size=="number"&&(t.size=e.size),typeof e.costAmount=="number"||typeof e.costCurrency=="string"){let r={};typeof e.costAmount=="number"&&(r.amount=e.costAmount),typeof e.costCurrency=="string"&&(r.currency=e.costCurrency),t.cost=r}if(Object.keys(t).length<=1)return;let s={sessionId:this.sessionId,update:t};this.historyStore.append(this.sessionId,{method:"session/update",params:s,recordedAt:Date.now()}).catch(()=>{})}broadcastTurnComplete(e,t,s,r){let o=t&&typeof t=="object"&&"stopReason"in t&&typeof t.stopReason=="string"?t.stopReason:void 0,i={sessionUpdate:"turn_complete",messageId:Ae()};o!==void 0&&(i.stopReason=o);let a=this.amendInProgress;a&&s!==void 0&&a.cancelledMessageId===s&&(i._meta={"hydra-acp":{amended:{cancelledMessageId:a.cancelledMessageId,newMessageId:a.newMessageId}}}),this.promptStartedAt=void 0,s!==void 0&&o!==void 0&&this.recordTerminal(s,o),this.recordCurrentUsageSnapshot(),this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:i},r?void 0:e),a&&s!==void 0&&a.cancelledMessageId===s&&this.broadcastPromptAmended(a)}recordTerminal(e,t){for(this.recentlyTerminal.set(e,{stopReason:t,terminatedAt:Date.now()});this.recentlyTerminal.size>sd;){let s=this.recentlyTerminal.keys().next().value;if(s===void 0)break;this.recentlyTerminal.delete(s)}}broadcastPromptAmended(e){let t=this.findUserEntry(e.newMessageId);if(!t)return;let s={sessionId:this.sessionId,cancelledMessageId:e.cancelledMessageId,newMessageId:e.newMessageId,prompt:t.prompt,originator:t.originator,amendedAt:Date.now()};this.broadcastQueueNotification("hydra-acp/prompt/amended",s)}findUserEntry(e){if(this.currentEntry?.messageId===e&&this.currentEntry.kind==="user")return this.currentEntry;let t=this.promptQueue.find(s=>s.messageId===e&&s.kind==="user");return t?.kind==="user"?t:void 0}visibleQueueDepth(){let e=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;for(let t of this.promptQueue)t.kind==="user"&&!t.cancelled&&(e+=1);return e}broadcastQueueAdded(e,t){let s=this.visibleQueueDepth(),r=t?.position??Math.max(0,s-1),o={sessionId:this.sessionId,messageId:e.messageId,originator:e.originator,prompt:e.prompt,position:r,queueDepth:s,enqueuedAt:e.enqueuedAt};t?.amending!==void 0&&(o._meta={"hydra-acp":{amending:t.amending}}),this.broadcastQueueNotification("hydra-acp/prompt_queue/added",o)}broadcastQueueUpdated(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/updated",{sessionId:this.sessionId,messageId:e,prompt:t})}broadcastQueueRemoved(e,t){this.broadcastQueueNotification("hydra-acp/prompt_queue/removed",{sessionId:this.sessionId,messageId:e,reason:t})}broadcastQueueNotification(e,t){for(let s of this.clients.values())s.connection.notify(e,t).catch(()=>{})}queueSnapshot(){let e=[],t=0;this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled&&e.push({messageId:this.currentEntry.messageId,originator:this.currentEntry.originator,prompt:this.currentEntry.prompt,position:t++,enqueuedAt:this.currentEntry.enqueuedAt});for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push({messageId:s.messageId,originator:s.originator,prompt:s.prompt,position:t++,enqueuedAt:s.enqueuedAt});return e}async flushPersistWrites(){await this.queueWriteChain.catch(()=>{})}replayPersistedQueue(e){for(let t of e){let s={clientId:`hydra-resurrected_${t.messageId}`};t.originator.clientInfo.name!==void 0&&(s.name=t.originator.clientInfo.name),t.originator.clientInfo.version!==void 0&&(s.version=t.originator.clientInfo.version);let r={kind:"user",messageId:t.messageId,originator:s,clientId:s.clientId,prompt:t.prompt,enqueuedAt:t.enqueuedAt,cancelled:!1,resolve:()=>{},reject:()=>{}};this.promptQueue.push(r),this.broadcastQueueAdded(r)}this.drainQueue()}cancelQueuedPrompt(e){if(this.currentEntry?.messageId===e)return{cancelled:!1,reason:"already_running"};let t=this.promptQueue.findIndex(r=>r.messageId===e);if(t<0)return{cancelled:!1,reason:"not_found"};let s=this.promptQueue[t];return s.cancelled=!0,this.promptQueue.splice(t,1),s.kind==="user"&&(this.broadcastQueueRemoved(e,"cancelled"),this.persistRewrite()),this.amendInProgress?.newMessageId===e&&(this.amendInProgress=void 0),s.resolve({stopReason:"cancelled"}),{cancelled:!0,reason:"ok"}}updateQueuedPrompt(e,t){if(this.currentEntry?.messageId===e)return{updated:!1,reason:"already_running"};let s=this.promptQueue.find(r=>r.messageId===e);return!s||s.kind!=="user"?{updated:!1,reason:"not_found"}:(s.prompt=t,this.broadcastQueueUpdated(e,t),this.persistRewrite(),{updated:!0,reason:"ok"})}amendPrompt(e,t){let s=this.clients.get(e);if(!s)throw ne(new Error("client not attached"),S.SessionNotFound);let{targetMessageId:r,prompt:o,replaceQueue:i,onTargetCompleted:a}=t;if(this.currentEntry?.messageId===r&&this.currentEntry.kind==="user"&&!this.currentEntry.cancelled&&this.amendInProgress===void 0)return this.amendOnHead(s,o,r,i);let u=this.promptQueue.find(d=>d.messageId===r&&d.kind==="user");if(u&&u.kind==="user"&&!u.cancelled)return u.prompt=o,this.broadcastQueueUpdated(r,o),this.persistRewrite(),{amended:!0,reason:"ok",messageId:r};let l=this.recentlyTerminal.get(r);return l?l.stopReason==="cancelled"?{amended:!1,reason:"target_cancelled"}:a==="send_anyway"?{amended:!1,reason:"target_completed",messageId:this.enqueueAmendmentAsFollowUp(s,o)}:{amended:!1,reason:"target_completed"}:{amended:!1,reason:"target_not_found"}}amendOnHead(e,t,s,r){let o=Ae(),i={clientId:e.clientId};if(e.clientInfo?.name&&(i.name=e.clientInfo.name),e.clientInfo?.version&&(i.version=e.clientInfo.version),r){let u=[];for(let l of this.promptQueue){if(l.kind==="user"&&!l.cancelled){l.cancelled=!0,this.broadcastQueueRemoved(l.messageId,"cancelled"),l.resolve({stopReason:"cancelled"});continue}u.push(l)}this.promptQueue=u}let a={kind:"user",messageId:o,originator:i,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,wasAmend:!0,resolve:()=>{},reject:()=>{}};return this.promptQueue.unshift(a),this.persistRewrite(),this.broadcastQueueAdded(a,{amending:s,position:1}),this.amendInProgress={cancelledMessageId:s,newMessageId:o},this.cancelExtensionDispatch(s,"amended"),this.agent.connection.notify("session/cancel",{sessionId:this.upstreamSessionId}).catch(()=>{}),{amended:!0,reason:"ok",messageId:o}}enqueueAmendmentAsFollowUp(e,t){let s=Ae(),r={clientId:e.clientId};e.clientInfo?.name&&(r.name=e.clientInfo.name),e.clientInfo?.version&&(r.version=e.clientInfo.version);let o={kind:"user",messageId:s,originator:r,clientId:e.clientId,prompt:t,enqueuedAt:Date.now(),cancelled:!1,resolve:()=>{},reject:()=>{}};return this.promptQueue.push(o),this.persistRewrite(),this.broadcastQueueAdded(o),this.drainQueue(),s}async cancel(e){if(!this.clients.get(e))throw ne(new Error("client not attached"),S.SessionNotFound);this.lastCancelAt=Date.now(),this.currentEntry?.kind==="user"&&this.currentEntry.messageId!==void 0&&this.cancelExtensionDispatch(this.currentEntry.messageId,"cancelled"),await this.forwardRequest("session/cancel",{sessionId:this.sessionId},new Set,0,"notification")}addTransformer(e){let t=this.transformChain.findIndex(s=>s.name===e.name);t>=0?this.transformChain[t]=e:this.transformChain.push(e),e.intercepts.has("lifecycle:session.opened")&&e.connection.notify("hydra-acp/transformer/session_event",{event:"session.opened",sessionId:this.sessionId}).catch(()=>{})}async forwardRequest(e,t,s=new Set,r=0,o="request"){let i=this.rewriteForAgent(t);for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name))continue;let l=`request:${e}`;if(!u.intercepts.has(l))continue;let d=`t_${zn()}`,f;try{f=await u.connection.request("hydra-acp/transformer/message",{token:d,phase:"request",method:e,direction:"client\u2192agent",sessionId:this.sessionId,envelope:i})}catch(c){this.logger?.warn(`transformer ${u.name} error on ${l}: ${c.message}`);continue}let p=f?.action??"continue";if(p==="stop")return o==="notification"?void 0:f?.payload??Jn(e);if(p==="continue"){f?.payload&&typeof f.payload=="object"&&(i=f.payload),s.add(u.name);continue}if(p==="processing"){let c=a,g=i,m=new Set(s);return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(d)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:d,transformerName:u.name}),this.forwardRequest(e,g,new Set([...m,u.name]),c+1,o).then(h).catch(()=>h(o==="notification"?void 0:Jn(e))))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(d,{resolve:h,timer:v,transformerName:u.name,method:e,envelope:g,chainIdx:c,originatedBy:m,side:"request",tailKind:o})})}s.add(u.name)}if(o==="notification"){await this.agent.connection.notify(e,i);return}return this.agent.connection.request(e,i)}async runAgentRequestChain(e,t,s=new Set,r=0){let o=t,i=`request:${e}`;for(let a=r;a<this.transformChain.length;a++){let u=this.transformChain[a];if(s.has(u.name)||!u.intercepts.has(i))continue;let l=`t_${zn()}`,d;try{d=await u.connection.request("hydra-acp/transformer/message",{token:l,phase:"request",method:e,direction:"agent\u2192client",sessionId:this.sessionId,envelope:o})}catch(p){this.logger?.warn(`transformer ${u.name} error on ${i}: ${p.message}`);continue}let f=d?.action??"continue";if(f==="stop")return{shortCircuit:!0,payload:d?.payload??md(e)};if(f==="continue"){d?.payload&&typeof d.payload=="object"&&(o=d.payload),s.add(u.name);continue}if(f==="processing"){let p=a,c=o,g=new Set(s),m=e;return new Promise(h=>{let v=setTimeout(()=>{this.pendingClaims.delete(l)&&(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:l,transformerName:u.name}),this.runAgentRequestChain(m,c,new Set([...g,u.name]),p+1).then(h).catch(()=>h({shortCircuit:!1,envelope:c})))},jt);typeof v.unref=="function"&&v.unref(),this.pendingClaims.set(l,{resolve:y=>h({shortCircuit:!0,payload:y}),timer:v,transformerName:u.name,method:m,envelope:c,chainIdx:p,originatedBy:g,side:"agent-request"})})}s.add(u.name)}return{shortCircuit:!1,envelope:o}}dischargeClaim(e,t){let s=this.pendingClaims.get(e);return s?(clearTimeout(s.timer),this.pendingClaims.delete(e),s.resolve(t),!0):!1}keepAliveClaim(e,t){let s=this.pendingClaims.get(e);if(!s)return!1;clearTimeout(s.timer);let r=typeof t=="number"&&t>0?Math.min(t*1.5,1800*1e3):jt,o=setTimeout(()=>{if(this.pendingClaims.delete(e))if(this.broadcastQueueNotification("hydra-acp/transformer/abandoned_request",{sessionId:this.sessionId,token:e,transformerName:s.transformerName}),s.side==="response")this.runResponseChain(s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(()=>s.resolve(void 0)).catch(()=>s.resolve(void 0));else if(s.side==="agent-request")this.runAgentRequestChain(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1).then(s.resolve).catch(()=>s.resolve({shortCircuit:!1,envelope:s.envelope}));else{let i=s.tailKind??"request";this.forwardRequest(s.method,s.envelope,new Set([...s.originatedBy,s.transformerName]),s.chainIdx+1,i).then(s.resolve).catch(()=>s.resolve(i==="notification"?void 0:Jn(s.method)))}},r);return typeof o.unref=="function"&&o.unref(),s.timer=o,!0}async emitToChain(e,t,s){let r=this.transformChain.findIndex(a=>a.name===e),o=r>=0?r+1:0,i=new Set([e]);if(t==="session/update"){await this.runResponseChain(s,i,o);return}return this.forwardRequest(t,s,i,o)}async emitToQueue(e,t){let s=this.transformChain.findIndex(l=>l.name===e),r=s>=0?s+1:0,o=(t??{}).prompt??[],i=Ae(),a=`transformer:${e}`,u={clientId:a,name:e};return new Promise((l,d)=>{let f={kind:"user",messageId:i,originator:u,clientId:a,prompt:o,enqueuedAt:Date.now(),cancelled:!1,emitterName:e,chainStartIdx:r,resolve:l,reject:d},p=this.insertEntryAt(f,"tail");this.persistRewrite(),this.broadcastQueueAdded(f,{position:p}),this.drainQueue()})}rewriteForAgent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.sessionId===this.sessionId)return{...t,sessionId:this.upstreamSessionId}}return e}async close(e={}){if(e.deleteRecord&&(this.deleteRecordIntent=!0),!this.closed)return this.closeInFlight?this.closeInFlight:(this.closing=!0,this.closeInFlight=this.doClose(e),this.closeInFlight)}async doClose(e){this.logger?.info(`session ${this.sessionId} closing deleteRecord=${e.deleteRecord??!1}`),this.cancelIdleTimer();for(let t of this.pendingClaims.values())clearTimeout(t.timer);this.pendingClaims.clear(),await this.agent.kill().catch(()=>{}),this.markClosed({deleteRecord:e.deleteRecord??!1})}onClose(e){return this.closeHandlers.push(e),()=>{let t=this.closeHandlers.indexOf(e);t>=0&&this.closeHandlers.splice(t,1)}}onTitleChange(e){this.titleHandlers.push(e)}retitle(e){return this.runTitleCommand(e)}retitleFromAgent(){return this.runTitleCommand("")}setTitle(e){let t=e.trim();if(!(!t||t===this.title)){this.title=t,this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",title:t,updatedAt:new Date().toISOString()}});for(let s of this.titleHandlers)try{s(t)}catch{}}}maybeSeedTitleFromPrompt(e){if(this.firstPromptSeeded)return;let s=Je((e??{}).prompt),r=Qn(s,200);r&&(r.startsWith("/")||(this._firstPromptSeeded=!0,this.setTitle(r)))}maybeApplyAgentModel(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_model_update")return!1;let r=We(s.availableModels);r.length>0&&this.setAgentAdvertisedModels(r);let o=typeof s.currentModel=="string"?s.currentModel:typeof s.model=="string"?s.model:void 0;if(o===void 0)return!0;let i=o.trim();if(!i||i===this.currentModel)return!0;this.logger?.info(`live current_model_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(i)}`),this.currentModel=i;for(let a of this.modelHandlers)try{a(i)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentConfigOption(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="config_option_update")return!1;let r=s.configOptions;if(!Array.isArray(r))return!0;for(let o of r){if(!o||typeof o!="object")continue;let i=o;if(i.id==="model"){let a=We(i.options);a.length>0&&this.setAgentAdvertisedModels(a);let u=i.currentValue;if(typeof u=="string"){let l=u.trim();l&&l!==this.currentModel&&(this.logger?.info(`live config_option_update(model): sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(l)}`),this.applyModelChange(l))}}else if(i.id==="mode"){let a=ut(i.options);a.length>0&&this.setAgentAdvertisedModes(a);let u=i.currentValue;if(typeof u=="string"){let l=u.trim();l&&l!==this.currentMode&&(this.logger?.info(`live config_option_update(mode): sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(l)}`),this.applyModeChange(l))}}else if(typeof i.id=="string"&&i.id.trim()){let a=i.id.trim(),u=We(i.options);if(u.length>0){let l=ut(i.options),d=l.length>0?l.map(h=>({value:h.id,name:h.name??h.id})):u.map(h=>({value:h.modelId,name:h.name??h.modelId})),f=i.name,p=typeof f=="string"&&f.trim()?f.trim():a,c=i.currentValue,g=typeof c=="string"&&c.trim()?c.trim():d[0]?.value??"",m=this.agentAdvertisedConfigOptions.findIndex(h=>h.id===a);if(m>=0){let h={...this.agentAdvertisedConfigOptions[m]};h.options=d,typeof c=="string"&&c.trim()&&(h.currentValue=c.trim()),this.agentAdvertisedConfigOptions[m]=h}else this.agentAdvertisedConfigOptions.push({id:a,name:p,category:"other",type:"select",currentValue:g,options:d})}}}return!0}maybeApplyAgentMode(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="current_mode_update")return!1;let r=typeof s.currentModeId=="string"?s.currentModeId:typeof s.currentMode=="string"?s.currentMode:typeof s.mode=="string"?s.mode:void 0;if(r===void 0)return!0;let o=r.trim();if(!o||o===this.currentMode)return!0;this.logger?.info(`current_mode_update: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(o)}`),this.currentMode=o;for(let i of this.modeHandlers)try{i(o)}catch{}return this.broadcastConfigOptions(),!0}maybeApplyAgentUsage(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="usage_update")return!1;let r={...this._currentUsage??{}},o=!1;if(typeof s.used=="number"&&r.used!==s.used&&(r.used=s.used,o=!0),typeof s.size=="number"&&r.size!==s.size&&(r.size=s.size,o=!0),s.cost&&typeof s.cost=="object"){let a=s.cost;typeof a.amount=="number"&&r.costAmount!==a.amount&&(r.costAmount=a.amount,o=!0),typeof a.currency=="string"&&r.costCurrency!==a.currency&&(r.costCurrency=a.currency,o=!0)}if(!o)return!0;this._currentUsage=r;let i=this.currentUsage??r;for(let a of this.usageHandlers)try{a(i)}catch{}return!0}accumulateAndResetCost(){let e=this._currentUsage?.costAmount;e&&(this.cumulativeCost+=e);let t={used:0,cumulativeCost:this.cumulativeCost,...typeof this._currentUsage?.size=="number"?{size:this._currentUsage.size}:{},...this._currentUsage?.costCurrency?{costCurrency:this._currentUsage.costCurrency}:{}};this._currentUsage=t;for(let r of this.usageHandlers)try{r(t)}catch{}let s=this.currentUsage;if(s!==void 0){let r={sessionUpdate:"usage_update"};if(typeof s.used=="number"&&(r.used=s.used),typeof s.size=="number"&&(r.size=s.size),typeof s.costAmount=="number"||typeof s.costCurrency=="string"){let o={};typeof s.costAmount=="number"&&(o.amount=s.costAmount),typeof s.costCurrency=="string"&&(o.currency=s.costCurrency),r.cost=o}this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:r})}}injectCumulativeCost(e){if(!this.cumulativeCost||!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update;if(s.sessionUpdate!=="usage_update"||!s.cost||typeof s.cost!="object")return e;let r=s.cost;return typeof r.amount!="number"?e:{...t,update:{...s,cost:{...r,amount:this.cumulativeCost+r.amount}}}}get totalUsage(){return this.currentUsage}setAgentAdvertisedCommands(e){if(od(this.agentAdvertisedCommands,e)){this.broadcastMergedCommands();return}this.agentAdvertisedCommands=e;for(let t of this.agentCommandsHandlers)try{t(e)}catch{}this.broadcastMergedCommands()}setAgentAdvertisedModes(e){if(id(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(",")}]`),ad(this.agentAdvertisedModels,e)){this.broadcastAvailableModels();return}this.agentAdvertisedModels=e;for(let t of this.agentModelsHandlers)try{t(e)}catch{}this.broadcastAvailableModels()}onAgentCommandsChange(e){this.agentCommandsHandlers.push(e)}onAgentModesChange(e){this.agentModesHandlers.push(e)}onAgentModelsChange(e){this.agentModelsHandlers.push(e)}onModelChange(e){this.modelHandlers.push(e)}onModeChange(e){this.modeHandlers.push(e)}onInteractiveChange(e){this.interactiveHandlers.push(e)}onPriorityChange(e){this.priorityHandlers.push(e)}setPriority(e){let t=e===void 0||e<=0?void 0:Math.floor(e);if(t!==this._priority){this._priority=t,this.updatedAt=Date.now();for(let s of this.priorityHandlers)try{s(t)}catch{}}}applyModelChange(e){let t=e.trim();if(t){this.modelChangeInFlight=!0;try{if(t!==this.currentModel){this.logger?.info(`applyModelChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentModel)} \u2192 ${JSON.stringify(t)}`),this.currentModel=t;for(let r of this.modelHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_model_update",currentModel:t};this.agentAdvertisedModels.length>0&&(s.availableModels=[...this.agentAdvertisedModels]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modelChangeInFlight=!1}}}applyModeChange(e){let t=e.trim();if(t){this.modeChangeInFlight=!0;try{if(t!==this.currentMode){this.logger?.info(`applyModeChange: sessionId=${this.sessionId} ${JSON.stringify(this.currentMode)} \u2192 ${JSON.stringify(t)}`),this.currentMode=t;for(let r of this.modeHandlers)try{r(t)}catch{}}let s={sessionUpdate:"current_mode_update",currentModeId:t};this.agentAdvertisedModes.length>0&&(s.availableModes=[...this.agentAdvertisedModes]),this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:s}),this.broadcastConfigOptions()}finally{this.modeChangeInFlight=!1}}}buildConfigOptions(){let e=[];if(this.agentAdvertisedModels.length>0){let r=this.agentAdvertisedModels.map(i=>({value:i.modelId,name:i.name??i.modelId,...i.description!==void 0?{description:i.description}:{}})),o=this.currentModel&&r.some(i=>i.value===this.currentModel)?this.currentModel:r[0].value;e.push({id:"model",name:"Model",category:"model",type:"select",currentValue:o,options:r})}if(this.agentAdvertisedModes.length>0){let r=this.agentAdvertisedModes.map(i=>({value:i.id,name:i.name??i.id,...i.description!==void 0?{description:i.description}:{}})),o=this.currentMode&&r.some(i=>i.value===this.currentMode)?this.currentMode:r[0].value;e.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:o,options:r})}let s=(this.availableAgentsFn?.()??[]).map(r=>({value:r.id,name:r.name??r.id,...r.description!==void 0?{description:r.description}:{}}));return s.some(r=>r.value===this.agentId)||s.unshift({value:this.agentId,name:this.agentId}),e.push({id:"agent",name:"Agent",category:"_hydra_agent",type:"select",currentValue:this.agentId,options:s}),e.push(...this.agentAdvertisedConfigOptions),e}broadcastConfigOptions(){this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"config_option_update",configOptions:this.buildConfigOptions()}})}mergeAgentOptionIntoEnvelope(e){if(!e||typeof e!="object")return e;let t=e;if(!t.update||typeof t.update!="object")return e;let s=t.update,r=Array.isArray(s.configOptions)?[...s.configOptions]:[];if(r.some(a=>a&&typeof a=="object"&&a.id==="agent"))return e;let i=this.buildConfigOptions().find(a=>a.id==="agent");return i?{...t,update:{...s,configOptions:[...r,i]}}:e}onUsageChange(e){this.usageHandlers.push(e)}mergedAvailableCommands(){let e=this.daemonTopLevelCommands(),t=this.aliasableBareVerbs();for(let s of Le){if(t.get(s.verb)!=="__hydra__")continue;let r=s.argsHint?`${s.verb} ${s.argsHint}`:s.verb;e.push({name:r,description:`Alias for '/hydra ${s.verb}': ${s.description}`})}if(this.extensionCommands)for(let{name:s,command:r}of this.extensionCommands.list()){let o=r.verb?`hydra ${s} ${r.verb}`:`hydra ${s}`,a={name:r.argsHint?`${o} ${r.argsHint}`:o};r.description&&(a.description=r.description),e.push(a);let u=s.startsWith("hydra-acp-")?s.slice(10):s;if(s.startsWith("hydra-acp-")&&u.length>0){let l=r.verb?`hydra ${u} ${r.verb}`:`hydra ${u}`,f={name:r.argsHint?`${l} ${r.argsHint}`:l};r.description&&(f.description=r.description),e.push(f)}if(u.length>0&&t.get(u)===s){let l=r.verb?`${u} ${r.verb}`:u,f={name:r.argsHint?`${l} ${r.argsHint}`:l};r.description&&(f.description=r.description),e.push(f)}}return e.push(...this.agentAdvertisedCommands),e}daemonTopLevelCommands(){return[{name:"hydra",description:"Hydra session command (kill, restart, title, agent <agent>)"},{name:"model",description:"Switch model; omit arg to list available models"},{name:"mode",description:"Switch mode; omit arg to list available modes"},{name:"sessions",description:"List all sessions"},{name:"help",description:"Show available commands"}]}aliasableBareVerbs(){let e=new Set,t=i=>i.split(/\s+/)[0]??"";for(let i of this.daemonTopLevelCommands()){let a=t(i.name);a&&e.add(a)}for(let i of this.agentAdvertisedCommands){let a=t(i.name);a&&e.add(a)}let s=new Map;for(let i of Le)e.has(i.verb)||s.set(i.verb,"__hydra__");if(!this.extensionCommands)return s;let r=new Map,o=new Set;for(let{name:i}of this.extensionCommands.list()){if(o.has(i))continue;o.add(i);let a=i.startsWith("hydra-acp-")?i.slice(10):i;if(!a||e.has(a)||s.has(a))continue;let u=r.get(a);u===void 0?r.set(a,i):u!==i&&r.set(a,"__conflict__")}for(let[i,a]of r)a!=="__conflict__"&&s.set(i,a);return s}agentOnlyAdvertisedCommands(){return[...this.agentAdvertisedCommands]}availableModes(){return[...this.agentAdvertisedModes]}availableModels(){return[...this.agentAdvertisedModels]}maybeApplyAgentSessionInfo(e){let s=(e??{}).update??{};if(s.sessionUpdate!=="session_info_update"||typeof s.title!="string")return;let r=s.title.trim();if(!(!r||r===this.title)){this.title=r,this._firstPromptSeeded=!0;for(let o of this.titleHandlers)try{o(r)}catch{}}}async handleSlashCommand(e,t){let r=e.slice(6).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),o=r?.[1]??"",i=(r?.[2]??"").trim();if(o==="")return{stopReason:"end_turn"};let a=t!==void 0;if(Le.some(f=>f.verb===o))switch(o){case"title":return a?this.runTitleCommandInline(i):this.runTitleCommand(i);case"agent":return a?this.runAgentCommandInline(i):this.runAgentCommand(i);case"config":return this.handleConfigCommand(`/config ${i}`);case"kill":return this.runKillCommand();case"restart":return a?this.runRestartCommandInline():this.runRestartCommand();case"compact":return a?this.runCompactCommandInline(i):this.runCompactCommand(i);case"uncompact":return a?this.runUncompactCommandInline():this.runUncompactCommand();default:{let f=new Error(`no dispatcher for /hydra verb ${o}`);throw f.code=S.InternalError,f}}if(this.extensionCommands?.has(o))return a?this.runExtensionCommandInline(o,i,t):this.runExtensionCommand(o,i);let u=`hydra-acp-${o}`;if(this.extensionCommands?.has(u))return a?this.runExtensionCommandInline(u,i,t):this.runExtensionCommand(u,i);let l=Le.map(f=>f.verb);if(this.extensionCommands){let f=new Set;for(let{name:p}of this.extensionCommands.list())f.has(p)||(l.push(p),f.add(p))}let d=new Error(`unknown /hydra verb: ${o} (known: ${l.join(", ")})`);throw d.code=S.InvalidParams,d}runExtensionCommand(e,t){return this.enqueuePrompt(()=>this.runExtensionCommandInline(e,t,void 0))}async runExtensionCommandInline(e,t,s){let r=this.extensionCommands?.get(e);if(!r)return this.emitExtensionReply(`extension "${e}" is no longer connected`);let o=t.match(/^(\S+)(?:\s+([\s\S]*))?$/),i=o?.[1]??"",a=(o?.[2]??"").trim();if(!r.commands.some(g=>g.verb===i)){let g=r.commands.map(m=>m.verb).join(", ");return this.emitExtensionReply(`/hydra ${e}${i?` ${i}`:""}: unknown verb (known: ${g||"(none)"})`)}let u={sessionId:this.sessionId,verb:i,args:a};s!==void 0&&(u.messageId=s);let l=()=>{},d=new Promise(g=>{l=g});s!==void 0&&this.inFlightExtensionDispatches.set(s,{extensionName:e,connection:r.connection,cancel:g=>l({stopReason:"cancelled",reason:g})});let f,p=!1;try{let g=r.connection.request("hydra-acp/commands/invoke",u),m=await Promise.race([g,d]);if(m&&typeof m=="object"&&m.stopReason==="cancelled"&&"reason"in m)return p=!0,this.logger?.info(`extension ${e} ${i} cancelled (cancelExtensionDispatch); abandoning in-flight commands/invoke`),{stopReason:"cancelled"};f=m}catch(g){return this.emitExtensionReply(`${e} ${i}: ${g.message}`)}finally{s!==void 0&&!p&&this.inFlightExtensionDispatches.delete(s)}let c=f&&typeof f=="object"&&typeof f.text=="string"?f.text:"";return c.length>0?this.emitExtensionReply(c):{stopReason:"end_turn"}}cancelExtensionDispatch(e,t){let s=this.inFlightExtensionDispatches.get(e);if(!s)return!1;this.inFlightExtensionDispatches.delete(e);try{s.connection.notify("hydra-acp/commands/cancel",{sessionId:this.sessionId,messageId:e,reason:t})}catch(r){this.logger?.warn(`notify commands/cancel to ${s.extensionName} failed: ${r.message}`)}return s.cancel(t),!0}emitExtensionReply(e){return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
34
34
|
${e}
|
|
35
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",
|
|
35
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}async handleSessionsCommand(){let e;if(!this.listSessions)e="_(session listing not available)_";else{let t=await this.listSessions();if(t.length===0)e="_(no sessions)_";else{let s=t.map(r=>{let o=r.sessionId.replace(/^hydra_session_/,"").slice(0,12),i=r.currentModel?` \xB7 ${r.currentModel}`:"",a=r.sessionId===this.sessionId?" \u25C0":"",u=r.title?` ${r.title}`:"";return`\`${o}\` ${r.cwd}${i}${a}${u}`});e=`Sessions (${t.length}):
|
|
36
36
|
${s.join(`
|
|
37
37
|
`)}`}}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
38
38
|
${e}
|
|
@@ -40,18 +40,18 @@ ${e}
|
|
|
40
40
|
${t.join(`
|
|
41
41
|
`)}`:"_(no commands advertised)_";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
42
42
|
${s}
|
|
43
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let
|
|
43
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),Promise.resolve({stopReason:"end_turn"})}async handleModelCommand(e){let t=e.slice(6).trim();if(t===""){let o=this.agentAdvertisedModels,i=this.currentModel,a;if(o.length===0)a=i?`Current model: ${i}`:"_(no models advertised yet)_";else{let u=i?o.some(d=>d.modelId===i):!0,l=o.map(d=>{let f=d.modelId===i?"\u25B6 ":" ",p=d.name&&d.name!==d.modelId?` ${d.name}`:"";return`${f}${d.modelId}${p}`});!u&&i&&l.unshift(`\u25B6 ${i}`),a=l.join(`
|
|
44
44
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
45
45
|
${a}
|
|
46
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=
|
|
47
|
-
${
|
|
46
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=qe(t,this.agentAdvertisedModels),r=t;if(s.kind==="resolved")r=s.modelId;else if(s.kind==="ambiguous"||s.kind==="unknown"){let o=this.agentAdvertisedModels.map(f=>f.modelId),i=t.toLowerCase(),a=s.kind==="ambiguous"?s.candidates:o.filter(f=>f.toLowerCase().includes(i)),u=a.length>0?a:o,l=s.kind==="ambiguous"?`"${t}" matches multiple models: ${s.candidates.join(", ")}`:a.length>0?`"${t}" is not an available model. Did you mean`:`"${t}" is not an available model`,d=s.kind==="ambiguous"||a.length===0?"Available models":"Matching models";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
47
|
+
${l}.
|
|
48
48
|
${d}:
|
|
49
|
-
${
|
|
49
|
+
${u.join(`
|
|
50
50
|
`)}
|
|
51
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(
|
|
51
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:r}),this.applyModelChange(r),{stopReason:"end_turn"}}async handleModeCommand(e){let t=e.slice(5).trim();if(t===""){let r=this.agentAdvertisedModes,o=this.currentMode,i;if(r.length===0)i=o?`Current mode: ${o}`:"_(no modes advertised yet)_";else{let a=o?r.some(l=>l.id===o):!0,u=r.map(l=>{let d=l.id===o?"\u25B6 ":" ",f=l.name&&l.name!==l.id?` ${l.name}`:"";return`${d}${l.id}${f}`});!a&&o&&u.unshift(`\u25B6 ${o}`),i=u.join(`
|
|
52
52
|
`)}return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
53
53
|
${i}
|
|
54
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(o=>o.id).join(", ");throw ne(new Error(`unknown mode: ${t} (known: ${r})`),
|
|
54
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}let s=this.agentAdvertisedModes;if(s.length>0&&!s.some(r=>r.id===t)){let r=s.map(o=>o.id).join(", ");throw ne(new Error(`unknown mode: ${t} (known: ${r})`),S.InvalidParams)}return await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:t}),this.applyModeChange(t),{stopReason:"end_turn"}}async handleConfigCommand(e){let t=e.slice(7).trim().match(/^(\S+)(?:\s+([\s\S]*))?$/),s=t?.[1],r=t?.[2]??"";if(!s){let d=this.buildConfigOptions();if(d.length===0)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
55
55
|
_(no config options advertised yet)_
|
|
56
56
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let f=d.map(p=>$r(p));return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
57
57
|
${f.join(`
|
|
@@ -64,17 +64,17 @@ Available options:
|
|
|
64
64
|
${d}
|
|
65
65
|
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}if(!r)return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
66
66
|
${$r(i)}
|
|
67
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(d=>d.value),
|
|
68
|
-
${
|
|
69
|
-
${
|
|
67
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"};let a=i.options.map(d=>d.value),u=jn(r,a),l=r;if(u.kind==="resolved")l=u.modelId;else if(u.kind==="ambiguous"||u.kind==="unknown"){let d=r.toLowerCase(),f=u.kind==="ambiguous"?u.candidates:a.filter(m=>m.toLowerCase().includes(d)),p=f.length>0?f:a,c=u.kind==="ambiguous"?`"${r}" matches multiple values for "${s}": ${u.candidates.join(", ")}`:f.length>0?`"${r}" is not a valid value for "${s}". Did you mean`:`"${r}" is not a valid value for "${s}"`,g=u.kind==="ambiguous"||f.length===0?"Valid values":"Matching values";return this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
|
|
68
|
+
${c}.
|
|
69
|
+
${g}:
|
|
70
70
|
${p.join(`
|
|
71
71
|
`)}
|
|
72
|
-
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(
|
|
73
|
-
`)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ne(new Error("session is closing"),
|
|
74
|
-
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=qn({synopsis:e,title:t,tail:s,tailK:Xa,tailFloor:Za,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Nt(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??Le,Le)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let c=await r.waitForData(i.nextCursor,s);(c==="data"||c==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=I.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let o of s){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Pr(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>jr.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(s))return;this.attentionFlags.set(o,{...i,payload:s,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!o)return;let i=typeof s.kind=="string"?s.kind:void 0;i&&!this.toolCallKind.has(o)&&this.toolCallKind.set(o,i);let a=i??this.toolCallKind.get(o);if(a==="edit"&&Array.isArray(s.locations))for(let d of s.locations){if(!d||typeof d!="object")continue;let f=d.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=d.line,l={path:f,toolCallId:o};typeof p=="number"&&(l.line=p),this.notifyChain("file.edited",l)}if(r!=="tool_call_update")return;let c=typeof s.status=="string"?s.status:void 0;if(c!=="completed"&&c!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,c);let u={toolCallId:o,status:c};a&&(u.kind=a),s.content!==void 0&&(u.content=s.content),Array.isArray(s.locations)&&(u.locations=s.locations),this.notifyChain("tool.completed",u)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),o=!Tr(e,r),i=o?cd(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let c=this.historyStore;c.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,c.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let c of this.broadcastHandlers)try{c(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ne(new Error("no clients attached to handle permission request"),I.PermissionDenied);let s=this.rewriteForClient(e),r=_r(s),o=Ae(),{toolCall:i,options:a}=s??{};return new Promise((c,u)=>{let d=!1,f=[],p=0,l,m=this.sessionId,g=y=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},h=y=>y?.code===I.MethodNotFound;function v(y){if(d)return;let w=y.connection.request("session/request_permission",s);f.push({client:y}),p++,w.then(b=>{p--,g(()=>{let A=ud({toolCallId:r,result:b,resolver:y});for(let x of f)x.client.clientId!==y.clientId&&x.client.connection.notify("session/update",{sessionId:m,update:A}).catch(()=>{});c(b)})}).catch(b=>{if(p--,h(b)||(l=b),p===0&&!d){let A=l??ne(new Error("no client handled permission request"),I.PermissionDenied);g(()=>u(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,v);for(let y of t)v(y)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ae(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],o={clientId:e.clientId};e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version);let i=this.parseQueuePosition(t);return new Promise((a,c)=>{let u={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:c},d=this.insertEntryAt(u,i);this.persistRewrite(),this.broadcastQueueAdded(u,{position:d}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),s+o+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ct(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=We(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
75
|
-
`)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||o){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(o){let
|
|
72
|
+
`},_meta:{"hydra-acp":{synthetic:!0}}}}),{stopReason:"end_turn"}}return s==="model"?(l!==this.currentModel&&await this.forwardRequest("session/set_model",{sessionId:this.sessionId,modelId:l}),this.applyModelChange(l),{stopReason:"end_turn"}):s==="mode"?(l!==this.currentMode&&await this.forwardRequest("session/set_mode",{sessionId:this.sessionId,modeId:l}),this.applyModeChange(l),{stopReason:"end_turn"}):s==="agent"?(l!==this.agentId&&await this.runAgentCommandInline(l),{stopReason:"end_turn"}):(await this.forwardRequest("session/set_config_option",{sessionId:this.sessionId,configId:s,value:l}),{stopReason:"end_turn"})}runTitleCommand(e){return this.enqueuePrompt(()=>this.runTitleCommandInline(e))}async runTitleCommandInline(e){return e?(this.setTitle(e),{stopReason:"end_turn"}):(this.scheduleSynopsisHook?.(),{stopReason:"end_turn"})}async runInternalPrompt(e){if(this.internalPromptCapture)throw new Error("internal prompt already in flight");let t={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};this.internalPromptCapture=t;try{return await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:e}]}),t.chunks.join("")}finally{this.internalPromptCapture=void 0}}setAgent(e){return this.runAgentCommand(e)}runAgentCommand(e){return this.enqueuePrompt(()=>this.runAgentCommandInline(e))}async runAgentCommandInline(e){if(e==="status")return this.runAgentStatusCommandInline();let t=e;if(!t)throw ne(new Error("/hydra agent requires an agent id"),S.InvalidParams);let r=(this.resolveAgentIdHook?await this.resolveAgentIdHook(t):void 0)??t;if(r===this.agentId)throw ne(new Error(`already on agent ${r}`),S.InvalidParams);return this.scheduleCompactionHook?(this.scheduleCompactionHook({targetAgentId:r}),this.emitExtensionReply(`Agent switch to ${r} scheduled. The session will rotate to ${r} once synthesis completes.`),{stopReason:"end_turn"}):(this.emitExtensionReply("agent switching not configured for this session"),{stopReason:"end_turn"})}async runAgentStatusCommandInline(){let e=await this.getPendingAgentSwapHook?.();return e?(this.emitExtensionReply(`Agent switch to ${e} pending \u2014 will rotate on the next idle edge.`),{stopReason:"end_turn"}):(this.emitExtensionReply("No agent switch pending."),{stopReason:"end_turn"})}async runKillCommand(){return await this.close({deleteRecord:!1}),{stopReason:"end_turn"}}runRestartCommand(){return this.enqueuePrompt(()=>this.runRestartCommandInline())}async runRestartCommandInline(){if(!this.spawnReplacementAgent)throw ne(new Error("agent restart not configured for this session"),S.InternalError);return await this.respawnAgent(),{stopReason:"end_turn"}}runCompactCommand(e){return this.enqueuePrompt(()=>this.runCompactCommandInline(e))}async runCompactCommandInline(e){return e==="status"?this.runCompactStatusCommandInline():this.scheduleCompactionHook?(this.scheduleCompactionHook(),this.emitExtensionReply("Compaction scheduled. The session will rotate to a fresh upstream once summarization completes."),{stopReason:"end_turn"}):(this.emitExtensionReply("compaction scheduling not configured for this session"),{stopReason:"end_turn"})}async runCompactStatusCommandInline(){let e=await this.getCompactionStateHook?.(),t=this._summarizedThroughEntry;if(e==null&&t==null)return this.emitExtensionReply("This session has never been compacted."),{stopReason:"end_turn"};if(e==null)return this.emitExtensionReply(`No compaction in progress. Last summarized through entry: ${t}`),{stopReason:"end_turn"};let s=[`Compaction state: ${e.status}${e.iter!=null?` (iteration ${e.iter})`:""}`,`Summarized through entry: ${t??0}`,`Pending attempts: ${e.attempts??0}`];return this.emitExtensionReply(s.join(`
|
|
73
|
+
`)),{stopReason:"end_turn"}}runUncompactCommand(){return this.enqueuePrompt(()=>this.runUncompactCommandInline())}async runUncompactCommandInline(){if(!this.uncompactHook)return this.emitExtensionReply("Rollback not available: uncompact hook not configured for this session."),{stopReason:"end_turn"};try{await this.uncompactHook(),this.emitExtensionReply("Rolled back to pre-compaction upstream. The session is now using the previous agent context.")}catch(e){this.emitExtensionReply(`Rollback failed: ${e instanceof Error?e.message:String(e)}`)}return{stopReason:"end_turn"}}async forceCancel(){if(this.closed||this.closing)throw ne(new Error("session is closing"),S.SessionClosing);return this.lastCancelAt=0,this.forceCancelling=!0,await this.close({deleteRecord:!1}),{stopReason:"cancelled"}}async respawnAgent(){let e=this.spawnReplacementAgent,t=this.agentId,s=await this.buildSwitchTranscript(t),r=await e({agentId:t,cwd:this.cwd,agentArgs:this.agentArgs,...this.forwardedEnv?{forwardedEnv:this.forwardedEnv}:{}});this.accumulateAndResetCost(),this.wireAgent(r.agent);let o=this.agent;this.agent=r.agent,this.upstreamSessionId=r.upstreamSessionId,this.agentMeta=r.agentMeta,this.agentCapabilities=r.agentCapabilities,this.agentAdvertisedCommands=[],this.broadcastMergedCommands(),this.currentModel=r.initialModel,this.currentMode=r.initialMode,this.setAgentAdvertisedModels(r.initialModels??[]),this.setAgentAdvertisedModes(r.initialModes??[]),await o.kill().catch(()=>{}),s&&await this.runInternalPrompt(s).catch(()=>{}),this.broadcastAgentSwitch(t,t);let i={agentId:t,upstreamSessionId:this.upstreamSessionId};for(let a of this.agentChangeHandlers)try{a(i)}catch{}}async buildSwitchTranscript(e,t){let s=[],r=await this.getHistorySnapshot();for(let l of r){if(l.method!=="session/update")continue;let f=(l.params??{}).update;if(!f||f._meta?.["hydra-acp"]?.synthetic)continue;let c=f.sessionUpdate;if(c==="prompt_received"){let g=Je(f.prompt);g&&s.push({speaker:"user",text:g})}else if(c==="agent_message_chunk"){let m=f.content?.text;m&&s.push({speaker:`agent: ${e}`,text:m})}else if(c==="tool_call"||c==="tool_call_update"){let g=f.status,m=f.title;(g==="completed"||g==="failed")&&s.push({speaker:"tool",text:`${m??"?"} ${g}`})}}if(s.length===0)return"";let o=[],i;for(let l of s)i&&i.speaker===l.speaker?i.text+=l.text:(i&&o.push(`<${i.speaker}>: ${i.text.trim()}`),i={speaker:l.speaker,text:l.text});i&&o.push(`<${i.speaker}>: ${i.text.trim()}`);let a=t?.intro??`You are taking over this conversation from ${e}. Below is the transcript so far.`,u=t?.followup??`Each line is prefixed with its speaker. Continue from where ${e} left off, responding to the user's most recent message.`;return[a,u,"","--- begin transcript ---",...o,"--- end transcript ---"].join(`
|
|
74
|
+
`)}async seedFromImport(){await this.enqueuePrompt(async()=>{let e=await this.buildSwitchTranscript(this.agentId,{intro:"You are continuing a conversation that was imported from another hydra. Below is the transcript so far.",followup:"Each line is prefixed with its speaker. Treat this as context for the next user message; do not re-respond to earlier turns."});e&&await this.runInternalPrompt(e).catch(()=>{})})}async seedFromFork(e){await this.enqueuePrompt(async()=>{let t=this.title??"(untitled)",s=[];if(this.historyStore)try{s=await this.historyStore.load(this.sessionId)}catch(o){this.logger?.warn(`seedFromFork: historyStore.load failed: ${o.message}`)}let r=qn({synopsis:e,title:t,tail:s,tailK:ed,tailFloor:td,watermark:this._summarizedThroughEntry});if(this.internalPromptCapture)throw new Error("seedFromFork: internal prompt already in flight");this.internalPromptCapture={chunks:[],toolCalls:0,thinkingChars:0,messageChars:0};try{await this.agent.connection.request("session/prompt",{sessionId:this.upstreamSessionId,prompt:[{type:"text",text:r}]});let o=this.internalPromptCapture;this.logger?.info(`seedFromFork: seed processed sessionId=${this.sessionId} seedChars=${r.length} toolCalls=${o.toolCalls} thinkingChars=${o.thinkingChars} messageChars=${o.messageChars}`)}finally{this.internalPromptCapture=void 0}})}broadcastAgentSwitch(e,t){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,agentId:t,pendingAgentSwap:null}}}}),this.broadcastConfigOptions()}broadcastPendingAgentSwap(e){this.recordAndBroadcast("session/update",{sessionId:this.sessionId,update:{sessionUpdate:"session_info_update",_meta:{"hydra-acp":{synthetic:!0,pendingAgentSwap:e}}}})}hasStreamBuffer(){return this.streamBuffer!==void 0}get streamPath(){return this.streamFilePath}openStream(e){if(this.streamBuffer!==void 0)throw new Error(`stream buffer already open for session ${this.sessionId}`);let s=(e.mode??"memory")==="file"&&e.filePathFor!==void 0?e.filePathFor(this.sessionId):void 0,r={};e.capacityBytes!==void 0&&(r.capacityBytes=e.capacityBytes),s!==void 0&&(r.filePath=s),e.fileCapBytes!==void 0&&(r.fileCapBytes=e.fileCapBytes),r.onFileCapReached=()=>{this.recordAndBroadcast("session/update",{sessionId:this.upstreamSessionId,update:{sessionUpdate:"stream_truncated",...s!==void 0?{filePath:s}:{},fileCapBytes:e.fileCapBytes}})};let o=new Nt(r);this.streamBuffer=o,this.streamFilePath=s;let i={capacityBytes:o.capacity};return s!==void 0&&(i.filePath=s),e.fileCapBytes!==void 0&&(i.fileCapBytes=e.fileCapBytes),i}streamWrite(e,t){let s=this.requireStreamBuffer();if(e.length>0){let r=Buffer.from(e,"base64");s.append(r)}return t===!0&&s.close(),{writeCursor:s.writeCursorPos}}async streamRead(e,t,s){let r=this.requireStreamBuffer(),o=Math.max(0,Math.min(t??De,De)),i=r.read(e,o);if(i.bytes.length===0&&i.eof!==!0&&s!==void 0&&s>0){let u=await r.waitForData(i.nextCursor,s);(u==="data"||u==="eof")&&(i=r.read(i.nextCursor,o))}let a={bytes:i.bytes.toString("base64"),nextCursor:i.nextCursor};return i.gap!==void 0&&(a.gap=i.gap),i.eof===!0&&(a.eof=!0),a}streamTail(e){let s=this.requireStreamBuffer().tail(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}streamHead(e){let s=this.requireStreamBuffer().head(e);return{bytes:s.bytes.toString("base64"),startCursor:s.startCursor,endCursor:s.endCursor,truncated:s.truncated}}async streamWaitFor(e,t){return this.requireStreamBuffer().waitForData(e,t)}streamGrep(e){return this.requireStreamBuffer().grep(e)}streamInfo(){let e=this.requireStreamBuffer();return{writeCursor:e.writeCursorPos,oldestAvailable:e.oldestAvailable,capacity:e.capacity,closed:e.isClosed}}requireStreamBuffer(){if(this.streamBuffer===void 0){let e=new Error(`session ${this.sessionId} has no stream buffer; POST /v1/sessions/:id/stdin/open first`);throw e.code=S.StreamNotEnabled,e}return this.streamBuffer}markClosed(e){if(this.closed)return;e={deleteRecord:e.deleteRecord||this.deleteRecordIntent},this.closing=!0,this.closed=!0,this.cancelIdleTimer(),this.extensionCommandsUnsub&&(this.extensionCommandsUnsub(),this.extensionCommandsUnsub=void 0);for(let o of[...this.inFlightExtensionDispatches.keys()])this.cancelExtensionDispatch(o,"abandoned");this.currentEntry?.kind==="user"&&!this.recentlyTerminal.has(this.currentEntry.messageId)&&this.broadcastTurnComplete(this.currentEntry.clientId,{stopReason:"interrupted"},this.currentEntry.messageId,this.currentEntry.wasAmend),this.currentEntry=void 0;let s=this.promptQueue;this.promptQueue=[];for(let o of s){o.cancelled=!0,o.kind==="user"&&this.broadcastQueueRemoved(o.messageId,"abandoned");try{o.resolve({stopReason:"cancelled"})}catch{}}this.notifyChain("session.closed",{}),this.toolCompletionSeen.clear(),this.toolCallKind.clear(),this.filesEditedSeen.clear();let r=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>Pr(r).catch(()=>{}));for(let o of this.clients.values())o.connection.notify("hydra-acp/session/closed",{sessionId:this.sessionId}).catch(()=>{});if(this.clients.clear(),this.streamBuffer!==void 0){let o=this.streamBuffer,i=this.streamFilePath;this.streamBuffer=void 0,this.streamFilePath=void 0,o.close(),i!==void 0&&o.drainFileWrites().then(()=>jr.unlink(i).catch(()=>{}))}for(let o of this.closeHandlers)o(e)}get lastActivityAt(){return this.lastRecordedAt}setAttentionFlag(e,t,s){this._setAttentionFlag(e,t,s,!0)}_setAttentionFlag(e,t,s,r){let o=`${e}::${t}`,i=this.attentionFlags.get(o);if(i){if(JSON.stringify(i.payload)===JSON.stringify(s))return;this.attentionFlags.set(o,{...i,payload:s,raisedAt:i.raisedAt})}else this.attentionFlags.set(o,{source:e,reason:t,raisedAt:Date.now(),payload:s});r&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}clearAttentionFlag(e,t){this._clearAttentionFlag(e,t,!0)}_clearAttentionFlag(e,t,s){let r=`${e}::${t}`;this.attentionFlags.delete(r)&&s&&(this.broadcastAttentionUpdated(),this.fireAttentionFlagsChange())}listAttentionFlags(){return Array.from(this.attentionFlags.values()).sort((e,t)=>e.raisedAt-t.raisedAt)}listAttentionFlagsBySource(e){return this.listAttentionFlags().filter(t=>t.source===e)}onAttentionFlagsChange(e){this.attentionFlagsChangeHandlers.push(e)}fireAttentionFlagsChange(){let e=this.listAttentionFlags();for(let t of this.attentionFlagsChangeHandlers)try{t(e)}catch{}}broadcastAttentionUpdated(){for(let e of this.clients.values())e.connection.notify("hydra-acp/session/attention_updated",{sessionId:this.sessionId,flags:this.listAttentionFlags()}).catch(()=>{})}scheduleIdleCheck(){if(this.closed||this.idleTimeoutMs<=0)return;let e=this.lastActivityAt+this.idleTimeoutMs;this.armIdleTimer(Math.max(0,e-Date.now()))}armIdleTimer(e){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.checkIdle()},e),typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}checkIdle(){if(this.closed||this.idleTimeoutMs<=0)return;if(this.turnStartedAt!==void 0||this.hasPermissionFlag||this.promptQueue.length>0){this.armIdleTimer(this.idleTimeoutMs);return}let e=Date.now()-this.lastActivityAt;if(e<this.idleTimeoutMs){this.armIdleTimer(this.idleTimeoutMs-e);return}let t=this.firstPromptSeeded?{deleteRecord:!1}:{deleteRecord:!0},s=Math.round(e/1e3);this.logger?.info(`session ${this.sessionId} idle timeout fired after ${s}s (window=${Math.round(this.idleTimeoutMs/1e3)}s) \u2014 closing`),this.close(t).catch(()=>{})}cancelIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.disposeIdleHandlers()}onIdle(e,t){let s={fn:e,once:!!t?.once,debounceMs:t?.debounceMs??0};return this.idleHandlers.push(s),()=>{let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1),s.timer&&(clearTimeout(s.timer),s.timer=void 0)}}onceIdle(e){return this.onIdle(e,{once:!0})}dispatchIdle(){if(this.closed)return;if(!this.isQuiescedSync()){for(let s of this.idleHandlers)s.timer&&(clearTimeout(s.timer),s.timer=void 0);return}let t=[...this.idleHandlers];for(let s of t){if(s.debounceMs===0){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}continue}s.timer&&(clearTimeout(s.timer),s.timer=void 0),s.timer=setTimeout(()=>{if(s.timer=void 0,!this.closed&&this.isQuiescedSync()){if(s.once){let r=this.idleHandlers.indexOf(s);r>=0&&this.idleHandlers.splice(r,1)}try{s.fn(this)}catch{}}},s.debounceMs),typeof s.timer.unref=="function"&&s.timer.unref()}}disposeIdleHandlers(){for(let e of this.idleHandlers)e.timer&&(clearTimeout(e.timer),e.timer=void 0);this.idleHandlers.length=0}maybeEmitToolEdges(e){if(!e||typeof e!="object")return;let t=e.update;if(!t||typeof t!="object")return;let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:"";if(r!=="tool_call"&&r!=="tool_call_update")return;let o=typeof s.toolCallId=="string"&&s.toolCallId.length>0?s.toolCallId:void 0;if(!o)return;let i=typeof s.kind=="string"?s.kind:void 0;i&&!this.toolCallKind.has(o)&&this.toolCallKind.set(o,i);let a=i??this.toolCallKind.get(o);if(a==="edit"&&Array.isArray(s.locations))for(let d of s.locations){if(!d||typeof d!="object")continue;let f=d.path;if(typeof f!="string"||f.length===0||this.filesEditedSeen.has(f))continue;this.filesEditedSeen.add(f);let p=d.line,c={path:f,toolCallId:o};typeof p=="number"&&(c.line=p),this.notifyChain("file.edited",c)}if(r!=="tool_call_update")return;let u=typeof s.status=="string"?s.status:void 0;if(u!=="completed"&&u!=="failed"||this.toolCompletionSeen.has(o))return;this.toolCompletionSeen.set(o,u);let l={toolCallId:o,status:u};a&&(l.kind=a),s.content!==void 0&&(l.content=s.content),Array.isArray(s.locations)&&(l.locations=s.locations),this.notifyChain("tool.completed",l)}notifyChain(e,t){let s=`lifecycle:${e}`;for(let r of this.transformChain)r.intercepts.has(s)&&r.connection.notify("hydra-acp/transformer/session_event",{event:e,sessionId:this.sessionId,payload:t}).catch(()=>{})}rewriteForClient(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.sessionId=="string"&&t.sessionId!==this.sessionId)return{...t,sessionId:this.sessionId}}return e}recordAndBroadcast(e,t,s){let r=this.rewriteForClient(t),o=!Tr(e,r),i=o?ld(e,r):r;if(o){let a={method:e,params:i,recordedAt:Date.now()};if(this.lastRecordedAt=a.recordedAt,this.appendCount+=1,this.historyStore){let u=this.historyStore;u.append(this.sessionId,a).catch(()=>{}),this.appendCount>=this.compactEvery&&(this.appendCount=0,u.compact(this.sessionId,this.historyMaxEntries).catch(()=>{}))}for(let u of this.broadcastHandlers)try{u(a)}catch{}this.scheduleIdleCheck(),this.dispatchIdle()}this.updatedAt=Date.now();for(let a of this.clients.values())s&&a.clientId===s||a.connection.notify(e,i).catch(()=>{})}async requestPermissionFromClients(e){return this.handlePermissionRequest(e)}async handlePermissionRequest(e){let t=[...this.clients.values()];if(t.length===0)throw ne(new Error("no clients attached to handle permission request"),S.PermissionDenied);let s=this.rewriteForClient(e),r=_r(s),o=Ae(),{toolCall:i,options:a}=s??{};return new Promise((u,l)=>{let d=!1,f=[],p=0,c,g=this.sessionId,m=y=>{d||(d=!0,this.clearAttentionFlag("daemon",`permission:${o}`),this.permissionCallbacks.delete(o),y())},h=y=>y?.code===S.MethodNotFound;function v(y){if(d)return;let w=y.connection.request("session/request_permission",s);f.push({client:y}),p++,w.then(b=>{p--,m(()=>{let A=fd({toolCallId:r,result:b,resolver:y});for(let x of f)x.client.clientId!==y.clientId&&x.client.connection.notify("session/update",{sessionId:g,update:A}).catch(()=>{});u(b)})}).catch(b=>{if(p--,h(b)||(c=b),p===0&&!d){let A=c??ne(new Error("no client handled permission request"),S.PermissionDenied);m(()=>l(A))}})}this.setAttentionFlag("daemon",`permission:${o}`,{kind:"permission",toolCall:i??null,options:a??null}),this.permissionCallbacks.set(o,v);for(let y of t)v(y)})}async enqueuePrompt(e){return new Promise((t,s)=>{let r={kind:"internal",messageId:Ae(),enqueuedAt:Date.now(),cancelled:!1,task:e,resolve:t,reject:s};this.promptQueue.push(r),this.drainQueue()})}async enqueueUserPrompt(e,t,s){let r=(t??{}).prompt??[],o={clientId:e.clientId};e.clientInfo?.name&&(o.name=e.clientInfo.name),e.clientInfo?.version&&(o.version=e.clientInfo.version);let i=this.parseQueuePosition(t);return new Promise((a,u)=>{let l={kind:"user",messageId:s,originator:o,clientId:e.clientId,prompt:r,enqueuedAt:Date.now(),cancelled:!1,resolve:a,reject:u},d=this.insertEntryAt(l,i);this.persistRewrite(),this.broadcastQueueAdded(l,{position:d}),this.drainQueue()})}parseQueuePosition(e){if(!e||typeof e!="object")return"tail";let t=e._meta;if(!t||typeof t!="object"||Array.isArray(t))return"tail";let s=t["hydra-acp"];if(!s||typeof s!="object"||Array.isArray(s))return"tail";let r=s.queuePosition;if(r==="head"||r==="tail")return r;if(r&&typeof r=="object"&&!Array.isArray(r)){let o=r.afterMessageId;if(typeof o=="string"&&o.length>0)return{afterMessageId:o}}return"tail"}insertEntryAt(e,t){let s=this.currentEntry?.kind==="user"&&!this.currentEntry.cancelled?1:0;if(t==="head")return this.promptQueue.unshift(e),s;if(typeof t=="object"){let r=t.afterMessageId,o=this.promptQueue.findIndex(i=>i.messageId===r);if(o>=0)return this.promptQueue.splice(o+1,0,e),s+o+1}return this.promptQueue.push(e),s+this.promptQueue.length-1}persistRewrite(){let e=[];for(let s of this.promptQueue)s.kind!=="user"||s.cancelled||e.push(this.persistedFromEntry(s));let t=this.sessionId;this.queueWriteChain=this.queueWriteChain.catch(()=>{}).then(()=>ct(t,e).catch(()=>{}))}persistedFromEntry(e){return{messageId:e.messageId,originator:{clientInfo:{...e.originator.name!==void 0?{name:e.originator.name}:{},...e.originator.version!==void 0?{version:e.originator.version}:{}}},prompt:e.prompt,enqueuedAt:e.enqueuedAt}}async drainQueue(){if(!this.promptInFlight){this.promptInFlight=!0,await new Promise(e=>setImmediate(e));try{for(;this.promptQueue.length>0&&!this.closing;){let e=this.promptQueue.shift();if(!e)break;if(!e.cancelled){this.currentEntry=e,e.kind==="user"&&this.persistRewrite(),e.kind==="user"&&this.broadcastQueueRemoved(e.messageId,"started");try{let t=await this.runQueueEntry(e);e.resolve(t),await new Promise(s=>setImmediate(s))}catch(t){e.reject(t)}finally{this.currentEntry=void 0}}}}finally{this.promptInFlight=!1,this.dispatchIdle()}}}async runQueueEntry(e){if(e.kind==="internal")return e.task();this.broadcastPromptReceived(e);let t=Je(e.prompt).replace(/\s+$/,""),s=!t.includes(`
|
|
75
|
+
`)&&t.startsWith("/")?t.split(/\s+/)[0]??"":"",r=s.startsWith("/")?s.slice(1):"",o=r.length>0&&this.aliasableBareVerbs().has(r);if(s==="/model"||s==="/mode"||s==="/sessions"||s==="/help"||s==="/hydra"||o){let a;if(s==="/sessions")a=await this.handleSessionsCommand();else if(s==="/help")a=await this.handleHelpCommand();else if(s==="/mode")a=await this.handleModeCommand(t);else if(s==="/model")a=await this.handleModelCommand(t);else if(o){let u=t.slice(s.length).trim(),l=u?`/hydra ${r} ${u}`:`/hydra ${r}`;a=await this.handleSlashCommand(l,e.messageId)}else a=await this.handleSlashCommand(t,e.messageId);return this.closed||this.broadcastTurnComplete(e.clientId,a,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}if(this.clearRollbackBreadcrumbHook)try{this.clearRollbackBreadcrumbHook()}catch{}let i;try{i=await this.forwardRequest("session/prompt",{sessionId:this.sessionId,prompt:e.prompt},e.emitterName?new Set([e.emitterName]):new Set,e.chainStartIdx??0)}catch(a){if(this.forceCancelling)return this.clearAmendIfMatches(e.messageId),{stopReason:"cancelled"};throw this.closed||this.broadcastTurnComplete(e.clientId,{stopReason:"error"},e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),a}return this.closed||this.broadcastTurnComplete(e.clientId,i,e.messageId,e.wasAmend),this.clearAmendIfMatches(e.messageId),i}clearAmendIfMatches(e){this.amendInProgress?.cancelledMessageId===e&&(this.amendInProgress=void 0)}};function ne(n,e){return n.code=e,n}var rd=new Set(["session_info_update","current_model_update","current_mode_update","available_commands_update","available_modes_update","usage_update","config_option_update","hydra_compaction"]);function Tr(n,e){if(n!=="session/update")return!1;let s=(e??{}).update?.sessionUpdate;return typeof s=="string"&&rd.has(s)}function od(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 id(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 ad(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]?.modelId!==e[t]?.modelId||n[t]?.name!==e[t]?.name||n[t]?.description!==e[t]?.description)return!1;return!0}function We(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.modelId=="string"&&s.modelId.trim()||typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={modelId:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function ut(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object"||Array.isArray(t))continue;let s=t,r=typeof s.value=="string"&&s.value.trim()||typeof s.id=="string"&&s.id.trim()||void 0;if(!r)continue;let o={id:r};typeof s.name=="string"&&s.name.length>0&&(o.name=s.name),typeof s.description=="string"&&s.description.length>0&&(o.description=s.description),e.push(o)}return e}function dd(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_modes_update")return null;let s=t.availableModes;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.id!="string"||i.id.length===0)continue;let a={id:i.id};typeof i.name=="string"&&(a.name=i.name),typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function cd(n,e){let s=(e??{}).update??{},r=s.sessionUpdate;if(r==="agent_message_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.chunks.push(o.text),n.messageChars+=o.text.length);return}if(r==="agent_thought_chunk"){let o=s.content??{};typeof o.text=="string"&&(n.thinkingChars+=o.text.length);return}if(r==="tool_call"){n.toolCalls++;return}if(r==="usage_update"){typeof s.used=="number"&&(n.lastUsed=s.used),typeof s.size=="number"&&(n.lastSize=s.size);return}}function ud(n){let t=(n??{}).update??{};if(t.sessionUpdate!=="available_commands_update")return null;let s=t.availableCommands??t.commands;if(!Array.isArray(s))return[];let r=[];for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(typeof i.name!="string"||i.name.length===0)continue;let a={name:i.name};typeof i.description=="string"&&(a.description=i.description),r.push(a)}return r}function ld(n,e){if(n!=="session/update"||!e||typeof e!="object")return e;let t=e;return!t.update||typeof t.update!="object"||Array.isArray(t.update)||typeof t.update.messageId=="string"?e:{...e,update:{...t.update,messageId:Ae()}}}function Wn(n,e){for(let t=0;t<n.length;t++){let s=n[t];if(!s||s.method!=="session/update")continue;if(s.params?.update?.messageId===e)return t}return-1}function _r(n){if(!n||typeof n!="object")return;let e=n.toolCall;if(!e||typeof e!="object")return;let t=e.toolCallId;return typeof t=="string"?t:void 0}function fd(n){let e=pd(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=gd(n.resolver),t}function pd(n){if(!n||typeof n!="object")return;let e=n.outcome;if(!e||typeof e!="object")return;let t=e.kind;if(typeof t!="string")return;let s={kind:t},r=e.optionId;typeof r=="string"&&(s.optionId=r);let o=e.reason;return typeof o=="string"&&(s.reason=o),s}function gd(n){let e={clientId:n.clientId};return n.clientInfo?.name&&(e.name=n.clientInfo.name),n.clientInfo?.version&&(e.version=n.clientInfo.version),e}function Je(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):""}function Jn(n){return n==="session/prompt"?{stopReason:"stopped"}:{}}function md(n){return n==="session/request_permission"?{outcome:{outcome:"cancelled"}}:{}}function $r(n){let e=n.name&&n.name!==n.id?`${n.id} (${n.name}) \u2014 \u25B6 ${n.currentValue}`:`${n.id} \u2014 \u25B6 ${n.currentValue}`;if(n.options.length===0)return e;let t=Math.max(...n.options.map(r=>r.value.length)),s=n.options.map(r=>{let o=r.value===n.currentValue?"\u25B6":"\xB7",i=r.name&&r.name!==r.value,a=i?r.value.padEnd(t):r.value;return i?` ${o} ${a} ${r.name}`:` ${o} ${a}`});return`${e}
|
|
76
76
|
${s.join(`
|
|
77
|
-
`)}`}function Qn(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as
|
|
77
|
+
`)}`}function Qn(n,e){for(let t of n.split(/\r?\n/)){let s=t.trim();if(s)return s.length>e?`${s.slice(0,e)}\u2026`:s}}import*as Ke from"fs/promises";import*as Zf from"path";import{customAlphabet as wd}from"nanoid";import{z as R}from"zod";import{z as Qe}from"zod";var hd=Qe.object({source:Qe.string(),reason:Qe.string(),raisedAt:Qe.number(),payload:Qe.unknown()}),Br=Qe.array(hd);import{z as q}from"zod";var Ur=q.object({status:q.enum(["requested","running","swap_pending","swap_deferred","failed"]),requestedAt:q.number(),iter:q.number().int().nonnegative().optional(),attempts:q.number().int().nonnegative().optional(),lastError:q.string().optional(),worker:q.object({upstreamSessionId:q.string(),pid:q.number().int().nonnegative()}).optional()}),lt=q.object({goal:q.string().optional(),outcome:q.string().optional(),files_touched:q.array(q.string()).optional(),tools_used:q.array(q.string()).optional(),rejected_approaches:q.array(q.string()).optional(),open_threads:q.array(q.string()).optional(),decisions:q.array(q.string()).optional(),file_edit_intentions:q.array(q.string()).optional(),unresolved_errors:q.array(q.string()).optional(),tool_state:q.array(q.string()).optional()}),Dr=200,Vn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
78
78
|
{
|
|
79
79
|
"title": "short summary, max 80 chars",
|
|
80
80
|
"synopsis": {
|
|
@@ -84,7 +84,7 @@ ${s.join(`
|
|
|
84
84
|
"open_threads": ["work started but not finished"]
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
Use empty arrays/strings where a field doesn't apply.`;function Lr(n){let e=n.trim();if(e.length===0)return;let t=
|
|
87
|
+
Use empty arrays/strings where a field doesn't apply.`;function Lr(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let o=e.indexOf("{"),i=e.lastIndexOf("}");o>=0&&i>o&&(t=Ve(e.slice(o,i+1)))}if(t===void 0){let o=zr(e);o!==void 0&&(t=Ve(o))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let o=s.title.trim();o.length>0&&(r.title=o.slice(0,Dr))}if(s.synopsis!==void 0&&s.synopsis!==null){let o=lt.safeParse(s.synopsis);o.success&&yd(o.data)&&(r.synopsis=o.data)}if(!(r.title===void 0&&r.synopsis===void 0))return r}var Kn=`Reply with ONLY a JSON object with exactly these keys, no prose, no markdown, no code fences:
|
|
88
88
|
{
|
|
89
89
|
"title": "short summary, max 80 chars",
|
|
90
90
|
"goal": "the user's original ask",
|
|
@@ -96,50 +96,49 @@ Use empty arrays/strings where a field doesn't apply.`;function Lr(n){let e=n.tr
|
|
|
96
96
|
"unresolved_errors": ["errors left open at session end"],
|
|
97
97
|
"tool_state": ["runtime state relevant for recall"]
|
|
98
98
|
}
|
|
99
|
-
Use empty arrays/strings where a field doesn't apply.`;function qr(n){let e=n.trim();if(e.length===0)return;let t=Ke(e);if(t===void 0){let u=e.indexOf("{"),d=e.lastIndexOf("}");u>=0&&d>u&&(t=Ke(e.slice(u,d+1)))}if(t===void 0){let u=zr(e);u!==void 0&&(t=Ke(u))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let u=s.title.trim();u.length>0&&(r.title=u.slice(0,Dr))}let o={},i=!1,a=["goal","outcome"];for(let u of a)if(typeof s[u]=="string"){let d=s[u].trim();d.length>0&&(o[u]=d,i=!0)}let c=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let u of c)if(Array.isArray(s[u])){let d=s[u],f=q.array(q.string()).safeParse(d);f.success&&d.length>0&&(o[u]=f.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ke(n){try{return JSON.parse(n)}catch{return}}function zr(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let o=e;o<n.length;o++){let i=n[o];if(s){r?r=!1:i==="\\"?r=!0:i==='"'&&(s=!1);continue}if(i==='"'){s=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function gd(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var yd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wd=hd(yd,16),vd="hydra_lineage_";function ft(){return`${vd}${wd()}`}var Yn=R.object({name:R.string(),description:R.string().optional()}),Xn=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),bd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),Zn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),es=R.object({name:R.string(),version:R.string().optional()}),Id=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Sd=R.object({version:R.literal(1),sessionId:R.string(),lineageId:R.string().optional(),upstreamSessionId:R.string(),importedFromSessionId:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),importedFromMachine:R.string().optional(),agentId:R.string(),cwd:R.string(),title:R.string().optional(),synopsis:lt.optional(),compactionState:Ur.optional(),rollbackBreadcrumb:Id.optional(),summarizedThroughEntry:R.number().int().nonnegative().optional(),agentArgs:R.array(R.string()).optional(),currentModel:R.string().optional(),currentMode:R.string().optional(),currentUsage:Zn.optional(),agentCommands:R.array(Yn).optional(),agentModes:R.array(Xn).optional(),agentModels:R.array(bd).optional(),pendingHistorySync:R.boolean().optional(),pendingAgentSwap:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),forkSynthesisState:R.enum(["running","failed"]).optional(),originatingClient:es.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:Br.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),Gn=/^[A-Za-z0-9_-]+$/;function kd(n){if(!Gn.test(n))throw new Error(`unsafe session id: ${n}`)}var Bt=class{async write(e){kd(e.sessionId);let t={version:1,...e};await de(S.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Gn.test(e))return;let t=await ue(S.sessionFile(e));if(t!==void 0)try{return Sd.parse(t)}catch{return}}async delete(e){if(Gn.test(e)){try{await Ge.unlink(S.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ge.rmdir(S.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Ge.readdir(S.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}};function ts(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as me}from"zod";var Ad=me.object({version:me.literal(1),agentId:me.string(),upstreamSessionId:me.string(),deletedAt:me.string(),upstreamUpdatedAt:me.string().optional(),cwd:me.string().optional(),title:me.string().optional(),reason:me.enum(["user","expired"]).optional(),interactive:me.boolean().optional()}),Ut=class{async add(e){let t={version:1,...e};await de(S.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(S.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=S.tombstoneFile(e,t),r=await ue(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return Ad.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(S.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(S.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await we.readdir(S.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let t;try{t=await we.readdir(S.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function Jr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as so from"fs/promises";import{fileURLToPath as Cd}from"url";import*as pt from"path";import*as Dt from"fs";function xd(){try{let n=pt.dirname(Cd(import.meta.url));for(let e=0;e<8;e+=1){let t=pt.join(n,"package.json");if(Dt.existsSync(t)){let r=JSON.parse(Dt.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=pt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var K=xd(),Lt="hydra-acp-cat";var Md=12e4;async function Qr(n,e,t){let s=n.timeoutMs??Md,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let c=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),u=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=u.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(d,r.pid),n.modelId){let m=Ed(u);if(m.size===0||m.has(n.modelId))try{await r.connection.request("session/set_model",{sessionId:d,modelId:n.modelId})}catch(g){n.logger?.warn(`synopsis: agent ${n.agentId} rejected set_model ${JSON.stringify(n.modelId)}: ${g.message}; continuing on default`)}else n.logger?.warn(`synopsis: model ${JSON.stringify(n.modelId)} not advertised by agent ${n.agentId} (have [${[...m].join(", ")}]); continuing on default`)}let f=[];r.connection.onNotification("session/update",m=>{let g=Rd(m);g.length>0&&f.push(g)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let p=f.join(""),l=t(p);if(!l){let m=JSON.stringify(p.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${p.length} preview=${m})`);let g=p.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${p.length} chars): ${g}${p.length>120?"\u2026":""}`)}return l})();return await new Promise((c,u)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),c(void 0)},s),o.unref?.(),a.then(d=>{o&&clearTimeout(o),i||c(d)},d=>{o&&clearTimeout(o),i||u(d)})})}catch(a){let c=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${c}`),n.onFailure?.(`agent ${n.agentId} failed: ${c}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function qt(n){let e=Je(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
|
|
99
|
+
Use empty arrays/strings where a field doesn't apply.`;function qr(n){let e=n.trim();if(e.length===0)return;let t=Ve(e);if(t===void 0){let l=e.indexOf("{"),d=e.lastIndexOf("}");l>=0&&d>l&&(t=Ve(e.slice(l,d+1)))}if(t===void 0){let l=zr(e);l!==void 0&&(t=Ve(l))}if(t===void 0||t===null||typeof t!="object")return;let s=t,r={};if(typeof s.title=="string"){let l=s.title.trim();l.length>0&&(r.title=l.slice(0,Dr))}let o={},i=!1,a=["goal","outcome"];for(let l of a)if(typeof s[l]=="string"){let d=s[l].trim();d.length>0&&(o[l]=d,i=!0)}let u=["files_touched","tools_used","rejected_approaches","open_threads","decisions","file_edit_intentions","unresolved_errors","tool_state"];for(let l of u)if(Array.isArray(s[l])){let d=s[l],f=q.array(q.string()).safeParse(d);f.success&&d.length>0&&(o[l]=f.data,i=!0)}if(i&&(r.synopsis=o),!(r.title===void 0&&r.synopsis===void 0))return r}function Ve(n){try{return JSON.parse(n)}catch{return}}function zr(n){let e=n.indexOf("{");if(e<0)return;let t=0,s=!1,r=!1;for(let o=e;o<n.length;o++){let i=n[o];if(s){r?r=!1:i==="\\"?r=!0:i==='"'&&(s=!1);continue}if(i==='"'){s=!0;continue}if(i==="{")t++;else if(i==="}"&&(t--,t===0))return n.slice(e,o+1)}}function yd(n){return n.goal!==void 0&&n.goal.trim().length>0||n.outcome!==void 0&&n.outcome.trim().length>0||n.files_touched!==void 0&&n.files_touched.length>0||n.tools_used!==void 0&&n.tools_used.length>0||n.rejected_approaches!==void 0&&n.rejected_approaches.length>0||n.open_threads!==void 0&&n.open_threads.length>0||n.decisions!==void 0&&n.decisions.length>0||n.file_edit_intentions!==void 0&&n.file_edit_intentions.length>0||n.unresolved_errors!==void 0&&n.unresolved_errors.length>0||n.tool_state!==void 0&&n.tool_state.length>0}var vd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",bd=wd(vd,16),Id="hydra_lineage_";function ft(){return`${Id}${bd()}`}var Yn=R.object({name:R.string(),description:R.string().optional()}),Xn=R.object({id:R.string(),name:R.string().optional(),description:R.string().optional()}),Sd=R.object({modelId:R.string(),name:R.string().optional(),description:R.string().optional()}),Zn=R.object({used:R.number().optional(),size:R.number().optional(),costAmount:R.number().optional(),costCurrency:R.string().optional(),cumulativeCost:R.number().optional()}),es=R.object({name:R.string(),version:R.string().optional()}),kd=R.object({previousUpstreamSessionId:R.string(),previousSummarizedThroughEntry:R.number().int().nonnegative().optional()}),Ad=R.object({version:R.literal(1),sessionId:R.string(),lineageId:R.string().optional(),upstreamSessionId:R.string(),importedFromSessionId:R.string().optional(),importedFromUpstreamSessionId:R.string().optional(),importedFromMachine:R.string().optional(),agentId:R.string(),cwd:R.string(),title:R.string().optional(),synopsis:lt.optional(),compactionState:Ur.optional(),rollbackBreadcrumb:kd.optional(),summarizedThroughEntry:R.number().int().nonnegative().optional(),agentArgs:R.array(R.string()).optional(),currentModel:R.string().optional(),currentMode:R.string().optional(),currentUsage:Zn.optional(),agentCommands:R.array(Yn).optional(),agentModes:R.array(Xn).optional(),agentModels:R.array(Sd).optional(),pendingHistorySync:R.boolean().optional(),pendingAgentSwap:R.string().optional(),parentSessionId:R.string().optional(),forkedFromSessionId:R.string().optional(),forkedFromMessageId:R.string().optional(),forkSynthesisState:R.enum(["running","failed"]).optional(),originatingClient:es.optional(),interactive:R.boolean().optional(),priority:R.number().int().nonnegative().optional(),forwardedEnv:R.record(R.string(),R.string()).optional(),attentionFlags:Br.default([]).optional(),extensionState:R.record(R.string(),R.record(R.string(),R.unknown())).default({}).optional(),createdAt:R.string(),updatedAt:R.string()}),Gn=/^[A-Za-z0-9_-]+$/;function Cd(n){if(!Gn.test(n))throw new Error(`unsafe session id: ${n}`)}var Bt=class{async write(e){Cd(e.sessionId);let t={version:1,...e};await de(k.sessionFile(e.sessionId),t,{mode:384})}async read(e){if(!Gn.test(e))return;let t=await ue(k.sessionFile(e));if(t!==void 0)try{return Ad.parse(t)}catch{return}}async delete(e){if(Gn.test(e)){try{await Ke.unlink(k.sessionFile(e))}catch(t){if(t.code!=="ENOENT")throw t}try{await Ke.rmdir(k.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}}}async findByLineageId(e){if(e.length===0)return;let t=await this.list().catch(()=>[]);for(let s of t)if(s.lineageId===e)return s}async list(){let e;try{e=await Ke.readdir(k.sessionsDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let t=await Promise.all(e.map(r=>this.read(r).catch(()=>{}))),s=[];for(let r of t)r&&s.push(r);return s}};function ts(n){let e=new Date().toISOString();return{sessionId:n.sessionId,lineageId:n.lineageId,upstreamSessionId:n.upstreamSessionId,importedFromSessionId:n.importedFromSessionId,importedFromUpstreamSessionId:n.importedFromUpstreamSessionId,importedFromMachine:n.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:n.synopsis,summarizedThroughEntry:n.summarizedThroughEntry,compactionState:n.compactionState,rollbackBreadcrumb:n.rollbackBreadcrumb,agentArgs:n.agentArgs,currentModel:n.currentModel,currentMode:n.currentMode,currentUsage:n.currentUsage,agentCommands:n.agentCommands,agentModes:n.agentModes,agentModels:n.agentModels,pendingHistorySync:n.pendingHistorySync,pendingAgentSwap:n.pendingAgentSwap,parentSessionId:n.parentSessionId,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,priority:n.priority,forwardedEnv:n.forwardedEnv,attentionFlags:n.attentionFlags??[],extensionState:n.extensionState??{},createdAt:n.createdAt??e,updatedAt:n.updatedAt??e}}import*as we from"fs/promises";import{z as ge}from"zod";var xd=ge.object({version:ge.literal(1),agentId:ge.string(),upstreamSessionId:ge.string(),deletedAt:ge.string(),upstreamUpdatedAt:ge.string().optional(),cwd:ge.string().optional(),title:ge.string().optional(),reason:ge.enum(["user","expired"]).optional(),interactive:ge.boolean().optional()}),Ut=class{async add(e){let t={version:1,...e};await de(k.tombstoneFile(e.agentId,e.upstreamSessionId),t,{mode:384})}async has(e,t){try{return await we.access(k.tombstoneFile(e,t)),!0}catch{return!1}}async read(e,t){let s=k.tombstoneFile(e,t),r=await ue(s);if(r===void 0)return await this.has(e,t)?{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}:void 0;try{return xd.parse(r)}catch{return{version:1,agentId:e,upstreamSessionId:t,deletedAt:new Date(0).toISOString()}}}async remove(e,t){try{await we.unlink(k.tombstoneFile(e,t))}catch(s){if(s.code!=="ENOENT")throw s}try{await we.rmdir(k.tombstoneAgentDir(e))}catch(s){let r=s;if(r.code!=="ENOENT"&&r.code!=="ENOTEMPTY")throw s}}async list(e){if(e!==void 0)return this.listForAgent(e);let t;try{t=await we.readdir(k.tombstonesDir())}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}s.push(...await this.listForAgent(o))}return s}async listForAgent(e){let t;try{t=await we.readdir(k.tombstoneAgentDir(e))}catch(r){if(r.code==="ENOENT")return[];throw r}let s=[];for(let r of t){let o;try{o=decodeURIComponent(r)}catch{continue}let i=await this.read(e,o);i&&s.push(i)}return s}};function Jr(n,e){return n.reason==="user"||e===void 0?!1:n.upstreamUpdatedAt===void 0?!0:e>n.upstreamUpdatedAt}import*as so from"fs/promises";import{fileURLToPath as Md}from"url";import*as pt from"path";import*as Dt from"fs";function Rd(){try{let n=pt.dirname(Md(import.meta.url));for(let e=0;e<8;e+=1){let t=pt.join(n,"package.json");if(Dt.existsSync(t)){let r=JSON.parse(Dt.readFileSync(t,"utf8"));if(typeof r.version=="string"&&r.version.length>0&&(typeof r.name!="string"||r.name.includes("hydra-acp")))return r.version}let s=pt.dirname(n);if(s===n)break;n=s}}catch{}return"0.0.0"}var K=Rd(),Lt="hydra-acp-cat";var Ed=12e4;async function Qr(n,e,t){let s=n.timeoutMs??Ed,r,o,i=!1;try{let a=(async()=>{r=he.spawn({agentId:n.agentId,cwd:n.cwd,plan:n.plan,logger:n.logger});let u=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"hydra-synopsis",version:K}}),l=await r.connection.request("session/new",{cwd:n.cwd,mcpServers:[]}),d=l.sessionId;if(typeof d!="string"){n.logger?.warn(`synopsis: agent ${n.agentId} returned non-string sessionId from session/new`),n.onFailure?.(`agent ${n.agentId} did not return a sessionId from session/new`);return}if(n.onWorkerSpawned?.(d,r.pid),n.modelId){let g=Td(l);if(g.size===0||g.has(n.modelId))try{await r.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 f=[];r.connection.onNotification("session/update",g=>{let m=Pd(g);m.length>0&&f.push(m)}),await r.connection.request("session/prompt",{sessionId:d,prompt:[{type:"text",text:e}]});let p=f.join(""),c=t(p);if(!c){let g=JSON.stringify(p.slice(0,200));n.logger?.warn(`synopsis: agent ${n.agentId} reply did not parse (replyLen=${p.length} preview=${g})`);let m=p.slice(0,120).replace(/\s+/g," ").trim();n.onFailure?.(`agent ${n.agentId} returned unparseable JSON (${p.length} chars): ${m}${p.length>120?"\u2026":""}`)}return c})();return await new Promise((u,l)=>{o=setTimeout(()=>{i=!0,n.logger?.warn(`synopsis: agent ${n.agentId} timed out after ${s}ms`),n.onFailure?.(`agent ${n.agentId} timed out after ${s}ms`),u(void 0)},s),o.unref?.(),a.then(d=>{o&&clearTimeout(o),i||u(d)},d=>{o&&clearTimeout(o),i||l(d)})})}catch(a){let u=a.message;n.logger?.warn(`synopsis: agent ${n.agentId} failed: ${u}`),n.onFailure?.(`agent ${n.agentId} failed: ${u}`);return}finally{o&&clearTimeout(o),r&&await r.kill().catch(()=>{})}}async function qt(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp title-regen worker for session ${n.sessionId}]`:"[hydra-acp title-regen worker]",s=e.length>0?`${t}
|
|
100
100
|
|
|
101
101
|
${e}
|
|
102
102
|
|
|
103
103
|
${Vn}`:`${t}
|
|
104
104
|
|
|
105
|
-
${Vn}`;return Qr(n,s,Lr)}async function Vr(n){let e=
|
|
105
|
+
${Vn}`;return Qr(n,s,Lr)}async function Vr(n){let e=ze(n.history,{maxChars:n.maxTranscriptChars}),t=n.sessionId!==void 0?`[hydra-acp compaction worker for session ${n.sessionId}]`:"[hydra-acp compaction worker]",s=e.length>0?`${t}
|
|
106
106
|
|
|
107
107
|
${e}
|
|
108
108
|
|
|
109
109
|
${Kn}`:`${t}
|
|
110
110
|
|
|
111
|
-
${Kn}`;return Qr(n,s,qr)}function Rd(n){if(!n||typeof n!="object")return"";let e=n.update;if(!e||typeof e!="object")return"";let t=e;if(t.sessionUpdate!=="agent_message_chunk")return"";let s=t.content;return s&&typeof s.text=="string"?s.text:""}function Ed(n){let e=new Set;Wr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Wr(e,t.availableModels),e}function Wr(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function Pd(n){let e=new Map;for(let t of Zr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Yr(n){return Pd(n).map(e=>e.name)}function Td(n){let e=new Map;for(let t of Zr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Xr(n){return Td(n).map(e=>e.path)}function Zr(n){let e=new Map,t=0;for(let s of n){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let c=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,u=e.get(c);u===void 0?(u={toolName:Kr(o),paths:new Set},e.set(c,u)):u.toolName=Kr(o);for(let d of Gr(o.rawInput,o.locations))u.paths.add(d);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let c of Gr(o.rawInput,o.locations))a.paths.add(c)}return e}function Kr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Gr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var _d=2,zt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??_d}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let c=s==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,u=await this.opts.registry.getAgent(c);if(!u){this.opts.logger?.warn(`synopsis: agent ${c} not in registry for session ${e}; skipping`);return}let d=await te(u,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,l=S.sessionDir(e);if(await so.mkdir(l,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${c} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${l}`),s==="compaction"){let m=this.opts.compactionMaxIterations??3,g=0,h=a??0,v,y=0,w,b=Date.now(),A={targetAgentId:r},x=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),C=T=>{this.opts.broadcastHydraCompaction?.(e,T,A)};await x({status:"requested",requestedAt:b}),C({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{g++,this.opts.logger?.info(`synopsis: compaction iteration ${g} sessionId=${e} historyLen=${i.length} watermark=${h}`);let T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await Vr({agentId:c,cwd:l,plan:d,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{x({status:"running",requestedAt:b,iter:g,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=eo(_.synopsis,T);$&&to($)&&(await this.opts.persistSynopsis(e,$,T.length),v=$,y=T.length,w=void 0,await x({status:"running",requestedAt:b,iter:g}),C({sessionUpdate:"hydra_compaction",phase:"iteration",iter:g,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,y,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${g} fields=${no($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${g} returned no result`);if(h=T.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(g<m);if(v)g>=m&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${g}`);else{g>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${m} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let T=w??(g===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${g} iteration(s)`);await x({status:"failed",requestedAt:b,iter:g,lastError:T}),C({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await x({status:"failed",requestedAt:b,iter:g,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let m=await qt({agentId:c,cwd:l,plan:d,history:i,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!m){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let g=eo(m.synopsis,i);g&&to(g)?(await this.opts.persistSynopsis(e,g,i.length),m.title&&await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!m.title)} fields=${no(g)}`)):m.title&&(await this.opts.persistTitle(e,m.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function eo(n,e){let t=Xr(e),s=Yr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function to(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function no(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Z from"fs/promises";function ro(n){return n==="summary"?"summary":"inline"}var ns=256;function oo(n,e){return e!=="summary"?n:n.map($d)}function $d(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(io));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,c={};a.error!==void 0&&(c.error=ss(a.error)),a.metadata!==void 0&&(c.metadata=a.metadata),o.rawOutput=c}return{...n,params:{...t,update:o}}}function Fd(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function io(n){if(Fd(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=ss(e.text)),typeof e.content=="string"?t.content=ss(e.content):e.content&&typeof e.content=="object"&&(t.content=io(e.content)),t}function ss(n){if(typeof n=="string"&&n.length>ns){let e=n.length-ns;return`${n.slice(0,ns)}\u2026[+${e} chars omitted from summary export]`}return n}var Od=2048;function ao(n){let e=new Set,t=s=>{if(co(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function co(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function Hd(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function is(n,e){if(!Hd(n))return n;let t=n.params,s=t.update,r=await rs(s,e);return{...n,params:{...t,update:r}}}async function rs(n,e){if(typeof n=="string"){if(n.length<=Od)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await rs(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await rs(r,e);return t}return n}async function uo(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await os(t,e);return s===t?n:{...n,params:s}}async function os(n,e){if(co(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let o=await os(r,e);o!==r&&(t=!0),s.push(o)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,o]of Object.entries(n)){let i=await os(o,e);i!==o&&(t=!0),s[r]=i}return t?s:n}return n}var mt=/^[A-Za-z0-9_-]+$/,Nd=1e3,Jt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Nd}async append(e,t){if(mt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(S.sessionDir(e),{recursive:!0});let s=await is(t,o=>Cn(e,o)),r=JSON.stringify(s)+`
|
|
112
|
-
`;await Z.appendFile(
|
|
111
|
+
${Kn}`;return Qr(n,s,qr)}function Pd(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 Td(n){let e=new Set;Wr(e,n.availableModels);let t=n.models;return t&&typeof t=="object"&&!Array.isArray(t)&&Wr(e,t.availableModels),e}function Wr(n,e){if(Array.isArray(e)){for(let t of e)if(t&&typeof t=="object"){let s=t.modelId??t.value??t.id;typeof s=="string"&&s.length>0&&n.add(s)}}}function _d(n){let e=new Map;for(let t of Zr(n).values())e.set(t.toolName,(e.get(t.toolName)??0)+1);return[...e.entries()].map(([t,s])=>({name:t,count:s})).sort((t,s)=>s.count-t.count||t.name.localeCompare(s.name))}function Yr(n){return _d(n).map(e=>e.name)}function $d(n){let e=new Map;for(let t of Zr(n).values())for(let s of t.paths){let r=e.get(s);r===void 0&&(r=new Map,e.set(s,r)),r.set(t.toolName,(r.get(t.toolName)??0)+1)}return[...e.entries()].map(([t,s])=>{let r=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count||i.name.localeCompare(a.name)),o=r.reduce((i,a)=>i+a.count,0);return{path:t,count:o,byTool:r}}).sort((t,s)=>s.count-t.count||t.path.localeCompare(s.path))}function Xr(n){return $d(n).map(e=>e.path)}function Zr(n){let e=new Map,t=0;for(let s of n){let o=s.params?.update;if(!o)continue;let i=o.sessionUpdate;if(i!=="tool_call"&&i!=="tool_call_update")continue;if(i==="tool_call"){let u=typeof o.toolCallId=="string"&&o.toolCallId.length>0?o.toolCallId:`__synth_${t++}`,l=e.get(u);l===void 0?(l={toolName:Kr(o),paths:new Set},e.set(u,l)):l.toolName=Kr(o);for(let d of Gr(o.rawInput,o.locations))l.paths.add(d);continue}if(typeof o.toolCallId!="string"||o.toolCallId.length===0)continue;let a=e.get(o.toolCallId);if(a!==void 0)for(let u of Gr(o.rawInput,o.locations))a.paths.add(u)}return e}function Kr(n){return typeof n.name=="string"&&n.name.length>0?n.name:typeof n.title=="string"&&n.title.length>0?n.title:"(unnamed)"}function Gr(n,e){let t=new Set;if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;typeof s.file_path=="string"?t.add(s.file_path):typeof s.path=="string"&&t.add(s.path);let r=s.edits;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let i=o.file_path;typeof i=="string"&&t.add(i)}}}if(Array.isArray(e)){for(let s of e)if(s&&typeof s=="object"){let r=s.path;typeof r=="string"&&t.add(r)}}return t}var Fd=2,zt=class{constructor(e){this.opts=e;this.maxConcurrent=e.maxConcurrent??Fd}opts;queued={};inflight=new Map;stopped=!1;maxConcurrent;schedule(e){this.stopped||this.inflight.has(e)||e in this.queued||(this.queued[e]={kind:"title"},this.drain())}scheduleCompaction(e,t){if(this.stopped)return;let s=t?.targetAgentId;if(this.inflight.has(e))return;let r=this.queued[e];if(r&&r.kind==="title"){this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}};return}this.queued[e]={kind:"compaction",...s?{targetAgentId:s}:{}},this.drain()}size(){return{queued:Object.keys(this.queued).length,inflight:this.inflight.size}}async flush(e){let t=Date.now()+e;for(;Object.keys(this.queued).length>0||this.inflight.size>0;){let s=t-Date.now();if(s<=0)return;let r=[...this.inflight.values()];if(r.length===0){await new Promise(o=>{setTimeout(o,25).unref?.()});continue}await Promise.race([Promise.race(r),new Promise(o=>{setTimeout(o,s).unref?.()})])}}async shutdown(){this.stopped=!0,this.queued={},await Promise.allSettled([...this.inflight.values()])}drain(){if(!this.stopped)for(;this.inflight.size<this.maxConcurrent&&Object.keys(this.queued).length>0;){let t=Object.keys(this.queued)[0];if(!t)return;let s=this.queued[t];delete this.queued[t];let r=this.runOne(t,s).finally(()=>{this.inflight.delete(t),this.drain()});this.inflight.set(t,r)}}async runOne(e,t){let s=t.kind,r=t.targetAgentId;try{let o=await this.opts.store.read(e);if(!o){this.opts.logger?.info(`synopsis: session ${e} record missing; skipping`);return}let i=await this.opts.histories.load(e,{maxEntries:1/0}),a=o.summarizedThroughEntry;if(a!==void 0&&i.length===a){this.opts.logger?.info(`synopsis: skip ${e} (history unchanged at ${i.length})`);return}a!==void 0&&i.length<a&&this.opts.logger?.warn(`synopsis: watermark ahead of history (last=${a} history=${i.length}) for ${e} \u2014 re-baselining`);let u=s==="compaction"?r??this.opts.compactionAgent??o.agentId:this.opts.synopsisAgent??o.agentId,l=await this.opts.registry.getAgent(u);if(!l){this.opts.logger?.warn(`synopsis: agent ${u} not in registry for session ${e}; skipping`);return}let d=await te(l,[],{npmRegistry:this.opts.npmRegistry}),f=this.opts.compactionAgent===void 0&&r===void 0,p=s==="compaction"?this.opts.compactionModel??(f?o.currentModel:void 0):this.opts.synopsisModel,c=k.sessionDir(e);if(await so.mkdir(c,{recursive:!0}).catch(()=>{}),this.opts.logger?.info(`synopsis: start sessionId=${e} agentId=${u} historyLen=${i.length} model=${JSON.stringify(p??"(default)")} cwd=${c}`),s==="compaction"){let g=this.opts.compactionMaxIterations??3,m=0,h=a??0,v,y=0,w,b=Date.now(),A={targetAgentId:r},x=T=>this.opts.onCompactionStateChange?.(e,T,A)??Promise.resolve(),C=T=>{this.opts.broadcastHydraCompaction?.(e,T,A)};await x({status:"requested",requestedAt:b}),C({sessionUpdate:"hydra_compaction",phase:"started",requestedAt:b});try{do{m++,this.opts.logger?.info(`synopsis: compaction iteration ${m} sessionId=${e} historyLen=${i.length} watermark=${h}`);let T=await this.opts.histories.load(e,{maxEntries:1/0});if(T.length===h)break;let _=await Vr({agentId:u,cwd:c,plan:d,history:T,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs,onWorkerSpawned:($,P)=>{x({status:"running",requestedAt:b,iter:m,worker:{upstreamSessionId:$,pid:P??0}})},onFailure:$=>{w=$}});if(_){let $=eo(_.synopsis,T);$&&to($)&&(await this.opts.persistSynopsis(e,$,T.length),v=$,y=T.length,w=void 0,await x({status:"running",requestedAt:b,iter:m}),C({sessionUpdate:"hydra_compaction",phase:"iteration",iter:m,historyLen:T.length}),await this.opts.onSynthesisArtifact?.(e,$,y,r),this.opts.logger?.info(`synopsis: persisted compaction sessionId=${e} iteration=${m} fields=${no($)}`))}else this.opts.logger?.warn(`synopsis: sessionId=${e} compaction iteration ${m} returned no result`);if(h=T.length,(await this.opts.histories.load(e,{maxEntries:1/0})).length===h)break}while(m<g);if(v)m>=g&&this.opts.logger?.info(`synopsis: compaction converged sessionId=${e} watermark=${y} iterations=${m}`);else{m>0&&this.opts.logger?.warn(`synopsis: compaction hit maxIterations=${g} without producing artifact sessionId=${e}: ${w??"no reason captured"}`);let T=w??(m===0?"no new history to compact since last summary":`compaction did not produce an artifact after ${m} iteration(s)`);await x({status:"failed",requestedAt:b,iter:m,lastError:T}),C({sessionUpdate:"hydra_compaction",phase:"failed",error:T})}}catch(T){let _=T instanceof Error?T.message:String(T);this.opts.logger?.warn(`synopsis: compaction threw for sessionId=${e}: ${_}`),await x({status:"failed",requestedAt:b,iter:m,lastError:_}),this.opts.broadcastHydraCompaction?.(e,{sessionUpdate:"hydra_compaction",phase:"failed",error:_},{targetAgentId:r})}}else{let g=await qt({agentId:u,cwd:c,plan:d,history:i,modelId:p,sessionId:e,logger:this.opts.logger,timeoutMs:this.opts.generateTimeoutMs});if(!g){this.opts.logger?.warn(`synopsis: sessionId=${e} no parseable result; not persisting`);return}let m=eo(g.synopsis,i);m&&to(m)?(await this.opts.persistSynopsis(e,m,i.length),g.title&&await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted sessionId=${e} title=${JSON.stringify(!!g.title)} fields=${no(m)}`)):g.title&&(await this.opts.persistTitle(e,g.title),this.opts.logger?.info(`synopsis: persisted title only sessionId=${e}`))}}catch(o){this.opts.logger?.warn(`synopsis: sessionId=${e} failed: ${o.message}`)}}};function eo(n,e){let t=Xr(e),s=Yr(e);return n?{...n,files_touched:t.length>0?t:n.files_touched,tools_used:s.length>0?s:n.tools_used}:t.length===0&&s.length===0?void 0:{files_touched:t.length>0?t:void 0,tools_used:s.length>0?s:void 0}}function to(n){return!!(n.goal&&n.goal.trim().length>0||n.outcome&&n.outcome.trim().length>0||n.files_touched&&n.files_touched.length>0||n.tools_used&&n.tools_used.length>0||n.rejected_approaches&&n.rejected_approaches.length>0||n.open_threads&&n.open_threads.length>0)}function no(n){let e=[];return n.goal&&e.push("goal"),n.outcome&&e.push("outcome"),n.files_touched&&n.files_touched.length>0&&e.push(`files=${n.files_touched.length}`),n.tools_used&&n.tools_used.length>0&&e.push(`tools=${n.tools_used.length}`),n.rejected_approaches&&n.rejected_approaches.length>0&&e.push(`rejected=${n.rejected_approaches.length}`),n.open_threads&&n.open_threads.length>0&&e.push(`open=${n.open_threads.length}`),`[${e.join(",")}]`}import*as Z from"fs/promises";function ro(n){return n==="summary"?"summary":"inline"}var ns=256;function oo(n,e){return e!=="summary"?n:n.map(Od)}function Od(n){if(n.method!=="session/update")return n;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return n;let t=e,s=t.update;if(!s||typeof s!="object"||Array.isArray(s))return n;let r=s;if(r.sessionUpdate!=="tool_call"&&r.sessionUpdate!=="tool_call_update")return n;let o={...r};Array.isArray(r.content)&&(o.content=r.content.map(io));let i=r.rawOutput;if(i&&typeof i=="object"&&!Array.isArray(i)){let a=i,u={};a.error!==void 0&&(u.error=ss(a.error)),a.metadata!==void 0&&(u.metadata=a.metadata),o.rawOutput=u}return{...n,params:{...t,update:o}}}function Hd(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="diff"}function io(n){if(Hd(n)){let s=n,r={type:"diff",oldText:"",newText:""};return typeof s.path=="string"&&(r.path=s.path),r}if(!n||typeof n!="object"||Array.isArray(n))return n;let e=n,t={...e};return typeof e.text=="string"&&(t.text=ss(e.text)),typeof e.content=="string"?t.content=ss(e.content):e.content&&typeof e.content=="object"&&(t.content=io(e.content)),t}function ss(n){if(typeof n=="string"&&n.length>ns){let e=n.length-ns;return`${n.slice(0,ns)}\u2026[+${e} chars omitted from summary export]`}return n}var Nd=2048;function ao(n){let e=new Set,t=s=>{if(co(s)){e.add(s.__hydraBlob);return}if(Array.isArray(s)){for(let r of s)t(r);return}if(s&&typeof s=="object")for(let r of Object.values(s))t(r)};for(let s of n)t(s.params);return e}function co(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.__hydraBlob=="string"}function jd(n){if(n.method!=="session/update")return!1;let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return!1;let s=t.sessionUpdate;return s==="tool_call"||s==="tool_call_update"}async function is(n,e){if(!jd(n))return n;let t=n.params,s=t.update,r=await rs(s,e);return{...n,params:{...t,update:r}}}async function rs(n,e){if(typeof n=="string"){if(n.length<=Nd)return n;let t=await e(n);return t===null?n:{__hydraBlob:t,bytes:n.length}}if(Array.isArray(n)){let t=[];for(let s of n)t.push(await rs(s,e));return t}if(n&&typeof n=="object"){let t={};for(let[s,r]of Object.entries(n))t[s]=await rs(r,e);return t}return n}async function uo(n,e){let t=n.params;if(!t||typeof t!="object"||Array.isArray(t))return n;let s=await os(t,e);return s===t?n:{...n,params:s}}async function os(n,e){if(co(n))return await e(n.__hydraBlob)??"";if(Array.isArray(n)){let t=!1,s=[];for(let r of n){let o=await os(r,e);o!==r&&(t=!0),s.push(o)}return t?s:n}if(n&&typeof n=="object"){let t=!1,s={};for(let[r,o]of Object.entries(n)){let i=await os(o,e);i!==o&&(t=!0),s[r]=i}return t?s:n}return n}var gt=/^[A-Za-z0-9_-]+$/,Bd=1e3,Jt=class{writeQueues=new Map;maxEntries;constructor(e={}){this.maxEntries=e.maxEntries??Bd}async append(e,t){if(gt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(k.sessionDir(e),{recursive:!0});let s=await is(t,o=>Cn(e,o)),r=JSON.stringify(s)+`
|
|
112
|
+
`;await Z.appendFile(k.historyFile(e),r,{encoding:"utf8",mode:384})})}async rewrite(e,t){if(gt.test(e))return this.enqueue(e,async()=>{await Z.mkdir(k.sessionDir(e),{recursive:!0});let s=[];for(let o of t)s.push(await is(o,i=>Cn(e,i)));let r=s.length===0?"":s.map(o=>JSON.stringify(o)).join(`
|
|
113
113
|
`)+`
|
|
114
|
-
`;await Z.writeFile(
|
|
115
|
-
`).filter(i=>i.length>0);if(r.length<=t)return;let o=r.slice(-t);await Z.writeFile(
|
|
114
|
+
`;await Z.writeFile(k.historyFile(e),r,{encoding:"utf8",mode:384})})}async compact(e,t){if(gt.test(e))return this.enqueue(e,async()=>{let s;try{s=await Z.readFile(k.historyFile(e),"utf8")}catch(i){if(i.code==="ENOENT")return;throw i}let r=s.split(`
|
|
115
|
+
`).filter(i=>i.length>0);if(r.length<=t)return;let o=r.slice(-t);await Z.writeFile(k.historyFile(e),o.join(`
|
|
116
116
|
`)+`
|
|
117
|
-
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!
|
|
118
|
-
`)){if(p.length===0)continue;let
|
|
117
|
+
`,{encoding:"utf8",mode:384})})}async load(e,t={}){if(!gt.test(e))return[];let s=(t.tools??"inline")==="inline",r=this.writeQueues.get(e);r&&await r;let o;try{o=await Z.readFile(k.historyFile(e),"utf8")}catch(p){if(p.code==="ENOENT")return[];throw p}let i=[];for(let p of o.split(`
|
|
118
|
+
`)){if(p.length===0)continue;let c;try{c=JSON.parse(p)}catch{continue}if(!c||typeof c!="object"||Array.isArray(c))continue;let g=c;typeof g.method=="string"&&typeof g.recordedAt=="number"&&i.push({method:g.method,params:g.params,recordedAt:g.recordedAt})}let a=t.maxEntries??this.maxEntries,u=i.length>a?i.slice(-a):i;if(!s)return u;let l=new Map,d=async p=>{let c=l.get(p);if(c!==void 0)return c;let g=await _t(e,p);return l.set(p,g),g},f=[];for(let p of u)f.push(await uo(p,d));return f}async flushAll(){let e=[...this.writeQueues.values()];e.length!==0&&await Promise.allSettled(e)}async delete(e){if(gt.test(e))return this.enqueue(e,async()=>{try{await Z.unlink(k.historyFile(e))}catch(t){if(t.code!=="ENOENT")throw t}await Ks(e);try{await Z.rmdir(k.sessionDir(e))}catch(t){let s=t;if(s.code!=="ENOENT"&&s.code!=="ENOTEMPTY")throw t}})}enqueue(e,t){let r=(this.writeQueues.get(e)??Promise.resolve()).then(t,t),o=r.catch(()=>{});return this.writeQueues.set(e,o),o.finally(()=>{this.writeQueues.get(e)===o&&this.writeQueues.delete(e)}),r}};import{promises as lo}from"fs";import*as fo from"path";async function po(n,e){await lo.mkdir(fo.dirname(n),{recursive:!0});let t=e.map(s=>JSON.stringify(s));await lo.writeFile(n,t.length>0?t.join(`
|
|
119
119
|
`)+`
|
|
120
|
-
`:"")}import{z as D}from"zod";var jd=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),Bd=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:lt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:Zn.optional(),agentCommands:D.array(Yn).optional(),agentModes:D.array(Xn).optional(),interactive:D.boolean().optional(),originatingClient:es.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),Ud=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:Bd,history:D.array(jd),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.string()).optional()});function gt(n){let e={version:1,exportedAt:new Date().toISOString(),exportedFrom:{hydraVersion:n.hydraVersion,machine:n.machine,...n.hydraHost!==void 0&&n.hydraHost.length>0?{hydraHost:n.hydraHost}:{}},session:{sessionId:n.record.sessionId,lineageId:n.record.lineageId,...n.record.upstreamSessionId?{upstreamSessionId:n.record.upstreamSessionId}:{},agentId:n.record.agentId,cwd:n.record.cwd,...n.record.title!==void 0?{title:n.record.title}:{},...n.record.synopsis!==void 0?{synopsis:n.record.synopsis}:{},...n.record.summarizedThroughEntry!==void 0?{summarizedThroughEntry:n.record.summarizedThroughEntry}:{},...n.record.currentModel!==void 0?{currentModel:n.record.currentModel}:{},...n.record.currentMode!==void 0?{currentMode:n.record.currentMode}:{},...n.record.currentUsage!==void 0?{currentUsage:n.record.currentUsage}:{},...n.record.agentCommands!==void 0?{agentCommands:n.record.agentCommands}:{},...n.record.agentModes!==void 0?{agentModes:n.record.agentModes}:{},...n.record.interactive!==void 0?{interactive:n.record.interactive}:{},...n.record.originatingClient!==void 0?{originatingClient:n.record.originatingClient}:{},...n.record.priority!==void 0&&n.record.priority>0?{priority:n.record.priority}:{},createdAt:n.record.createdAt,updatedAt:n.record.updatedAt},history:n.history};return n.promptHistory!==void 0&&(e.promptHistory=n.promptHistory),n.toolBlobs!==void 0&&Object.keys(n.toolBlobs).length>0&&(e.toolBlobs=n.toolBlobs),e}function mo(n){return Ud.parse(n)}var go=900*1e3,Ld="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=Dd(Ld,16),vt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>he.spawn(a)),this.store=s??new Bt,this.tombstones=r.tombstones??new Ut,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Jt({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new zt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,c)=>{let u=this.get(a);if(u){await u.retitle(c);return}await this.persistTitle(a,c)},persistSynopsis:(a,c,u)=>this.persistSynopsis(a,c,u),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,c,u)=>{if(u.targetAgentId)return;let d=this.get(a);d&&(d.compactionState=c),await this.mutateRecord(a,{compactionState:c})},broadcastHydraCompaction:(a,c,u)=>{this.emitSwapPhase(a,u.targetAgentId,c)},onSynthesisArtifact:async(a,c,u,d)=>{await this.dispatchSynthesisSwap(a,c,u,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let o=this.get(e);if(!o){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let i=this.compactionTailK;try{if(await o.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(o,t,i,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let c=o.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,c)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let c=await this.store.read(e).catch(()=>{});c?.synopsis&&c.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,c.synopsis,c.summarizedThroughEntry,c.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,s,o.summarizedThroughEntry,i)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,o){try{let i=o?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:i,summarizedThroughEntry:r,...o?{newAgentId:o}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await je(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let o={...s.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let a=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Wt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:o});a.action==="stop"&&a.payload&&(o=a.payload)}catch{}s.agentCapabilities=o}let r=new Pe({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:o=>this.bootstrapAgent({...o,mcpServers:o.mcpServers??[]}),loadExistingAgentSession:(o,i)=>this.bootstrapAgentLoad(o,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:o=>this.scheduleCompaction(r.sessionId,o),resolveAgentId:async o=>(await this.registry.getAgent(o))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:o=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:o}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=I.AlreadyAttached,o}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let g=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw g.code=I.AgentNotInstalled,g}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await te(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),i;try{let g=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}});i=g.agentCapabilities,o.authMethods=ht(g.authMethods)}catch(g){throw await o.kill().catch(()=>{}),Ce(g,o)}let a;try{let g=ho(e.agentId,e.currentModel);a=await o.connection.request("session/load",{sessionId:e.upstreamSessionId,cwd:e.cwd,mcpServers:e.mcpServers??[],...g&&{_meta:g}})}catch(g){if(g&&typeof g=="object"&&g.code===I.AuthRequired)throw await o.kill().catch(()=>{}),Ce(g,o);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${g.message}); recovering via import-reseed
|
|
121
|
-
`),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=ls(a??{}),u=e.agentModes??ds(us(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(c)} advertisedModes=${JSON.stringify(u?.map(g=>g.id))}`);let d=await Ue({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:c,advertisedModes:u,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(d)} for sessionId=${e.hydraSessionId}`);let f=as(a??{}),p=ds(cs(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(p?.map(g=>g.modelId))}`),e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let l=await De({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let g=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain3 (post-model-restore) dropped ${g} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let m=new Pe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:g=>this.bootstrapAgent({...g,mcpServers:g.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(g,h)=>this.bootstrapAgentLoad(g,{...h,mcpServers:h.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:l,currentMode:d,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:u,agentModels:p,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(m.sessionId),scheduleCompaction:g=>this.scheduleCompaction(m.sessionId,g),resolveAgentId:async g=>(await this.registry.getAgent(g))?.id,getCompactionState:()=>this.getCompactionState(m.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(m.sessionId),uncompactHook:()=>this.performUncompact(m.sessionId),onCompactionSwapHook:g=>{this.mutateRecord(m.sessionId,{rollbackBreadcrumb:g}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(m.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(m),m}async doResurrectFromImport(e){let t=await this.resolveResurrectCwd(e.cwd),s=await this.bootstrapAgent({agentId:e.agentId,cwd:t,agentArgs:e.agentArgs,mcpServers:e.mcpServers??[],onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv,model:e.currentModel}),r=e.agentModes??s.initialModes,o=await Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await De({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let c=new Pe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:u=>this.bootstrapAgent({...u,mcpServers:u.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(u,d)=>this.bootstrapAgentLoad(u,{...d,mcpServers:d.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(c.sessionId),scheduleCompaction:u=>this.scheduleCompaction(c.sessionId,u),resolveAgentId:async u=>(await this.registry.getAgent(u))?.id,getCompactionState:()=>this.getCompactionState(c.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(c.sessionId),uncompactHook:()=>this.performUncompact(c.sessionId),onCompactionSwapHook:u=>{this.mutateRecord(c.sessionId,{rollbackBreadcrumb:u}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(c.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(c),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${c.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?c.seedFromFork(e.synopsis).catch(()=>{}):c.seedFromImport().catch(()=>{}),c}async dirExists(e){try{return(await Te.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Y(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let l=new Error(`agent ${e} not found in registry`);throw l.code=I.AgentNotInstalled,l}let s=await te(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Qt.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}})}catch(l){throw await r.kill().catch(()=>{}),Ce(l,r)}if(r.authMethods=ht(o.authMethods),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(l){throw await r.kill().catch(()=>{}),l}await r.kill().catch(()=>{});let c=new Set;for(let l of this.sessions.values())c.add(`${l.agentId}::${l.upstreamSessionId}`);let u=await this.store.list().catch(()=>[]);for(let l of u)c.add(`${l.agentId}::${l.upstreamSessionId}`);let d=S.sessionsDir(),f=[],p=0;for(let l of a){let m=`${e}::${l.sessionId}`;if(c.has(m)){p+=1;continue}if(qd(l.cwd,d)){p+=1;continue}let g=await this.tombstones.read(e,l.sessionId).catch(()=>{});if(g){if(!Jr(g,l.updatedAt)){p+=1;continue}await this.tombstones.remove(e,l.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${l.sessionId} (upstream updatedAt advanced past ${g.upstreamUpdatedAt??"<unset>"})`)}c.add(m);let h=`${ye}${Wt()}`,v=new Date().toISOString(),y=l.updatedAt??v,w={sessionId:h,lineageId:ft(),upstreamSessionId:l.sessionId,agentId:e,cwd:l.cwd,pendingHistorySync:!0,interactive:!0,createdAt:y,updatedAt:y};l.title!==void 0&&(w.title=l.title);let b=ts(w);await this.store.write(b),f.push({version:1,...b})}return{synced:f,skipped:p}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let o=0;o<100;o+=1){let i={};s!==void 0&&(i.cursor=s);let a=await e.connection.request("session/list",i),c=Array.isArray(a.sessions)?a.sessions:[];for(let u of c){if(typeof u.sessionId!="string"||typeof u.cwd!="string")continue;let d={sessionId:u.sessionId,cwd:u.cwd};typeof u.title=="string"&&(d.title=u.title),typeof u.updatedAt=="string"&&(d.updatedAt=u.updatedAt),t.push(d)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=I.AgentNotInstalled,o}let s=await te(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}}),i=o.agentCapabilities;r.authMethods=ht(o.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),c=a.sessionId;if(typeof c!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let u=as(a),d=cs(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==u){let m=ze(f,d),g=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(m.kind==="exact"||m.kind==="none")await this.applySeedModel(r,c,f,g)&&(u=f);else if(m.kind==="resolved")(m.modelId===u||await this.applySeedModel(r,c,m.modelId,`${g} resolved to ${JSON.stringify(m.modelId)}`))&&(u=m.modelId);else if(m.kind==="ambiguous")this.logger?.warn(`${g} is ambiguous (trailing-segment matches [${m.candidates.join(", ")}]); skipping session/set_model, session will use ${JSON.stringify(u)}`);else{let h=d.map(v=>v.modelId).join(", ");this.logger?.warn(`${g} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(u)}`)}}let p=us(a),l=ls(a);return{agent:r,upstreamSessionId:c,agentMeta:a._meta,agentCapabilities:i,initialModel:u,initialModels:d.length>0?d:void 0,initialModes:p.length>0?p:void 0,initialMode:l}}catch(o){throw await r.kill().catch(()=>{}),Ce(wo(o,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let i=new Error(`agent ${t.agentId} not found in registry`);throw i.code=I.AgentNotInstalled,i}let r=await te(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=ht(i.authMethods);let c=ho(t.agentId,void 0),u=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...c&&{_meta:c}}),d=as(u),f=ds(cs(u)),p=us(u),l=ls(u);return{agent:o,upstreamSessionId:e,agentMeta:u._meta,agentCapabilities:a,initialModel:d,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:l}}catch(i){throw await o.kill().catch(()=>{}),Ce(wo(i,o,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),o)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=s.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let c=new Error(`agent ${e} not found in registry`);throw c.code=I.AgentNotInstalled,c}let o=await te(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let c=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:Be,clientInfo:{name:"hydra",version:K}});a.authMethods=ht(c.authMethods)}catch(c){throw await a.kill().catch(()=>{}),Ce(c,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=I.AgentNotInstalled,s}return te(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Ye({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:bo(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=zd(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return _t(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Jd(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=We(r.update.prompt),i=Qn(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ye))return;let t=ye+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=I.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await yt(t.sessionId),c=Ye({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),u=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:c,priority:t.priority,updatedAt:u,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await yt(s.sessionId),o=Ye(s,r.hasContent),i=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:o,priority:s.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=d=>e.includeNonInteractive?!0:d===!0,o=[...this.sessions.values()].filter(d=>!e.cwd||d.cwd===e.cwd),i=await Promise.all(o.map(d=>yt(d.sessionId)));for(let d=0;d<o.length;d+=1){let f=o[d],p=i[d];s.add(f.sessionId);let l=Ye({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(l))continue;let m=p.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let c=(await this.store.list().catch(d=>{throw this.logger?.warn(`session list: store.list() failed: ${d?.message??String(d)}`),d})).filter(d=>!s.has(d.sessionId)&&(!e.cwd||d.cwd===e.cwd)),u=await Promise.all(c.map(d=>yt(d.sessionId)));for(let d=0;d<c.length;d+=1){let f=c[d],p=u[d],l=Ye(f,p.hasContent);if(!r(l))continue;let m=p.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:l,priority:f.priority,updatedAt:m,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((d,f)=>d.updatedAt<f.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let u=ft(),d={...s,lineageId:u};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:u}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await vo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let c={};for(let u of ao(i)){let d=await Qs(e,u);d&&(c[u]=d.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:c}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=I.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=I.SessionNotFound,w}let r=t.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=I.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,c,u=t.mode??"synthesis",d,f,p,l=12e4;if(u==="verbatim")if(t.forkAt!==void 0){let w=Wn(i,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=I.InvalidParams,b}c=t.forkAt,a=i.slice(0,w+1)}else{let w=Qd(i);w?(c=w.messageId,a=i.slice(0,w.index+1)):(c="",a=i.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),c="",a=i;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=I.AgentNotInstalled,b}p=w,f=s.currentModel,d="running"}let m=await vo(e),g=u==="synthesis",h={...s,lineageId:ft(),agentId:r,interactive:!1,...d!==void 0?{forkSynthesisState:d}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},v=gt({record:h,history:a,promptHistory:m.length>0?m:void 0,hydraVersion:K,machine:Qt.hostname()}),y=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:y,bundle:v,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:c,...d!==void 0?{forkSynthesisState:d}:{}}),g&&(async()=>{try{let w=await te(p,[],{npmRegistry:this.npmRegistry}),b=await qt({agentId:r,cwd:t.cwd??S.sessionDir(e),plan:w,history:i,modelId:f,sessionId:e,logger:this.logger,timeoutMs:l});b&&b.synopsis?await this.mutateRecord(y,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:y,forkedFromSessionId:e,forkedAt:c}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await Vs(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(S.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await po(S.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await yt(e),o=Ye(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...o!==void 0?{interactive:o}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,...t,updatedAt:new Date().toISOString()};for(let i of s)delete o[i];await this.store.write(o)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[s]:r},c=Buffer.byteLength(JSON.stringify(a),"utf8");if(c>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${c} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let u={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(u)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(s in i))return;delete i[s],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let o=s.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(s.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Er(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(c=>r-c.enqueuedAt<go),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${go/1e3}s)`),await ct(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await ct(t.sessionId,[]).catch(()=>{});continue}try{let c=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),c.replayPersistedQueue(o)}catch(c){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${c.message}`)}}}};function qd(n,e){if(typeof n!="string"||n.length===0)return!1;let t=wt.resolve(n),s=wt.resolve(e);return t===s||t.startsWith(s+wt.sep)}function zd(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(d=>d.description!==void 0?{name:d.name,description:d.description}:{name:d.name}):void 0)??e?.agentCommands,r=n.availableModes(),i=(r.length>0?r.map(d=>{let f={id:d.id};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModes,a=n.availableModels(),u=(a.length>0?a.map(d=>{let f={modelId:d.modelId};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModels;return ts({sessionId:n.sessionId,lineageId:e?.lineageId??ft(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:bo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:u,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function bo(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Jd(n){return n?{...n}:void 0}function ho(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Vt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let i=e.fromObject(s);if(i!==void 0)return i}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let c=e.fromObject(a);if(c!==void 0)return c}}let o=Wd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function as(n){return Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>ge(e.currentModelId)??ge(e.currentModel)??ge(e.modelId)??ge(e.model),fromConfig:e=>ge(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==I.AuthRequired)return n;let s=u=>!!u&&typeof u=="object"&&!Array.isArray(u),r=s(t.data)?t.data:{},o=s(r._meta)?r._meta:{},i=s(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",c=new Error(a);return c.code=I.AuthRequired,c.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},c}function yo(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function wo(n,e,t,s){if(n&&typeof n=="object"&&n.code===I.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=s?`to reproduce: (cd ${yo(s.cwd)} && ${[s.command,...s.args].map(yo).join(" ")})`:"";if(!i&&!a)return n;let c=[o?r:`agent ${t} failed to start: ${r}`];i&&c.push(`stderr: ${i}`),a&&c.push(a);let u=new Error(c.join(`
|
|
122
|
-
`));if(n&&typeof n=="object"){let d=n;typeof d.code=="number"&&(
|
|
123
|
-
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function yt(n){try{let e=await Te.stat(
|
|
124
|
-
`);let
|
|
125
|
-
`),a.end();return}let p=Y(d),
|
|
126
|
-
`),a.end(),this.scheduleRestart(e,t);return}let
|
|
120
|
+
`:"")}import{z as D}from"zod";var Ud=D.object({method:D.string(),params:D.unknown(),recordedAt:D.number()}),Dd=D.object({sessionId:D.string(),lineageId:D.string(),upstreamSessionId:D.string().optional(),agentId:D.string(),cwd:D.string(),title:D.string().optional(),synopsis:lt.optional(),summarizedThroughEntry:D.number().int().nonnegative().optional(),currentModel:D.string().optional(),currentMode:D.string().optional(),currentUsage:Zn.optional(),agentCommands:D.array(Yn).optional(),agentModes:D.array(Xn).optional(),interactive:D.boolean().optional(),originatingClient:es.optional(),priority:D.number().int().nonnegative().optional(),createdAt:D.string(),updatedAt:D.string()}),Ld=D.object({version:D.literal(1),exportedAt:D.string(),exportedFrom:D.object({hydraVersion:D.string(),machine:D.string(),hydraHost:D.string().optional()}),session:Dd,history:D.array(Ud),promptHistory:D.array(D.string()).optional(),toolBlobs:D.record(D.string()).optional()});function mt(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 go(n){return Ld.parse(n)}var mo=900*1e3,zd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Wt=qd(zd,16),vt=class n{constructor(e,t,s,r={}){this.registry=e;this.spawner=t??(a=>he.spawn(a)),this.store=s??new Bt,this.tombstones=r.tombstones??new Ut,this.sessionHistoryMaxEntries=r.sessionHistoryMaxEntries??1e3,this.histories=new Jt({maxEntries:this.sessionHistoryMaxEntries}),this.idleTimeoutMs=r.idleTimeoutMs??0,this.idleEventTimeoutMs=r.idleEventTimeoutMs??3e4,this.defaultModels=r.defaultModels??{},this.synopsisAgent=r.synopsisAgent,this.synopsisModel=r.synopsisModel,this.compactionAgent=r.compactionAgent,this.compactionModel=r.compactionModel,this.defaultTransformers=r.defaultTransformers??[],this.logger=r.logger,this.npmRegistry=r.npmRegistry,this.extensionCommands=r.extensionCommands,this.defaultCwd=r.defaultCwd??"~";let o=r.compaction??{},i=o.tailK??20;this.compactionTailK=i,this.synopsisCoordinator=new zt({registry:this.registry,store:this.store,histories:this.histories,synopsisAgent:this.synopsisAgent,synopsisModel:this.synopsisModel,compactionAgent:this.compactionAgent,compactionModel:this.compactionModel,compactionMaxIterations:o.maxIterations,persistTitle:async(a,u)=>{let l=this.get(a);if(l){await l.retitle(u);return}await this.persistTitle(a,u)},persistSynopsis:(a,u,l)=>this.persistSynopsis(a,u,l),logger:this.logger,npmRegistry:this.npmRegistry,onCompactionStateChange:async(a,u,l)=>{if(l.targetAgentId)return;let d=this.get(a);d&&(d.compactionState=u),await this.mutateRecord(a,{compactionState:u})},broadcastHydraCompaction:(a,u,l)=>{this.emitSwapPhase(a,l.targetAgentId,u)},onSynthesisArtifact:async(a,u,l,d)=>{await this.dispatchSynthesisSwap(a,u,l,d)}}),this.refreshAgentCatalog()}registry;sessions=new Map;resurrectionInflight=new Map;pendingAuthAgents=new Map;spawner;store;tombstones;histories;idleTimeoutMs;defaultModels;synopsisAgent;synopsisModel;compactionAgent;compactionModel;defaultTransformers;idleEventTimeoutMs;sessionHistoryMaxEntries;metaWriteQueues=new Map;listCache=new Map;static LIST_CACHE_TTL_MS=500;logger;npmRegistry;extensionCommands;defaultCwd;synopsisCoordinator;pendingDeletions=new Map;pendingSwapDisposers=new Map;rollbackLocks=new Set;compactionTailK=20;agentCatalog=[];async dispatchSynthesisSwap(e,t,s,r){let o=this.get(e);if(!o){this.logger?.info(`compaction: persisted artifact for cold session sessionId=${e}`),await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s});return}let i=this.compactionTailK;try{if(await o.isQuiescedForSwap()){this.pendingSwapDisposers.get(e)?.(),this.pendingSwapDisposers.delete(e),await this.performSynthesisSwap(o,t,i,s,r);return}this.pendingSwapDisposers.get(e)?.(),this.logger?.info(`compaction: session not quiesced, parking onceIdle swap sessionId=${e}`),this.emitSwapPhase(e,r,{phase:"deferred"});let u=o.onceIdle(()=>{this.pendingSwapDisposers.delete(e),this.onIdleAttemptSwap(e)});this.pendingSwapDisposers.set(e,u)}catch(a){this.logger?.warn(`compaction: dispatch failed for sessionId=${e}: ${a instanceof Error?a.message:String(a)}, leaving session as-is`)}}async onIdleAttemptSwap(e){let t=this.get(e);if(!t)return;let s=this.compactionTailK;try{if(!await t.isQuiescedForSwap()){let u=await this.store.read(e).catch(()=>{});u?.synopsis&&u.summarizedThroughEntry!==void 0&&this.dispatchSynthesisSwap(e,u.synopsis,u.summarizedThroughEntry,u.pendingAgentSwap);return}let o=await this.store.read(e).catch(()=>{});if(!o?.synopsis||o.summarizedThroughEntry===void 0){this.logger?.warn(`compaction: persisted artifact missing for sessionId=${e}, abandoning swap`),t.compactionState=void 0,await this.mutateRecord(e,{},["compactionState"]);return}let i=o.pendingAgentSwap,a=await this.histories.load(e).catch(()=>[]);if(a.length>o.summarizedThroughEntry){this.logger?.info(`compaction: history grew during deferral (have=${a.length} artifact=${o.summarizedThroughEntry}), rescheduling synopsis sessionId=${e}`),i?this.synopsisCoordinator.scheduleCompaction(e,{targetAgentId:i}):this.synopsisCoordinator.scheduleCompaction(e);return}await this.performSynthesisSwap(t,o.synopsis,s,o.summarizedThroughEntry,i)}catch(r){this.logger?.warn(`compaction: onIdleAttemptSwap failed for sessionId=${e}: ${r instanceof Error?r.message:String(r)}`)}}async performSynthesisSwap(e,t,s,r,o){try{let i=o?Math.min(5,s):0;await e.swapUpstream({artifact:t,tailK:s,tailFloor:i,summarizedThroughEntry:r,...o?{newAgentId:o}:{}}),o?await this.mutateRecord(e.sessionId,{},["pendingAgentSwap"]):(e.compactionState=void 0,await this.mutateRecord(e.sessionId,{},["compactionState"]))}catch(i){this.logger?.warn(`compaction: swap failed for sessionId=${e.sessionId}: ${i instanceof Error?i.message:String(i)}, leaving session as-is`)}}async refreshAgentCatalog(){try{let{agents:e}=await Ne(this.registry);this.agentCatalog=e.map(t=>({id:t.id,name:t.name,...t.description!==void 0?{description:t.description}:{}}))}catch{}}async create(e){let t=await this.registry.getAgent(e.agentId);t&&t.id!==e.agentId&&(e={...e,agentId:t.id});let s=await this.bootstrapAgent({agentId:e.agentId,cwd:e.cwd,agentArgs:e.agentArgs,mcpServers:e.mcpServers,model:e.model,onInstallProgress:e.onInstallProgress,forwardedEnv:e.forwardedEnv});if(e.transformChain&&e.transformChain.length>0){let o={...s.agentCapabilities??{}};for(let i of e.transformChain)if(i.intercepts.has("agent:initialize"))try{let a=await i.connection.request("hydra-acp/transformer/message",{token:`t_${Wt()}`,phase:"response",method:"initialize",direction:"agent\u2192daemon",sessionId:"(pre-session)",envelope:o});a.action==="stop"&&a.payload&&(o=a.payload)}catch{}s.agentCapabilities=o}let r=new Pe({cwd:e.cwd,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,idleEventTimeoutMs:this.idleEventTimeoutMs,logger:this.logger,spawnReplacementAgent:o=>this.bootstrapAgent({...o,mcpServers:o.mcpServers??[]}),loadExistingAgentSession:(o,i)=>this.bootstrapAgentLoad(o,{...i,mcpServers:i.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:s.initialModel,currentMode:s.initialMode,agentModes:s.initialModes,agentModels:s.initialModels,transformChain:e.transformChain,parentSessionId:e.parentSessionId,originatingClient:e.originatingClient,interactive:e.interactive,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(r.sessionId),scheduleCompaction:o=>this.scheduleCompaction(r.sessionId,o),resolveAgentId:async o=>(await this.registry.getAgent(o))?.id,getCompactionState:()=>this.getCompactionState(r.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(r.sessionId),uncompactHook:()=>this.performUncompact(r.sessionId),onCompactionSwapHook:o=>{this.mutateRecord(r.sessionId,{rollbackBreadcrumb:o}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(r.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(r),r}async resurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t){if(t.upstreamSessionId!==e.upstreamSessionId){let o=new Error(`session ${e.hydraSessionId} already exists with a different upstream id`);throw o.code=S.AlreadyAttached,o}return t}let s=this.resurrectionInflight.get(e.hydraSessionId);if(s)return s;let r=this.doResurrect(e);this.resurrectionInflight.set(e.hydraSessionId,r);try{return await r}finally{this.resurrectionInflight.delete(e.hydraSessionId)}}async doResurrect(e){let t=this.sessions.get(e.hydraSessionId);if(t)return t;let s=await this.registry.getAgent(e.agentId);if(!s){let m=new Error(`agent ${e.agentId} not found in registry; cannot resurrect`);throw m.code=S.AgentNotInstalled,m}if(e.upstreamSessionId==="")return this.doResurrectFromImport(e);if(!await this.dirExists(e.cwd))return this.doResurrectFromImport(e);let r=await te(s,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),o=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:r,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}}),i;try{let m=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});i=m.agentCapabilities,o.authMethods=ht(m.authMethods)}catch(m){throw await o.kill().catch(()=>{}),Ce(m,o)}let a;try{let m=ho(e.agentId,e.currentModel);a=await o.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===S.AuthRequired)throw await o.kill().catch(()=>{}),Ce(m,o);return process.stderr.write(`session/load failed for upstream ${e.upstreamSessionId} on ${e.agentId} (${m.message}); recovering via import-reseed
|
|
121
|
+
`),await o.kill().catch(()=>{}),this.doResurrectFromImport(e)}if(e.pendingHistorySync===!0)this.clearPendingHistorySync(e.hydraSessionId).catch(()=>{});else{let m=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain1 dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let u=ls(a??{}),l=e.agentModes??ds(us(a??{}));this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedMode=${JSON.stringify(e.currentMode)} agentReportedMode=${JSON.stringify(u)} advertisedModes=${JSON.stringify(l?.map(m=>m.id))}`);let d=await Be({agent:o,upstreamSessionId:e.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:u,advertisedModes:l,logger:this.logger});this.logger?.info(`resurrect: effectiveMode=${JSON.stringify(d)} for sessionId=${e.hydraSessionId}`);let f=as(a??{}),p=ds(cs(a??{}))??e.agentModels;if(this.logger?.info(`resurrect: sessionId=${e.hydraSessionId} persistedModel=${JSON.stringify(e.currentModel)} agentReportedModel=${JSON.stringify(f)} advertisedModels=${JSON.stringify(p?.map(m=>m.modelId))}`),e.pendingHistorySync!==!0){let m=o.connection.drainBuffered("session/update");this.logger?.info(`resurrect: drain2 (post-mode-restore) dropped ${m} buffered session/update(s) for sessionId=${e.hydraSessionId}`)}let c=await Ue({agent:o,upstreamSessionId:e.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:f,logger:this.logger});if(e.pendingHistorySync!==!0){let m=o.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 Pe({sessionId:e.hydraSessionId,cwd:e.cwd,agentId:e.agentId,agent:o,upstreamSessionId:e.upstreamSessionId,agentMeta:a?._meta,agentCapabilities:i,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:m=>this.bootstrapAgent({...m,mcpServers:m.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(m,h)=>this.bootstrapAgentLoad(m,{...h,mcpServers:h.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:c,currentMode:d,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:l,agentModels:p,summarizedThroughEntry:e.summarizedThroughEntry,compactionState:e.compactionState,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(g.sessionId),scheduleCompaction:m=>this.scheduleCompaction(g.sessionId,m),resolveAgentId:async m=>(await this.registry.getAgent(m))?.id,getCompactionState:()=>this.getCompactionState(g.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(g.sessionId),uncompactHook:()=>this.performUncompact(g.sessionId),onCompactionSwapHook:m=>{this.mutateRecord(g.sessionId,{rollbackBreadcrumb:m}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(g.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});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,o=await Be({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedMode:e.currentMode,agentReportedMode:s.initialMode,advertisedModes:r,logger:this.logger}),i=e.agentModels??s.initialModels,a=await Ue({agent:s.agent,upstreamSessionId:s.upstreamSessionId,persistedModel:e.currentModel,agentReportedModel:s.initialModel,logger:this.logger});s.agent.connection.drainBuffered("session/update");let u=new Pe({sessionId:e.hydraSessionId,cwd:t,agentId:e.agentId,agent:s.agent,upstreamSessionId:s.upstreamSessionId,agentMeta:s.agentMeta,agentCapabilities:s.agentCapabilities,title:e.title,agentArgs:e.agentArgs,idleTimeoutMs:this.idleTimeoutMs,logger:this.logger,spawnReplacementAgent:l=>this.bootstrapAgent({...l,mcpServers:l.mcpServers??e.mcpServers??[]}),loadExistingAgentSession:(l,d)=>this.bootstrapAgentLoad(l,{...d,mcpServers:d.mcpServers??e.mcpServers??[]}),...e.mintMcpServersForSwap?{mintMcpServersForSwap:e.mintMcpServersForSwap}:{},listSessions:()=>this.list(),availableAgents:()=>this.agentCatalog,historyStore:this.histories,historyMaxEntries:this.sessionHistoryMaxEntries,currentModel:a,currentMode:o,currentUsage:e.currentUsage,agentCommands:e.agentCommands,agentModes:r,agentModels:i,summarizedThroughEntry:e.summarizedThroughEntry,firstPromptSeeded:!!e.title,createdAt:e.createdAt?new Date(e.createdAt).getTime():void 0,originatingClient:e.originatingClient,interactive:e.interactive,priority:e.priority,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forwardedEnv:e.forwardedEnv,mcpServers:e.mcpServers??[],extensionCommands:this.extensionCommands,attentionFlags:e.attentionFlags,scheduleSynopsis:()=>this.synopsisCoordinator.schedule(u.sessionId),scheduleCompaction:l=>this.scheduleCompaction(u.sessionId,l),resolveAgentId:async l=>(await this.registry.getAgent(l))?.id,getCompactionState:()=>this.getCompactionState(u.sessionId),getPendingAgentSwap:()=>this.getPendingAgentSwap(u.sessionId),uncompactHook:()=>this.performUncompact(u.sessionId),onCompactionSwapHook:l=>{this.mutateRecord(u.sessionId,{rollbackBreadcrumb:l}).catch(()=>{})},clearRollbackBreadcrumbHook:()=>{this.mutateRecord(u.sessionId,{},["rollbackBreadcrumb"]).catch(()=>{})}});return await this.attachManagerHooks(u),e.forkedFromSessionId&&e.forkSynthesisState==="running"?this.logger?.info(`fork ${u.sessionId}: synthesis in flight \u2014 skipping seed, recall available`):e.forkedFromSessionId&&(e.synopsis||(e.summarizedThroughEntry??0)>0)?u.seedFromFork(e.synopsis).catch(()=>{}):u.seedFromImport().catch(()=>{}),u}async dirExists(e){try{return(await Te.stat(e)).isDirectory()}catch{return!1}}async reapIfOrphanedNonInteractive(e){let t=this.sessions.get(e);!t||t.attachedCount>0||t.interactive!==!0&&(this.logger?.info(`reaping orphaned non-interactive session ${e} (agent killed, cold record kept)`),await t.close({deleteRecord:!1}).catch(()=>{}))}async resolveResurrectCwd(e){return await this.dirExists(e)?e:Y(this.defaultCwd)}async syncFromAgent(e){let t=await this.registry.getAgent(e);if(!t){let c=new Error(`agent ${e} not found in registry`);throw c.code=S.AgentNotInstalled,c}let s=await te(t,[],{npmRegistry:this.npmRegistry}),r=this.spawner({agentId:e,cwd:Qt.homedir(),plan:s}),o;try{o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}})}catch(c){throw await r.kill().catch(()=>{}),Ce(c,r)}if(r.authMethods=ht(o.authMethods),(o.agentCapabilities??{}).sessionCapabilities?.list===void 0)throw await r.kill().catch(()=>{}),new Error(`agent ${e} does not advertise sessionCapabilities.list; cannot sync`);let a;try{a=await this.collectAgentSessions(r)}catch(c){throw await r.kill().catch(()=>{}),c}await r.kill().catch(()=>{});let u=new Set;for(let c of this.sessions.values())u.add(`${c.agentId}::${c.upstreamSessionId}`);let l=await this.store.list().catch(()=>[]);for(let c of l)u.add(`${c.agentId}::${c.upstreamSessionId}`);let d=k.sessionsDir(),f=[],p=0;for(let c of a){let g=`${e}::${c.sessionId}`;if(u.has(g)){p+=1;continue}if(Jd(c.cwd,d)){p+=1;continue}let m=await this.tombstones.read(e,c.sessionId).catch(()=>{});if(m){if(!Jr(m,c.updatedAt)){p+=1;continue}await this.tombstones.remove(e,c.sessionId).catch(()=>{}),this.logger?.info(`syncFromAgent: resurrecting tombstoned ${e}/${c.sessionId} (upstream updatedAt advanced past ${m.upstreamUpdatedAt??"<unset>"})`)}u.add(g);let h=`${ye}${Wt()}`,v=new Date().toISOString(),y=c.updatedAt??v,w={sessionId:h,lineageId:ft(),upstreamSessionId:c.sessionId,agentId:e,cwd:c.cwd,pendingHistorySync:!0,interactive:!0,createdAt:y,updatedAt:y};c.title!==void 0&&(w.title=c.title);let b=ts(w);await this.store.write(b),f.push({version:1,...b})}return{synced:f,skipped:p}}async collectAgentSessions(e){let t=[],s,r=new Set;for(let o=0;o<100;o+=1){let i={};s!==void 0&&(i.cursor=s);let a=await e.connection.request("session/list",i),u=Array.isArray(a.sessions)?a.sessions:[];for(let l of u){if(typeof l.sessionId!="string"||typeof l.cwd!="string")continue;let d={sessionId:l.sessionId,cwd:l.cwd};typeof l.title=="string"&&(d.title=l.title),typeof l.updatedAt=="string"&&(d.updatedAt=l.updatedAt),t.push(d)}if(typeof a.nextCursor!="string"||a.nextCursor.length===0||r.has(a.nextCursor))break;r.add(a.nextCursor),s=a.nextCursor}return t}async applySeedModel(e,t,s,r){try{return await e.connection.request("session/set_model",{sessionId:t,modelId:s}),this.logger?.info(`${r}: session/set_model accepted`),!0}catch(o){return this.logger?.warn(`${r} rejected by agent (${o.message}); session will use the agent's own default`),!1}}async bootstrapAgent(e){let t=await this.registry.getAgent(e.agentId);if(!t){let o=new Error(`agent ${e.agentId} not found in registry`);throw o.code=S.AgentNotInstalled,o}let s=await te(t,e.agentArgs??[],{npmRegistry:this.npmRegistry,onInstallProgress:e.onInstallProgress}),r=this.spawner({agentId:e.agentId,cwd:e.cwd,plan:s,...e.forwardedEnv?{extraEnv:e.forwardedEnv}:{}});try{let o=await r.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),i=o.agentCapabilities;r.authMethods=ht(o.authMethods);let a=await r.connection.request("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]}),u=a.sessionId;if(typeof u!="string")throw new Error(`agent ${e.agentId} returned a non-string sessionId from session/new`);let l=as(a),d=cs(a),f=e.model??this.defaultModels[e.agentId];if(f&&f!==l){let g=qe(f,d),m=e.model!==void 0?`model=${JSON.stringify(f)}`:`defaultModels[${e.agentId}]=${JSON.stringify(f)}`;if(g.kind==="exact"||g.kind==="none")await this.applySeedModel(r,u,f,m)&&(l=f);else if(g.kind==="resolved")(g.modelId===l||await this.applySeedModel(r,u,g.modelId,`${m} resolved to ${JSON.stringify(g.modelId)}`))&&(l=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(l)}`);else{let h=d.map(v=>v.modelId).join(", ");this.logger?.warn(`${m} not in agent's availableModels ([${h}]); skipping session/set_model, session will use ${JSON.stringify(l)}`)}}let p=us(a),c=ls(a);return{agent:r,upstreamSessionId:u,agentMeta:a._meta,agentCapabilities:i,initialModel:l,initialModels:d.length>0?d:void 0,initialModes:p.length>0?p:void 0,initialMode:c}}catch(o){throw await r.kill().catch(()=>{}),Ce(wo(o,r,e.agentId,{command:s.command,args:s.args,cwd:e.cwd}),r)}}async bootstrapAgentLoad(e,t){let s=await this.registry.getAgent(t.agentId);if(!s){let i=new Error(`agent ${t.agentId} not found in registry`);throw i.code=S.AgentNotInstalled,i}let r=await te(s,t.agentArgs??[],{npmRegistry:this.npmRegistry}),o=this.spawner({agentId:t.agentId,cwd:t.cwd,plan:r,...t.forwardedEnv?{extraEnv:t.forwardedEnv}:{}});try{let i=await o.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}}),a=i.agentCapabilities;o.authMethods=ht(i.authMethods);let u=ho(t.agentId,void 0),l=await o.connection.request("session/load",{sessionId:e,cwd:t.cwd,mcpServers:t.mcpServers??[],...u&&{_meta:u}}),d=as(l),f=ds(cs(l)),p=us(l),c=ls(l);return{agent:o,upstreamSessionId:e,agentMeta:l._meta,agentCapabilities:a,initialModel:d,initialModels:f,initialModes:p.length>0?p:void 0,initialMode:c}}catch(i){throw await o.kill().catch(()=>{}),Ce(wo(i,o,t.agentId,{command:r.command,args:r.args,cwd:t.cwd}),o)}}async performUncompact(e){if(this.rollbackLocks.has(e))throw new Error("a rollback is already in progress for this session");let t=this.get(e);if(!t)throw new Error("session is not live \u2014 cannot roll back a cold session");let s=await this.store.read(e);if(!s)throw new Error("session record not found");let r=s.rollbackBreadcrumb;if(!r)throw new Error("no rollback breadcrumb found \u2014 either the session has not been compacted, the rollback window has closed (a new turn was dispatched), or a previous rollback already consumed the breadcrumb");let o=s.compactionState;if(o!=null)throw new Error(`compaction is in progress (status: ${o.status}) \u2014 wait for it to complete before rolling back`);if(!await t.isQuiescedForSwap())throw new Error("session is not quiesced for rollback \u2014 wait for in-flight work to complete");this.rollbackLocks.add(e);try{await t.rollbackToUpstream({previousUpstreamSessionId:r.previousUpstreamSessionId,previousSummarizedThroughEntry:r.previousSummarizedThroughEntry}),await this.mutateRecord(e,{summarizedThroughEntry:r.previousSummarizedThroughEntry},["synopsis","rollbackBreadcrumb"])}finally{this.rollbackLocks.delete(e)}}async bootstrapAgentForAuth(e,t){let s=this.pendingAuthAgents.get(e);if(s&&s.isAlive())return s;let r=await this.registry.getAgent(e);if(!r){let u=new Error(`agent ${e} not found in registry`);throw u.code=S.AgentNotInstalled,u}let o=await te(r,[],{npmRegistry:this.npmRegistry}),i=t??Y(this.defaultCwd),a=this.spawner({agentId:e,cwd:i,plan:o});try{let u=await a.connection.request("initialize",{protocolVersion:1,clientCapabilities:je,clientInfo:{name:"hydra",version:K}});a.authMethods=ht(u.authMethods)}catch(u){throw await a.kill().catch(()=>{}),Ce(u,a)}return this.pendingAuthAgents.set(e,a),a.onExit(()=>{this.pendingAuthAgents.get(e)===a&&this.pendingAuthAgents.delete(e)}),a}async planSpawnForAgent(e){let t=await this.registry.getAgent(e);if(!t){let s=new Error(`agent ${e} not found in registry`);throw s.code=S.AgentNotInstalled,s}return te(t,[],{npmRegistry:this.npmRegistry})}consumePendingAuthAgent(e){let t=this.pendingAuthAgents.get(e);if(t&&(this.pendingAuthAgents.delete(e),!!t.isAlive()))return t}getAgentForSession(e){return this.sessions.get(e)?.agent}async attachManagerHooks(e){e.onClose(({deleteRecord:t})=>{if(this.sessions.delete(e.sessionId),this.invalidateListCache(),t){if(e.upstreamSessionId){let r=Ge({interactive:e.interactive,...e.originatingClient?{originatingClient:e.originatingClient}:{}},!0),o=this.tombstones.add({agentId:e.agentId,upstreamSessionId:e.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:new Date(e.updatedAt).toISOString(),cwd:e.cwd,title:e.title,reason:"user",...r!==void 0?{interactive:r}:{}}).catch(()=>{}).then(()=>this.store.delete(e.sessionId).catch(()=>{})).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===o&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,o);return}let s=this.store.delete(e.sessionId).catch(()=>{}).then(()=>this.histories.delete(e.sessionId).catch(()=>{})).finally(()=>{this.pendingDeletions.get(e.sessionId)===s&&this.pendingDeletions.delete(e.sessionId)});this.pendingDeletions.set(e.sessionId,s);return}}),e.onTitleChange(t=>{this.persistTitle(e.sessionId,t).catch(()=>{})}),e.onPriorityChange(t=>{this.persistPriority(e.sessionId,t).catch(()=>{})}),e.onAgentChange(({agentId:t,upstreamSessionId:s})=>{this.persistAgentChange(e.sessionId,t,s).catch(()=>{})}),e.onModelChange(t=>{this.persistSnapshot(e.sessionId,{currentModel:t}).catch(()=>{})}),e.onModeChange(t=>{this.persistSnapshot(e.sessionId,{currentMode:t}).catch(()=>{})}),e.onInteractiveChange(t=>{this.persistSnapshot(e.sessionId,{interactive:t}).catch(()=>{})}),e.onUsageChange(t=>{this.persistSnapshot(e.sessionId,{currentUsage:bo(t)}).catch(()=>{})}),e.onAgentCommandsChange(t=>{this.persistSnapshot(e.sessionId,{agentCommands:t.map(s=>({name:s.name,...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModesChange(t=>{this.persistSnapshot(e.sessionId,{agentModes:t.map(s=>({id:s.id,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAgentModelsChange(t=>{this.persistSnapshot(e.sessionId,{agentModels:t.map(s=>({modelId:s.modelId,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{}}))}).catch(()=>{})}),e.onAttentionFlagsChange(t=>{this.mutateRecord(e.sessionId,{attentionFlags:t}).catch(()=>{})}),this.sessions.set(e.sessionId,e),this.invalidateListCache(),await this.enqueueMetaWrite(e.sessionId,async()=>{let t=await this.store.read(e.sessionId),s=Wd(e,t);await this.store.write(s)}).catch(()=>{})}async getHistory(e){if(this.sessions.has(e))return this.histories.load(e).catch(()=>[]);if(await this.store.read(e))return this.histories.load(e).catch(()=>[])}async loadHistory(e){return this.histories.load(e)}async loadToolBlob(e,t){return _t(e,t)}async loadFromDisk(e){let t=await this.store.read(e);if(!t)return;let s=t.title;return s||(s=await this.deriveTitleFromHistory(e)),{hydraSessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,agentId:t.agentId,cwd:t.cwd,title:s,synopsis:t.synopsis,summarizedThroughEntry:t.summarizedThroughEntry,agentArgs:t.agentArgs,currentModel:t.currentModel,currentMode:t.currentMode,currentUsage:Qd(t.currentUsage?{...t.currentUsage,cumulativeCost:(t.currentUsage.cumulativeCost??0)+(t.currentUsage.costAmount??0),costAmount:void 0}:void 0),agentCommands:t.agentCommands,agentModes:t.agentModes,agentModels:t.agentModels,createdAt:t.createdAt,pendingHistorySync:t.pendingHistorySync,originatingClient:t.originatingClient,interactive:t.interactive,priority:t.priority,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,forwardedEnv:t.forwardedEnv,compactionState:t.compactionState,attentionFlags:t.attentionFlags?.filter(r=>!(r.source==="daemon"&&r.reason.startsWith("permission:")))}}async setForwardedEnv(e,t){if(t===void 0)return;let s=this.sessions.get(e);s&&(s.forwardedEnv=t),await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,forwardedEnv:t};await this.store.write(o)})}async clearPendingHistorySync(e){await this.enqueueMetaWrite(e,async()=>{let t=await this.store.read(e);if(!t||t.pendingHistorySync!==!0)return;let s={...t};delete s.pendingHistorySync,await this.store.write(s)})}async deriveTitleFromHistory(e){let t=await this.histories.load(e).catch(()=>[]);for(let s of t){let r=s.params;if(r?.update?.sessionUpdate!=="prompt_received")continue;let o=Je(r.update.prompt),i=Qn(o,200);if(i)return i}}get(e){return this.sessions.get(e)}liveSessions(){return this.sessions.values()}activeAgentVersions(){let e=new Map;for(let t of this.sessions.values()){let s=t.agent.agentId,r=t.agent.version,o=e.get(s);o||(o=new Set,e.set(s,o)),o.add(r)}return e}async resolveCanonicalId(e){if(this.sessions.has(e)||await this.store.read(e))return e;if(e.startsWith(ye))return;let t=ye+e;if(this.sessions.has(t)||await this.store.read(t))return t}require(e){let t=this.sessions.get(e);if(!t){let s=new Error(`session ${e} not found`);throw s.code=S.SessionNotFound,s}return t}liveListEntry(e){return{sessionId:e.sessionId,upstreamSessionId:e.upstreamSessionId,cwd:e.cwd,title:e.title,agentId:e.agentId,currentModel:e.currentModel,currentUsage:e.currentUsage,parentSessionId:e.parentSessionId,forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId,forkSynthesisState:e.forkSynthesisState,originatingClient:e.originatingClient,interactive:e.interactive,updatedAt:new Date(e.updatedAt).toISOString(),attachedClients:e.attachedCount,status:"warm",busy:e.turnStartedAt!==void 0,awaitingInput:e.awaitingInput}}async getOne(e){let t=this.sessions.get(e);if(t){let a=await yt(t.sessionId),u=Ge({interactive:t.interactive,...t.originatingClient?{originatingClient:t.originatingClient}:{}},a.hasContent),l=a.mtime??new Date(t.updatedAt).toISOString();return{sessionId:t.sessionId,upstreamSessionId:t.upstreamSessionId,cwd:t.cwd,title:t.title,agentId:t.agentId,currentModel:t.currentModel,currentUsage:t.currentUsage,parentSessionId:t.parentSessionId,forkedFromSessionId:t.forkedFromSessionId,forkedFromMessageId:t.forkedFromMessageId,forkSynthesisState:t.forkSynthesisState,originatingClient:t.originatingClient,interactive:u,priority:t.priority,updatedAt:l,attachedClients:t.attachedCount,status:"warm",busy:t.turnStartedAt!==void 0,awaitingInput:t.awaitingInput}}let s=await this.store.read(e).catch(()=>{});if(!s)return;let r=await yt(s.sessionId),o=Ge(s,r.hasContent),i=r.mtime??s.updatedAt;return{sessionId:s.sessionId,upstreamSessionId:s.upstreamSessionId,cwd:s.cwd,title:s.title,agentId:s.agentId,currentModel:s.currentModel,currentUsage:s.currentUsage?{...s.currentUsage,costAmount:(s.currentUsage.cumulativeCost??0)+(s.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:s.importedFromMachine,importedFromUpstreamSessionId:s.importedFromUpstreamSessionId,parentSessionId:s.parentSessionId,forkedFromSessionId:s.forkedFromSessionId,forkedFromMessageId:s.forkedFromMessageId,forkSynthesisState:s.forkSynthesisState,originatingClient:s.originatingClient,interactive:o,priority:s.priority,updatedAt:i,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1}}async list(e={}){let t=`${e.cwd??""}|${e.includeNonInteractive?"1":"0"}`,s=Date.now(),r=this.listCache.get(t);if(r&&r.expiresAt>s)return r.promise;let o=this.listUncached(e);return this.listCache.set(t,{expiresAt:s+n.LIST_CACHE_TTL_MS,promise:o}),o.catch(()=>{let i=this.listCache.get(t);i&&i.promise===o&&this.listCache.delete(t)}),o}invalidateListCache(){this.listCache.clear()}async listUncached(e={}){let t=[],s=new Set,r=d=>e.includeNonInteractive?!0:d===!0,o=[...this.sessions.values()].filter(d=>!e.cwd||d.cwd===e.cwd),i=await Promise.all(o.map(d=>yt(d.sessionId)));for(let d=0;d<o.length;d+=1){let f=o[d],p=i[d];s.add(f.sessionId);let c=Ge({interactive:f.interactive,...f.originatingClient?{originatingClient:f.originatingClient}:{}},p.hasContent);if(!r(c))continue;let g=p.mtime??new Date(f.updatedAt).toISOString();t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:c,priority:f.priority,updatedAt:g,attachedClients:f.attachedCount,status:"warm",busy:f.turnStartedAt!==void 0,awaitingInput:f.awaitingInput,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}let u=(await this.store.list().catch(d=>{throw this.logger?.warn(`session list: store.list() failed: ${d?.message??String(d)}`),d})).filter(d=>!s.has(d.sessionId)&&(!e.cwd||d.cwd===e.cwd)),l=await Promise.all(u.map(d=>yt(d.sessionId)));for(let d=0;d<u.length;d+=1){let f=u[d],p=l[d],c=Ge(f,p.hasContent);if(!r(c))continue;let g=p.mtime??f.updatedAt;t.push({sessionId:f.sessionId,upstreamSessionId:f.upstreamSessionId,cwd:f.cwd,title:f.title,agentId:f.agentId,currentModel:f.currentModel,currentUsage:f.currentUsage?{...f.currentUsage,costAmount:(f.currentUsage.cumulativeCost??0)+(f.currentUsage.costAmount??0)||void 0}:void 0,importedFromMachine:f.importedFromMachine,importedFromUpstreamSessionId:f.importedFromUpstreamSessionId,parentSessionId:f.parentSessionId,forkedFromSessionId:f.forkedFromSessionId,forkedFromMessageId:f.forkedFromMessageId,originatingClient:f.originatingClient,interactive:c,priority:f.priority,updatedAt:g,attachedClients:0,status:"cold",busy:!1,awaitingInput:!1,compactionState:f.compactionState,forkSynthesisState:f.forkSynthesisState})}return t.sort((d,f)=>d.updatedAt<f.updatedAt?1:-1),t}async exportBundle(e,t={}){let s=await this.store.read(e);if(!s)return;let r;if(s.lineageId)r=s;else{let l=ft(),d={...s,lineageId:l};await this.enqueueMetaWrite(e,async()=>{let f=await this.store.read(e);f&&(f.lineageId||await this.store.write({...f,lineageId:l}))}).catch(()=>{}),r=d}let o=t.tools??"inline",i=await this.histories.load(e,o==="references"?{tools:"references"}:{}).catch(()=>[]),a=await vo(e);if(o!=="references")return{record:r,history:i,promptHistory:a};let u={};for(let l of ao(i)){let d=await Qs(e,l);d&&(u[l]=d.toString("base64"))}return{record:r,history:i,promptHistory:a,toolBlobs:u}}async importBundle(e,t={}){let s=await this.store.findByLineageId(e.session.lineageId);if(s){if(!t.replace){let i=new Error(`bundle already imported as ${s.sessionId}`);throw i.code=S.BundleAlreadyImported,i.existingSessionId=s.sessionId,i}let o=this.sessions.get(s.sessionId);return o&&await o.close({deleteRecord:!1}).catch(()=>{}),await this.writeImportedRecord({sessionId:s.sessionId,bundle:e,preservedCreatedAt:s.createdAt,cwd:t.cwd}),{sessionId:s.sessionId,importedFromSessionId:e.session.sessionId,replaced:!0}}let r=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:r,bundle:e,cwd:t.cwd}),{sessionId:r,importedFromSessionId:e.session.sessionId,replaced:!1}}async forkSession(e,t={}){let s=await this.store.read(e);if(!s){let w=new Error(`source session not found: ${e}`);throw w.code=S.SessionNotFound,w}let r=t.agentId??s.agentId,o=r!==s.agentId;if(o&&!await this.registry.getAgent(r)){let b=new Error(`agent ${r} not found in registry`);throw b.code=S.AgentNotInstalled,b}let i=await this.histories.load(e).catch(()=>[]),a=i,u,l=t.mode??"synthesis",d,f,p,c=12e4;if(l==="verbatim")if(t.forkAt!==void 0){let w=Wn(i,t.forkAt);if(w<0){let b=new Error(`forkAt messageId not found in source history: ${t.forkAt}`);throw b.code=S.InvalidParams,b}u=t.forkAt,a=i.slice(0,w+1)}else{let w=Kd(i);w?(u=w.messageId,a=i.slice(0,w.index+1)):(u="",a=i.slice(0,0))}else{t.forkAt!==void 0&&this.logger?.warn(`synthesis fork: ignoring forkAt=${t.forkAt} (synthesis covers full history)`),u="",a=i;let w=await this.registry.getAgent(r);if(!w){let b=new Error(`agent ${r} not found in registry`);throw b.code=S.AgentNotInstalled,b}p=w,f=s.currentModel,d="running"}let g=await vo(e),m=l==="synthesis",h={...s,lineageId:ft(),agentId:r,interactive:!1,...d!==void 0?{forkSynthesisState:d}:{},summarizedThroughEntry:a.length,...t.title!==void 0?{title:t.title}:{},currentUsage:void 0,...o?{currentModel:void 0,currentMode:void 0,agentCommands:void 0,agentModes:void 0,agentModels:void 0}:{},...t.model!==void 0?{currentModel:t.model}:{}},v=mt({record:h,history:a,promptHistory:g.length>0?g:void 0,hydraVersion:K,machine:Qt.hostname()}),y=`${ye}${Wt()}`;return await this.writeImportedRecord({sessionId:y,bundle:v,cwd:t.cwd,forkedFromSessionId:e,forkedFromMessageId:u,...d!==void 0?{forkSynthesisState:d}:{}}),m&&(async()=>{try{let w=await te(p,[],{npmRegistry:this.npmRegistry}),b=await qt({agentId:r,cwd:t.cwd??k.sessionDir(e),plan:w,history:i,modelId:f,sessionId:e,logger:this.logger,timeoutMs:c});b&&b.synopsis?await this.mutateRecord(y,{synopsis:b.synopsis},["forkSynthesisState"]):(this.logger?.warn(`forkSession(${e}): generateSynopsis returned no synopsis \u2014 fork usable via recall`),await this.mutateRecord(y,{},["forkSynthesisState"]))}catch(w){this.logger?.warn(`forkSession(${e}): generateSynopsis failed \u2014 fork usable via recall: ${w.message}`);try{await this.mutateRecord(y,{},["forkSynthesisState"])}catch(b){this.logger?.warn(`forkSession(${e}): mutateRecord to clear forkSynthesisState failed: ${b.message}`)}}})(),{sessionId:y,forkedFromSessionId:e,forkedAt:u}}async writeImportedRecord(e){if(await this.histories.rewrite(e.sessionId,e.bundle.history),e.bundle.toolBlobs)for(let[o,i]of Object.entries(e.bundle.toolBlobs))await Vs(e.sessionId,o,Buffer.from(i,"base64")).catch(()=>{});let t=new Date(e.bundle.session.updatedAt);Number.isNaN(t.getTime())||await Te.utimes(k.historyFile(e.sessionId),t,t).catch(()=>{}),e.bundle.promptHistory&&e.bundle.promptHistory.length>0&&await po(k.tuiHistoryFile(e.sessionId),e.bundle.promptHistory).catch(()=>{});let s=new Date().toISOString(),r=e.forkedFromSessionId!==void 0;await this.enqueueMetaWrite(e.sessionId,async()=>{await this.store.write({sessionId:e.sessionId,lineageId:e.bundle.session.lineageId,upstreamSessionId:"",...r?{forkedFromSessionId:e.forkedFromSessionId,forkedFromMessageId:e.forkedFromMessageId}:{importedFromSessionId:e.bundle.session.sessionId,importedFromUpstreamSessionId:e.bundle.session.upstreamSessionId,importedFromMachine:e.bundle.exportedFrom.machine},agentId:e.bundle.session.agentId,cwd:e.cwd??e.bundle.session.cwd,title:e.bundle.session.title,synopsis:e.bundle.session.synopsis,summarizedThroughEntry:e.bundle.session.summarizedThroughEntry,...e.forkSynthesisState!==void 0?{forkSynthesisState:e.forkSynthesisState}:{},currentModel:e.bundle.session.currentModel,currentMode:e.bundle.session.currentMode,currentUsage:e.bundle.session.currentUsage,agentCommands:e.bundle.session.agentCommands,agentModes:e.bundle.session.agentModes,interactive:e.bundle.session.interactive,originatingClient:e.bundle.session.originatingClient,priority:e.bundle.session.priority,attentionFlags:[],createdAt:e.preservedCreatedAt??s,updatedAt:e.bundle.session.updatedAt})})}async deleteRecord(e,t="user"){let s=await this.store.read(e);if(!s)return!1;if(s.upstreamSessionId){let r=await yt(e),o=Ge(s,r.hasContent);await this.tombstones.add({agentId:s.agentId,upstreamSessionId:s.upstreamSessionId,deletedAt:new Date().toISOString(),upstreamUpdatedAt:s.updatedAt,cwd:s.cwd,title:s.title,reason:t,...o!==void 0?{interactive:o}:{}}).catch(()=>{})}return await this.store.delete(e).catch(()=>{}),await this.histories.delete(e).catch(()=>{}),this.invalidateListCache(),!0}async waitForDeletion(e){let t=this.pendingDeletions.get(e);t&&await t}async isTombstoned(e,t){return(await this.tombstones.read(e,t).catch(()=>{}))?.reason==="user"}async hasRecord(e){return await this.store.read(e).catch(()=>{})!==void 0}async setPriority(e,t){let s=this.get(e);if(s)return s.setPriority(t),!0;if(!await this.hasRecord(e))return!1;let r=t===void 0||t<=0?void 0:Math.floor(t);return await this.persistPriority(e,r),!0}async persistPriority(e,t){t===void 0?await this.mutateRecord(e,{},["priority"]):await this.mutateRecord(e,{priority:t}),this.invalidateListCache()}async setTitle(e,t){let s=this.get(e);return s?(await s.retitle(t),!0):await this.hasRecord(e)?(await this.persistTitle(e,t),!0):!1}async persistTitle(e,t){await this.mutateRecord(e,{title:t})}async persistSynopsis(e,t,s){await this.mutateRecord(e,{synopsis:t,summarizedThroughEntry:s})}async persistAgentChange(e,t,s){await this.mutateRecord(e,{agentId:t,upstreamSessionId:s})}async persistSnapshot(e,t){let s={};t.currentModel!==void 0&&(s.currentModel=t.currentModel),t.currentMode!==void 0&&(s.currentMode=t.currentMode),t.currentUsage!==void 0&&(s.currentUsage=t.currentUsage),t.agentCommands!==void 0&&(s.agentCommands=t.agentCommands),t.agentModes!==void 0&&(s.agentModes=t.agentModes),t.agentModels!==void 0&&(s.agentModels=t.agentModels),t.interactive!==void 0&&(s.interactive=t.interactive),t.cwd!==void 0&&(s.cwd=t.cwd),await this.mutateRecord(e,s)}async mutateRecord(e,t,s=[]){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r)return;let o={...r,...t,updatedAt:new Date().toISOString()};for(let i of s)delete o[i];await this.store.write(o)})}static EXTENSION_STATE_CAP_BYTES=64*1024;async getExtensionState(e,t){return(await this.store.read(e))?.extensionState?.[t]??{}}async getExtensionStateKey(e,t,s){return(await this.getExtensionState(e,t))[s]}async setExtensionStateKey(e,t,s,r){await this.enqueueMetaWrite(e,async()=>{let o=await this.store.read(e);if(!o)return;let i={...o.extensionState??{}},a={...i[t]??{},[s]:r},u=Buffer.byteLength(JSON.stringify(a),"utf8");if(u>n.EXTENSION_STATE_CAP_BYTES)throw new Error(`extension_state: bucket for ${t} would be ${u} bytes; cap is ${n.EXTENSION_STATE_CAP_BYTES}`);i[t]=a;let l={...o,extensionState:i,updatedAt:new Date().toISOString()};await this.store.write(l)})}async deleteExtensionStateKey(e,t,s){await this.enqueueMetaWrite(e,async()=>{let r=await this.store.read(e);if(!r?.extensionState?.[t])return;let o={...r.extensionState},i={...o[t]};if(!(s in i))return;delete i[s],Object.keys(i).length===0?delete o[t]:o[t]=i;let a={...r,extensionState:o,updatedAt:new Date().toISOString()};await this.store.write(a)})}enqueueMetaWrite(e,t){let r=(this.metaWriteQueues.get(e)??Promise.resolve()).catch(()=>{}).then(t),o=r.catch(()=>{});return this.metaWriteQueues.set(e,o),o.finally(()=>{this.metaWriteQueues.get(e)===o&&this.metaWriteQueues.delete(e)}),r}async closeAll(){let e=[...this.sessions.values()];await Promise.allSettled(e.map(t=>t.close({deleteRecord:!1}))),this.sessions.clear()}async flushSynopsis(e){await this.synopsisCoordinator.flush(e)}async shutdownSynopsis(){await this.synopsisCoordinator.shutdown()}scheduleSynopsis(e){this.synopsisCoordinator.schedule(e)}scheduleCompaction(e,t){if(t?.targetAgentId){this.mutateRecord(e,{pendingAgentSwap:t.targetAgentId}).catch(r=>{this.logger?.warn(`scheduleCompaction: failed to stamp pendingAgentSwap for ${e}: ${r instanceof Error?r.message:String(r)}`)});let s=t.targetAgentId;(async()=>{try{let r=await this.store.read(e);if(!r?.synopsis||r.summarizedThroughEntry===void 0){this.synopsisCoordinator.scheduleCompaction(e,t);return}if((await this.histories.load(e,{maxEntries:1/0})).length!==r.summarizedThroughEntry){this.synopsisCoordinator.scheduleCompaction(e,t);return}this.logger?.info(`compaction: fast-path swap sessionId=${e} target=${s} (reusing artifact @${r.summarizedThroughEntry})`),await this.dispatchSynthesisSwap(e,r.synopsis,r.summarizedThroughEntry,s)}catch(r){this.logger?.warn(`scheduleCompaction: fast-path check failed for ${e}: ${r instanceof Error?r.message:String(r)} \u2014 falling back to synthesis`),this.synopsisCoordinator.scheduleCompaction(e,t)}})();return}this.synopsisCoordinator.scheduleCompaction(e,t)}getCompactionInFlight(){let e=this.synopsisCoordinator.size();return e.inflight>0||e.queued>0}async getPendingAgentSwap(e){return(await this.store.read(e).catch(()=>{}))?.pendingAgentSwap}async getCompactionState(e){return(await this.store.read(e).catch(()=>{}))?.compactionState}async getRollbackBreadcrumb(e){return(await this.store.read(e).catch(()=>{}))?.rollbackBreadcrumb}emitSwapPhase(e,t,s){let r=this.get(e);if(r){if(t){let o=s.phase==="failed";r.broadcastPendingAgentSwap(o?null:t);return}r.broadcastCompactionPhase(s)}}async getSummarizedThroughEntry(e){let t=this.sessions.get(e);return t?t.summarizedThroughEntry:(await this.store.read(e).catch(()=>{}))?.summarizedThroughEntry}async flushMetaWrites(){let e=[...this.metaWriteQueues.values()];e.length!==0&&await Promise.allSettled(e)}async flushHistoryWrites(){await this.histories.flushAll()}async reconcilePermissionFlags(){let e=await this.store.list().catch(()=>[]),t=0;for(let s of e){let r=s.attentionFlags??[],o=r.filter(i=>!(i.source==="daemon"&&i.reason.startsWith("permission:")));if(o.length!==r.length){let i=r.length-o.length;t+=i,await this.mutateRecord(s.sessionId,{attentionFlags:o}).catch(()=>{})}}t>0&&this.logger?.info(`cleared ${t} stale permission attention flags on startup`)}async resumePendingCompactions(){let e=new Set(["requested","running","swap_pending","swap_deferred"]),t=await this.store.list().catch(()=>[]);for(let s of t){let r=s.compactionState;if(r!=null){if(!e.has(r.status)){this.logger?.info(`compaction: not resuming sessionId=${s.sessionId} status=${r.status} (terminal \u2014 user must re-trigger explicitly)`);continue}this.logger?.info(`compaction: resuming sessionId=${s.sessionId} status=${r.status} from prior daemon`);try{this.scheduleCompaction(s.sessionId)}catch(o){this.logger?.warn(`compaction: resume failed for sessionId=${s.sessionId}: ${o instanceof Error?o.message:String(o)}`)}}}}async resumePendingAgentSwaps(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=t.pendingAgentSwap;if(s)try{let r=await this.histories.load(t.sessionId).catch(()=>[]);t.synopsis!==void 0&&t.summarizedThroughEntry!==void 0&&t.summarizedThroughEntry>=r.length&&t.synopsis?(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} with persisted synopsis (history=${r.length})`),await this.dispatchSynthesisSwap(t.sessionId,t.synopsis,t.summarizedThroughEntry??r.length,s)):(this.logger?.info(`agent-swap: resuming sessionId=${t.sessionId} target=${s} via fresh synthesis (history=${r.length} watermark=${t.summarizedThroughEntry??"(none)"})`),this.scheduleCompaction(t.sessionId,{targetAgentId:s}))}catch(r){this.logger?.warn(`agent-swap: resume failed for sessionId=${t.sessionId}: ${r instanceof Error?r.message:String(r)}`)}}}async resurrectPendingQueues(){let e=await this.store.list().catch(()=>[]);for(let t of e){let s=await Er(t.sessionId).catch(()=>[]);if(s.length===0)continue;let r=Date.now(),o=s.filter(u=>r-u.enqueuedAt<mo),i=s.length-o.length;if(i>0&&(this.logger?.info(`queue replay: dropping ${i} stale prompt(s) for ${t.sessionId} (TTL ${mo/1e3}s)`),await ct(t.sessionId,o).catch(()=>{})),o.length===0)continue;let a=await this.loadFromDisk(t.sessionId).catch(()=>{});if(!a){this.logger?.warn(`queue replay: no meta for ${t.sessionId}; discarding ${o.length} entr${o.length===1?"y":"ies"}`),await ct(t.sessionId,[]).catch(()=>{});continue}try{let u=await this.resurrect(a);this.logger?.info(`queue replay: resurrected ${t.sessionId} and replaying ${o.length} prompt(s)`),u.replayPersistedQueue(o)}catch(u){this.logger?.warn(`queue replay: failed to resurrect ${t.sessionId}: ${u.message}`)}}}};function Jd(n,e){if(typeof n!="string"||n.length===0)return!1;let t=wt.resolve(n),s=wt.resolve(e);return t===s||t.startsWith(s+wt.sep)}function Wd(n,e){let s=(n.mergedAvailableCommands().length>0?n.agentOnlyAdvertisedCommands().map(d=>d.description!==void 0?{name:d.name,description:d.description}:{name:d.name}):void 0)??e?.agentCommands,r=n.availableModes(),i=(r.length>0?r.map(d=>{let f={id:d.id};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModes,a=n.availableModels(),l=(a.length>0?a.map(d=>{let f={modelId:d.modelId};return d.name!==void 0&&(f.name=d.name),d.description!==void 0&&(f.description=d.description),f}):void 0)??e?.agentModels;return ts({sessionId:n.sessionId,lineageId:e?.lineageId??ft(),upstreamSessionId:n.upstreamSessionId,importedFromSessionId:e?.importedFromSessionId,importedFromUpstreamSessionId:e?.importedFromUpstreamSessionId,importedFromMachine:e?.importedFromMachine,agentId:n.agentId,cwd:n.cwd,title:n.title,synopsis:e?.synopsis,summarizedThroughEntry:e?.summarizedThroughEntry,agentArgs:n.agentArgs,currentModel:n.currentModel??e?.currentModel,currentMode:n.currentMode??e?.currentMode,currentUsage:bo(n.currentUsage)??e?.currentUsage,agentCommands:s,agentModes:i,agentModels:l,parentSessionId:n.parentSessionId??e?.parentSessionId,forkedFromSessionId:n.forkedFromSessionId??e?.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId??e?.forkedFromMessageId,originatingClient:n.originatingClient??e?.originatingClient,interactive:n.interactive??e?.interactive,priority:n.priority??e?.priority,forwardedEnv:n.forwardedEnv??e?.forwardedEnv,attentionFlags:n.listAttentionFlags(),extensionState:e?.extensionState,createdAt:e?.createdAt??new Date(n.createdAt).toISOString()})}function bo(n){if(!n)return;let e={};return n.used!==void 0&&(e.used=n.used),n.size!==void 0&&(e.size=n.size),n.costAmount!==void 0&&(e.costAmount=n.costAmount),n.costCurrency!==void 0&&(e.costCurrency=n.costCurrency),n.cumulativeCost!==void 0&&(e.cumulativeCost=n.cumulativeCost),Object.keys(e).length>0?e:void 0}function Qd(n){return n?{...n}:void 0}function ho(n,e){if(e&&n==="claude-acp")return{claudeCode:{options:{model:e}}}}function Vt(n,e){let t=e.fromObject(n);if(t!==void 0)return t;let s=n[e.nestedKey];if(s&&typeof s=="object"&&!Array.isArray(s)){let i=e.fromObject(s);if(i!==void 0)return i}let r=n._meta;if(r&&typeof r=="object"&&!Array.isArray(r)){for(let[i,a]of Object.entries(r))if(i!=="hydra-acp"&&a&&typeof a=="object"&&!Array.isArray(a)){let u=e.fromObject(a);if(u!==void 0)return u}}let o=Vd(n,e.configId);if(o){let i=e.fromConfig(o);if(i!==void 0)return i}}function as(n){return Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>me(e.currentModelId)??me(e.currentModel)??me(e.modelId)??me(e.model),fromConfig:e=>me(e.currentValue)})}function Ce(n,e){if(!n||typeof n!="object")return n;let t=n;if(t.code!==S.AuthRequired)return n;let s=l=>!!l&&typeof l=="object"&&!Array.isArray(l),r=s(t.data)?t.data:{},o=s(r._meta)?r._meta:{},i=s(o["hydra-acp"])?o["hydra-acp"]:{},a=typeof t.message=="string"?t.message:"authentication required",u=new Error(a);return u.code=S.AuthRequired,u.data={...r,_meta:{...o,"hydra-acp":{...i,authMethods:e.authMethods??[],agentId:e.agentId}}},u}function yo(n){return/^[A-Za-z0-9_\-./=:@]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}function wo(n,e,t,s){if(n&&typeof n=="object"&&n.code===S.AuthRequired)return n;let r=n instanceof Error?n.message:String(n),o=r.includes("stderr:"),i=o?"":e.stderrTailText(),a=s?`to reproduce: (cd ${yo(s.cwd)} && ${[s.command,...s.args].map(yo).join(" ")})`:"";if(!i&&!a)return n;let u=[o?r:`agent ${t} failed to start: ${r}`];i&&u.push(`stderr: ${i}`),a&&u.push(a);let l=new Error(u.join(`
|
|
122
|
+
`));if(n&&typeof n=="object"){let d=n;typeof d.code=="number"&&(l.code=d.code),d.data!==void 0&&(l.data=d.data)}return l}function ht(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.id!="string")continue;let r=typeof s.description=="string"?s.description:"",o=s.type==="agent"||s.type==="terminal"?s.type:void 0,i=typeof s.name=="string"?s.name:void 0,a=s._meta,u=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0;e.push({id:s.id,description:r,...o&&{type:o},...i!==void 0&&{name:i},...u&&{_meta:u}})}return e.length>0?e:void 0}function me(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Vd(n,e){let t=n.configOptions;if(Array.isArray(t))for(let s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let r=s;if(r.id===e)return r}}function ds(n){return n.length>0?n:void 0}function cs(n){return Vt(n,{nestedKey:"models",configId:"model",fromObject:e=>{let t=We(e.availableModels);return t.length>0?t:void 0},fromConfig:e=>{let t=We(e.options);return t.length>0?t:void 0}})??[]}function us(n){return Vt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>{let t=ut(e.availableModes);return t.length>0?t:void 0},fromConfig:e=>{let t=ut(e.options);return t.length>0?t:void 0}})??[]}function ls(n){return Vt(n,{nestedKey:"modes",configId:"mode",fromObject:e=>me(e.currentModeId)??me(e.currentMode)??me(e.modeId)??me(e.mode),fromConfig:e=>me(e.currentValue)})}function Kd(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(!t||t.method!=="session/update")continue;let s=t.params?.update;if(s?.sessionUpdate==="turn_complete"&&!(typeof s.messageId!="string"||s.messageId.length===0))return{index:e,messageId:s.messageId}}}async function vo(n){try{let e=await Te.readFile(k.tuiHistoryFile(n),"utf8"),t=[];for(let s of e.split(`
|
|
123
|
+
`))if(s.length!==0)try{let r=JSON.parse(s);typeof r=="string"&&t.push(r)}catch{}return t}catch{return[]}}async function yt(n){try{let e=await Te.stat(k.historyFile(n));return{mtime:new Date(e.mtimeMs).toISOString(),hasContent:e.size>0}}catch{return{hasContent:!1}}}function Ge(n,e){return n.interactive!==void 0?n.interactive:n.originatingClient?.name===Lt?!1:e?!0:void 0}import{spawn as Gd}from"child_process";import*as Gt from"fs";import*as be from"fs/promises";import*as Yt from"path";import Yd from"pino-roll";var Kt=class{windowMs;maxFailures;now;recentExits=[];tripped_;constructor(e={}){this.windowMs=e.windowMs??3e5,this.maxFailures=e.maxFailuresInWindow??10,this.now=e.now??Date.now}recordExit(e,t,s){if(e===78){let i=`exited with code 78 (unrecoverable); fix and run \`${s}s start ${t}\``;return this.tripped_=i,{tripped:i}}let r=this.now();this.recentExits.push(r);let o=r-this.windowMs;for(;this.recentExits.length>0&&this.recentExits[0]<o;)this.recentExits.shift();if(this.recentExits.length>this.maxFailures){let i=Math.round(this.windowMs/6e4),a=`${this.recentExits.length} exits in ${i}m (crash loop); fix and run \`${s}s start ${t}\``;return this.tripped_=a,{tripped:a}}return"restart"}reset(){this.recentExits=[],this.tripped_=void 0}get tripped(){return this.tripped_}};var Xd=1e3,Zd=6e4,fs=3e3,Ye=class{entries=new Map;stopping=!1;context;tokenRegistry;breakerOptions;restartBaseMs;restartCapMs;adapter;constructor(e,t,s,r={}){this.adapter=t,this.context=s,this.tokenRegistry=r.tokenRegistry,this.breakerOptions=r.breakerOptions,this.restartBaseMs=r.restartBaseMs??Xd,this.restartCapMs=r.restartCapMs??Zd;for(let o of e)this.entries.set(o.name,this.makeEntry(o))}setContext(e){this.context=e}reportVersion(e,t){let s=this.entries.get(e);s&&(s.version=t)}async start(){if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before start`);await be.mkdir(this.adapter.paths.dir(),{recursive:!0}),await this.reapOrphans();let e=[];for(let t of this.entries.values())t.config.enabled&&e.push(this.spawn(t,0));await Promise.all(e)}async stop(){this.stopping=!0;let e=[];for(let t of this.entries.values()){t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;if(s){try{s.kill("SIGTERM")}catch{}e.push(new Promise(r=>{if(s.exitCode!==null||s.signalCode!==null){r();return}let o=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}r()},fs);s.on("exit",()=>{clearTimeout(o),r()})}))}}await Promise.allSettled(e);for(let t of this.entries.values()){try{t.logStream?.end()}catch{}t.child=void 0,t.logStream=void 0,t.pid=void 0}}list(){return[...this.entries.values()].map(e=>this.infoFor(e))}get(e){let t=this.entries.get(e);return t?this.infoFor(t):void 0}has(e){return this.entries.has(e)}async startByName(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");if(t.child)throw bt(new Error(`${this.adapter.kind} ${e} already running`),"CONFLICT");return t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),t.manuallyStopped=!1,t.restartCount=0,t.breaker.reset(),t.failureReason=void 0,await this.spawn(t,0),this.infoFor(t)}async stopByName(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;return s?(await this.terminate(t,s),this.infoFor(t)):this.infoFor(t)}async restartByName(e){return await this.stopByName(e),this.startByName(e)}register(e){if(this.entries.has(e.name))throw bt(new Error(`${this.adapter.kind} ${e.name} already exists`),"CONFLICT");if(!this.context)throw new Error(`${this.managerName()}: setContext must be called before register`);let t=this.makeEntry(e);return this.entries.set(e.name,t),e.enabled&&this.spawn(t,0).catch(s=>{t.failureReason=`spawn: ${s.message}`}),this.infoFor(t)}async unregister(e){let t=this.entries.get(e);if(!t)throw bt(new Error(`unknown ${this.adapter.kind}: ${e}`),"NOT_FOUND");t.manuallyStopped=!0,t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0);let s=t.child;s&&await this.terminate(t,s);try{t.logStream?.end()}catch{}this.entries.delete(e)}async terminate(e,t){if(t.exitCode!==null||t.signalCode!==null)return;let s=new Promise(o=>{e.exitWaiters.push(o)});try{t.kill("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},fs);typeof r.unref=="function"&&r.unref();try{await s}finally{clearTimeout(r)}}infoFor(e){let t;return e.failureReason!==void 0?t="failed":e.child?t="running":e.restartTimer?t="restarting":e.config.enabled?t="stopped":t="disabled",{name:e.config.name,status:t,pid:e.pid,enabled:e.config.enabled,restartCount:e.restartCount,startedAt:e.startedAt,lastExitCode:e.lastExitCode,logPath:this.adapter.paths.logFile(e.config.name),version:e.version,failureReason:e.failureReason}}makeEntry(e){return{config:e,child:void 0,logStream:void 0,restartTimer:void 0,pid:void 0,startedAt:void 0,restartCount:0,lastExitCode:void 0,manuallyStopped:!1,exitWaiters:[],version:void 0,processToken:void 0,breaker:new Kt(this.breakerOptions),failureReason:void 0}}async reapOrphans(){let e;try{e=await be.readdir(this.adapter.paths.dir(),{withFileTypes:!0})}catch(t){if(t.code==="ENOENT")return;throw t}for(let t of e){if(!t.isDirectory())continue;let s=this.adapter.paths.pidFile(t.name),r;try{let o=await be.readFile(s,"utf8"),i=Number.parseInt(o.trim(),10);Number.isInteger(i)&&i>0&&(r=i)}catch{}if(typeof r=="number"&&ps(r)){try{process.kill(r,"SIGTERM")}catch{}let o=Date.now()+fs;for(;Date.now()<o&&ps(r);)await new Promise(i=>setTimeout(i,50));if(ps(r))try{process.kill(r,"SIGKILL")}catch{}}await be.unlink(s).catch(()=>{})}}async spawn(e,t){if(this.stopping||e.manuallyStopped)return;let s=this.context;if(!s)throw new Error(`${this.managerName()}.spawn called before setContext`);let r=e.config,o=r.command.length>0?r.command:[r.name],i=Yt.dirname(this.adapter.paths.logFile(r.name)),a;try{await be.mkdir(i,{recursive:!0}),a=await Yd({file:Yt.join(i,`${r.name}.log`),size:"5m",mkdir:!0,symlink:!0,limit:{count:5}})}catch(h){if(this.stopping||e.manuallyStopped)return;e.failureReason=`log setup: ${h.message}`,this.scheduleRestart(e,t+1);return}if(this.stopping||e.manuallyStopped){try{a.end()}catch{}return}a.write(`[hydra-acp] ${new Date().toISOString()} starting ${this.adapter.kind} ${r.name} (attempt ${t+1})
|
|
124
|
+
`);let u=this.tokenRegistry?.mint(r.name,this.adapter.tokenRole)??s.serviceToken;e.processToken=u,e.version=void 0;let l={...process.env,HYDRA_ACP_DAEMON_URL:s.daemonUrl,HYDRA_ACP_DAEMON_HOST:s.daemonHost,HYDRA_ACP_DAEMON_PORT:String(s.daemonPort),HYDRA_ACP_TOKEN:u,HYDRA_ACP_WS_URL:s.daemonWsUrl,HYDRA_ACP_HOME:s.hydraHome,[this.adapter.nameEnvVar]:r.name,...r.env},[d,...f]=o;if(d===void 0){a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} has empty command
|
|
125
|
+
`),a.end();return}let p=Y(d),c=[...f,...r.args].map(Y),g;try{g=Gd(p,c,{env:l,stdio:["ignore","pipe","pipe"],detached:!1})}catch(h){a.write(`[hydra-acp] failed to spawn ${r.name}: ${h.message}
|
|
126
|
+
`),a.end(),this.scheduleRestart(e,t);return}let m=h=>{try{a.write(typeof h=="string"?h:h.toString())}catch{}};if(g.stdout?.on("data",m),g.stderr?.on("data",m),typeof g.pid=="number")try{Gt.writeFileSync(this.adapter.paths.pidFile(r.name),`${g.pid}
|
|
127
127
|
`,{encoding:"utf8",mode:384})}catch(h){a.write(`[hydra-acp] failed to write pid file for ${r.name}: ${h.message}
|
|
128
|
-
`)}e.child=
|
|
129
|
-
`)}),
|
|
128
|
+
`)}e.child=g,e.logStream=a,e.pid=typeof g.pid=="number"?g.pid:void 0,e.startedAt=Date.now(),e.lastExitCode=void 0,g.on("error",h=>{a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} error: ${h.message}
|
|
129
|
+
`)}),g.on("exit",(h,v)=>{try{Gt.unlinkSync(this.adapter.paths.pidFile(r.name))}catch{}a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} exited code=${h??"null"} signal=${v??"null"}
|
|
130
130
|
`),e.child=void 0,e.pid=void 0,e.lastExitCode=typeof h=="number"?h:void 0,e.processToken&&(this.tokenRegistry?.revoke(r.name),e.processToken=void 0);let y=e.exitWaiters.splice(0);for(let b of y)b();if(this.stopping||e.manuallyStopped){try{a.end()}catch{}e.logStream=void 0;return}e.restartCount+=1;let w=e.breaker.recordExit(h,r.name,this.adapter.kind);if(typeof w=="object"){e.failureReason=w.tripped,a.write(`[hydra-acp] ${this.adapter.kind} ${r.name} circuit breaker tripped: ${w.tripped}
|
|
131
|
-
`);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ps(n){try{return process.kill(n,0),!0}catch{return!1}}function bt(n,e){return n.code=e,n}var
|
|
131
|
+
`);try{a.end()}catch{}e.logStream=void 0;return}this.scheduleRestart(e,t+1)})}scheduleRestart(e,t){if(this.stopping||e.manuallyStopped)return;let s=Math.min(this.restartBaseMs*2**Math.min(t,10),this.restartCapMs);e.restartTimer=setTimeout(()=>{e.restartTimer=void 0,this.spawn(e,t).catch(r=>{e.failureReason=`spawn: ${r.message}`})},s),typeof e.restartTimer.unref=="function"&&e.restartTimer.unref()}managerName(){return this.adapter.kind==="extension"?"ExtensionManager":"TransformerManager"}};function ps(n){try{return process.kill(n,0),!0}catch{return!1}}function bt(n,e){return n.code=e,n}var ec={kind:"extension",nameEnvVar:"HYDRA_ACP_EXTENSION_NAME",tokenRole:"extension",paths:{dir:k.extensionsDir,logFile:k.extensionLogFile,pidFile:k.extensionPidFile}},Xt=class extends Ye{constructor(e,t,s={}){super(e,ec,t,s)}};var tc={kind:"transformer",nameEnvVar:"HYDRA_ACP_TRANSFORMER_NAME",tokenRole:"transformer",paths:{dir:k.transformersDir,logFile:k.transformerLogFile,pidFile:k.transformerPidFile}},Zt=class extends Ye{connected=new Map;constructor(e,t,s={}){super(e,tc,t,s)}registerConnection(e,t,s){this.connected.set(e,{name:e,connection:t,intercepts:new Set(s)})}deregisterConnection(e){this.connected.delete(e)}resolveChain(e){let t=[];for(let s of e){let r=this.connected.get(s);r&&t.push(r)}return t}interestedIn(e){let t=[];for(let s of this.connected.values())s.intercepts.has(e)&&t.push(s);return t}};var en=class{entries=new Map;changeHandlers=[];register(e,t,s){this.entries.set(e,{connection:t,commands:[...s]}),this.fireChanged()}clear(e){this.entries.delete(e)&&this.fireChanged()}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}list(){let e=[];for(let[t,s]of this.entries)for(let r of s.commands)e.push({name:t,command:r});return e}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(){for(let e of this.changeHandlers)try{e()}catch{}}};import*as gs from"fs/promises";async function Io(n){await gs.writeFile(k.pidFile(),JSON.stringify(n)+`
|
|
132
132
|
`,{encoding:"utf8",mode:384})}import*as St from"fs/promises";import*as tn from"path";var It=n=>{process.stderr.write(n+`
|
|
133
|
-
`)};function
|
|
134
|
-
`))}async function So(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let c of s.agents)r.set(c.id,c.version??"current");let o=e.activeAgentVersions(),i=tn.join(S.agentsDir(),t),a;try{a=await St.readdir(i,{withFileTypes:!0})}catch(c){let u=c;if(u.code==="ENOENT")return;It(`hydra-acp: prune: failed to read ${i}: ${u.message}`);return}for(let c of a){if(!c.isDirectory())continue;let u=c.name,d=r.get(u);if(d===void 0)continue;let f=o.get(u)??new Set,p=tn.join(i,u),l;try{l=await St.readdir(p,{withFileTypes:!0})}catch(m){It(`hydra-acp: prune: failed to read ${p}: ${m.message}`);continue}for(let m of l){if(!m.isDirectory())continue;let g=m.name;if(g===d||f.has(g)||g.includes(".partial-"))continue;let h=tn.join(p,g);try{await St.rm(h,{recursive:!0,force:!0}),It(`hydra-acp: pruned stale ${u} ${g} (${h})`)}catch(v){It(`hydra-acp: prune: failed to remove ${h}: ${v.message}`)}}}}function ko(n){let e,t=!1,s=0,r=(a,c)=>{n.logger&&n.logger[a](`agent-sync: ${c}`)},o=async()=>{let a=[];try{let d=await n.registry.load();for(let f of d.agents)await Fn(f)==="yes"&&a.push(f.id)}catch(d){return r("warn",`registry load failed: ${d.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let c=s%a.length;s=(s+1)%a.length;let u=a[c];try{let{synced:d,skipped:f}=await n.manager.syncFromAgent(u);r("info",`${u}: synced ${d.length}, skipped ${f}`)}catch(d){r("warn",`${u}: ${d.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(c=>{i(c)}).catch(c=>{r("warn",`tick crashed: ${c.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function hs(n){let e=n.maxDeletions??200,t=(l,m)=>{n.logger&&n.logger[l](`session-gc: ${m}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(l=>(t("warn",`manager.list failed: ${l.message}`),[])),i=[];for(let l of o){if(l.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(l.interactive!==!1)continue}else if(l.interactive===!0)continue;let g=Date.parse(l.updatedAt);Number.isFinite(g)&&(n.maxAgeMs>0&&g>r||i.push({sessionId:l.sessionId,lastUsedMs:g}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((l,m)=>l.lastUsedMs-m.lastUsedMs);let a=i.slice(0,e),c=a[0]?.lastUsedMs,u=0,d=0;for(let{sessionId:l}of a)try{await n.manager.deleteRecord(l,"expired")&&(u+=1)}catch(m){d+=1,t("warn",`delete ${l} failed: ${m.message}`)}let f=i.length-a.length;if(n.verbose||u>0||d>0){let l=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${u} ${l} session(s) older than ${ec(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:i.length,deleted:u,failed:d,deferred:f};return c!==void 0&&(p.oldestLastUsedMs=c),p}function Ao(n){let e,t=!1,s=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await hs({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},o),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function ec(n){if(n<=0)return"any age";let e=n/(1440*60*1e3);if(e>=1)return`${e.toFixed(e>=10?0:1)}d`;let t=n/(3600*1e3);return`${t.toFixed(t>=10?0:1)}h`}import{createHash as tc}from"crypto";function ys(n){if(Array.isArray(n))return n.map(ys);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=ys(n[t]);return e}return n}function Co(n){let{tui:e,...t}=n,s=JSON.stringify(ys(t));return tc("sha256").update(s).digest("hex").slice(0,16)}import*as Ro from"path";import{createHash as nc,randomBytes as sc,timingSafeEqual as rc}from"crypto";var Eo="hydra_session_",oc=3600*24*30,xo=12,ic=32,ac=50;function dc(){return Ro.join(S.home(),"session-tokens.json")}function Mo(n){return nc("sha256").update(n).digest("hex")}function Po(n){return sc(n).toString("hex")}function cc(){return Po(xo).slice(0,xo*2)}function uc(){return`${Eo}${Po(ic)}`}var nn=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=dc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(lc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=uc(),s=Mo(t),r=cc(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:oc,a=new Date(o.getTime()+i*1e3),c={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,c),this.scheduleWrite(),{id:r,token:t,expiresAt:c.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Eo))return;let t=Mo(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!rc(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},ac))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>de(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function lc(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var To="Bearer ",sn=class{constructor(e){this.token=e}token;async validate(e){return fc(e,this.token)?"service":void 0}},rn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},on=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function _o(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(To)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(To.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function $o(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var an=class{tokens=new Map;mint(e,t){let s=Et();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function fc(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var dn=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Ss from"fs";import*as Ct from"os";import*as ti from"path";import*as ks from"readline";function ws(n){return Math.floor(n/4)}function Fo(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=ws(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}import{posix as pc}from"path";import mc from"strip-ansi";function kt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var gc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ie(n){return mc(n).replace(gc,"")}function W(n){return ie(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function No(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Sc(t);case"agent_thought_chunk":case"agent_thought":return kc(t);case"user_message_chunk":return Ac(t);case"prompt_received":return Cc(t);case"tool_call":return xc(t,e);case"tool_call_update":return Tc(t,e);case"plan":return Fc(t);case"current_mode_update":return Oc(t);case"current_model_update":return Hc(t);case"turn_complete":return Nc(t);case"usage_update":return Ic(t);case"available_commands_update":return vc(t);case"available_modes_update":return bc(t);case"session_info_update":return yc(t);case"config_option_update":return hc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function hc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function yc(n){let e=J(n,"title"),t=e!==void 0?W(e):void 0,s=n._meta,r,o;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a.agentId;if(typeof c=="string"&&(r=c),"pendingAgentSwap"in a){let u=a.pendingAgentSwap;typeof u=="string"?o=u:u===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function wc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:W(r)};typeof s.description=="string"&&(o.description=W(s.description)),e.push(o)}return e}function vc(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:wc(e)}:null}function bc(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:W(r.id)};typeof r.name=="string"&&(o.name=W(r.name)),typeof r.description=="string"&&(o.description=W(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function Ic(n){let e={kind:"usage-update"};if(typeof n.used=="number"&&(e.used=n.used),typeof n.size=="number"&&(e.size=n.size),n.cost&&typeof n.cost=="object"){let t=n.cost;typeof t.amount=="number"&&(e.costAmount=t.amount),typeof t.currency=="string"&&(e.costCurrency=t.currency)}return e}function Sc(n){let e=At(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:kt(n)}}function kc(n){let e=typeof n.text=="string"?ie(n.text):At(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:kt(n)}}function Ac(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=At(n.content);return t===null?null:{kind:"user-text",text:t}}function Cc(n){let e=jc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function jo(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Oo(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function cn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=Oo(r.oldText),i=Oo(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Bo(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:ie(t)}function xc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title")??J(n,"name")??J(n,"label")??"tool call",r=J(n,"name")??J(n,"title");if(jo(r)){let m=Bo(n);if(m!==null){let g=J(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:m};return g!==void 0&&(h.status=g),h}}let o=Lo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),c={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(c.status=i),a!==void 0&&(c.rawKind=a);let u=cn(n);u!==null&&(c.editDiff=u);let d=Do(n);d!==void 0&&(c.detail=d);let f=vs(n);f!==void 0&&(c.detailFull=f);let p=Uo(n);p!==void 0&&(c.locations=p);let l=kt(n);return l!==void 0&&(c.workerTaskId=l),c}function Uo(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Ho=64;function Do(n){let e=vs(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?Ec(t,Ho):Pc(t,Ho)}function vs(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ie(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Me(W(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return Me(W(s))}}}var Mc=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Rc(n){for(let e of Mc)if(n.startsWith(e))return!0;return!1}function Lo(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return Me(i)}return Rc(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(pc.resolve(t.cwd,n)):n}function Ec(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Pc(n,e){if(n.length<=e)return n;let t=n.slice(-(e-1)),s=t.indexOf("/");return s>=0&&s<e/2?`\u2026${t.slice(s)}`:`\u2026${t}`}function Tc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Lo(W(s),n,e):void 0,o=J(n,"status"),i=cn(n),a=Do(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let u=J(n,"name")??s;if(jo(u)){let m={kind:"exit-plan-mode",toolCallId:t},g=Bo(n);return g!==null&&(m.plan=g),o!==void 0&&(m.status=o),m}let d={kind:"tool-call-update",toolCallId:t};r!==void 0&&(d.title=r),a!==void 0&&(d.detail=a);let f=vs(n);f!==void 0&&(d.detailFull=f);let p=Uo(n);if(p!==void 0&&(d.locations=p),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let m=_c(n);m!==null&&(d.errorText=m),$c(n,m)&&(d.upstreamInterrupted=!0)}let l=kt(n);return l!==void 0&&(d.workerTaskId=l),d}function _c(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=At(s.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ie(s)}return null}function $c(n,e){let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.metadata;if(s&&typeof s=="object"&&s.interrupted===!0)return!0}return!!(e!==null&&e.toLowerCase().includes("tool execution aborted"))}function Fc(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?W(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function Oc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function Hc(n){let e=J(n,"currentModel")??J(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:W(e),...s&&s.length>0?{availableModels:s}:{}}}function Nc(n){let e=J(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function At(n){if(typeof n=="string")return ie(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ie(e.text):null}function jc(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=At(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function J(n,e){let t=n[e];return typeof t=="string"?t:void 0}function qo(n){let e=new Map,t=new Map;for(let r of n){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let c=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,u=Uc(i);if(u.length===0)continue;let d=u;if(c!==void 0){let f=e.get(c)??[],p=[];for(let l of u)f.some(m=>m.path===l.path&&m.oldText===l.oldText&&m.newText===l.newText)||p.push(l);if(p.length===0)continue;e.set(c,[...f,...p]),d=p}for(let f of d)Bc(t,f)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function zo(n){let e=[];for(let t of n){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){s=o;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Bc(n,e){let t={oldText:e.oldText,newText:e.newText},s=n.get(e.path);if(s===void 0){n.set(e.path,{hunks:[t],created:e.oldText.length===0});return}s.hunks.push(t)}function Uc(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let c of a){if(!c||typeof c!="object")continue;let u=c,d=typeof u.old_string=="string"?u.old_string:void 0,f=typeof u.new_string=="string"?u.new_string:void 0;d===void 0||f===void 0||e.push({path:i,oldText:d,newText:f})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let c=typeof i.oldText=="string"?i.oldText:"",u=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:c,newText:u})}if(e.length>0)return e}let r=cn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Jo(n){let e=Dc(n),t=Lc(e),s=[];qc(s,n),zc(s,e,t);let r=s.join(`
|
|
135
|
-
`);return
|
|
136
|
-
`)||(
|
|
137
|
-
`),
|
|
138
|
-
`)),n.push("")}function
|
|
139
|
-
`))n.push(`> ${_e(d)}`);n.push(""),n.push("**Assistant:**"),n.push(""),i=!0;break}case"agent-text":c(),o+=u.text;break;case"agent-thought":{c(),a();let d=u.text.split(`
|
|
140
|
-
`);for(let f of d)n.push(`> _${_e(f)}_`);n.push("");break}case"tool-call":{if(c(),a(),s.has(u.toolCallId))break;s.add(u.toolCallId);let d=t.get(u.toolCallId)??{title:u.title,status:u.status??"pending"};n.push(`- ${Qc(d.status)} ${Wc(d)}`),n.push("");break}case"tool-call-update":break;case"plan":{c(),a(),n.push("**Plan:**"),n.push("");for(let d of u.entries){let f=d.status==="completed"?"[x]":"[ ]";n.push(`- ${f} ${_e(d.content)}`)}n.push("");break}case"mode-changed":c(),a(),n.push(`_mode: ${_e(u.mode)}_`),n.push("");break;case"model-changed":c(),a(),n.push(`_model: ${_e(u.model)}_`),n.push("");break;case"turn-complete":a();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}a()}function Jc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Wc(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${_e(n.title)}${t}`}function Qc(n){switch(n){case"completed":return"\u2713";case"failed":return"\u2717";case"cancelled":case"rejected":return"\u2298";case"in_progress":return"\u21BB";default:return"\xB7"}}function _e(n){return n.replace(/</g,"<").replace(/>/g,">")}function bs(n){return n.toLocaleString("en-US")}function Wo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Vc(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,c=[];for(let d of s){let f=d.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:c.push(d)}i?o="AND":a&&(o="OR");let u=c.map(d=>Kc(d)).filter(d=>d.term.length>0);return{operator:o,terms:u}}function Kc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Qo(e[1]),term:e[2]};let t=/^"([^"]*)"$/.exec(n);if(t)return{scope:"all",term:t[1]};let s=/^(prompt|response|tool):([\s\S]*)$/i.exec(n);return s?{scope:Qo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Qo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Gc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Yc=5,Xc=200,Vo=30;async function Yo(n,e,t={}){let s=Vc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Yc,o=t.maxSessions??Xc,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),c=i?a.filter(f=>i.has(f.sessionId)):a,u=[],d=!1;for(let f of c){if(u.length>=o){d=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),l=Zc(p,s,r);if(l.snippets.length===0)continue;let m={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:l.totalMatches,snippets:l.snippets};f.title!==void 0&&(m.title=f.title),u.push(m)}return{query:e,truncated:d,results:u}}function Zc(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=eu(n,i,o,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function eu(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let c=tu(a).filter(u=>Gc(t,u.kind));for(let u of c){let d=u.text.toLowerCase(),f=d.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=d.indexOf(r,f+r.length);if(o+=p,i.length<s){let l=d.indexOf(r),m={kind:u.kind,text:iu(u.text,l,r.length),recordedAt:a.recordedAt};u.toolName!==void 0&&(m.toolName=u.toolName),i.push(m)}}}return{totalMatches:o,snippets:i}}function tu(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=un(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?ie(s.text):un(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(ru(s))return[];let o=un(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=ou(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return nu(s);default:return[]}}function nu(n){let e=Ko(n,"name"),t=Ko(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let c={kind:"tool",text:a};e!==void 0&&(c.toolName=e),s.push(c)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Go(r);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Go(o);if(a.length>0){let c={kind:"tool-input",text:W(a)};e!==void 0&&(c.toolName=e),s.push(c)}}let i=su(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function su(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=W(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=W(s);if(r.length>0)return r}}return null}function ru(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function un(n){if(typeof n=="string")return ie(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ie(e.text):""}function ou(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=un(t);s.length>0&&e.push(s)}return e.join("")}function Ko(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Go(n){try{return JSON.stringify(n)}catch{return""}}function iu(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-Vo),c=Math.min(s.length,i+o.length+Vo),u=a>0?"\u2026":"",d=c<s.length?"\u2026":"";return`${u}${s.slice(a,c)}${d}`}import{randomBytes as Zo}from"crypto";function Xo(n){let e=Zo(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Is(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Xo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Xo({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let o=Ze(n.deps);return o!==void 0&&(o.bindToSession(s),r=[...r,...o.descriptors]),r}}function Ze(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=Zo(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{s.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>s.abandon(a)}}var ln=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ei(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Wo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function ni(n,e,t,s={}){n.get("/v1/sessions",async u=>{let d=u.query,f=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.getOne(p);return l||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(u,d)=>{let f=u.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return d.code(400).send({error:"q is required"}),d;let l=Array.isArray(f.sessionIds)?f.sessionIds.filter(g=>typeof g=="string"&&g.length>0):void 0;return await Yo(e,p,{sessionIds:l})}),n.post("/v1/sessions",async(u,d)=>{let f=u.body??{},p=Y(f.cwd??t.cwd),l=f.agentId??t.agentId,m=Ze(s),g=m!==void 0?[...f.mcpServers??[],...m.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:l,mcpServers:g});m!==void 0&&m.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){m!==void 0&&m.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),n.post("/v1/sessions/collect",async(u,d)=>{let f=u.body??{},p=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,l=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,m=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let g=await hs({manager:e,maxAgeMs:p,maxDeletions:l,selection:m,verbose:!1});d.code(200).send(g)}catch(g){d.code(500).send({error:g.message})}}),n.post("/v1/sessions/:id/kill",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){l.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return d.code(404).send({error:"session not found"}),d;let m=u.body??{},g={};(m.mode==="memory"||m.mode==="file")&&(g.mode=m.mode),typeof m.capacityBytes=="number"&&(g.capacityBytes=m.capacityBytes),typeof m.fileCapBytes=="number"&&(g.fileCapBytes=m.fileCapBytes),(g.mode??"memory")==="file"&&(g.filePathFor=h=>ti.join(Ct.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return l.openStream(g)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(!l)return d.code(404).send({error:"session not found"}),d;let m=u.body??{},g=typeof m.chunk=="string"?m.chunk:"",h=m.eof===!0;try{return l.streamWrite(g,h)}catch(v){return d.code(409).send({error:v.message}),d}}),n.patch("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{};if(l.priority!==void 0){let g=l.priority,h;if(g===null||g===0)h=void 0;else if(typeof g=="number"&&Number.isInteger(g)&&g>0)h=g;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(l.regen===!0){if(!(e.get(p)!==void 0||await e.hasRecord(p))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(p),d.code(202).send();return}if(typeof l.title!="string"||l.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,l.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);if(l){await l.close({deleteRecord:!0}),await e.waitForDeletion(p),await e.hasRecord(p)&&await e.deleteRecord(p),d.code(204).send();return}if(!await e.deleteRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.get("/v1/sessions/:id/export",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.query?.tools,m=l==="references"?"references":ro(l),g=await e.exportBundle(p,m==="references"?{tools:"references"}:{});if(!g){d.code(404).send({error:"session not found"});return}let h=gt({record:g.record,history:m==="summary"?oo(g.history,"summary"):g.history,promptHistory:g.promptHistory.length>0?g.promptHistory:void 0,...g.toolBlobs!==void 0?{toolBlobs:g.toolBlobs}:{},hydraVersion:K,machine:Ct.hostname(),hydraHost:ei(t)}),v=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${p}-${v}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){d.code(404).send({error:"session not found"});return}let m=u.query??{},g=m.fold==="true"||m.fold==="1",h=typeof m.paths=="string"&&m.paths.length>0?new Set(m.paths.split(",").map(y=>y.trim()).filter(y=>y.length>0)):void 0,v=qo(l.history);h&&(v=v.filter(y=>h.has(y.path))),g&&(v=v.map(y=>({...y,hunks:zo(y.hunks)}))),d.code(200).send(v)}),n.get("/v1/sessions/:id/tools/:hash",async(u,d)=>{let f=u.params,p=await e.resolveCanonicalId(f.id)??f.id,l=await e.loadToolBlob(p,f.hash);if(l===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(l)}),n.get("/v1/sessions/:id/transcript",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=await e.exportBundle(p);if(!l){d.code(404).send({error:"session not found"});return}let m=gt({record:l.record,history:l.history,promptHistory:l.promptHistory.length>0?l.promptHistory:void 0,hydraVersion:K,machine:Ct.hostname(),hydraHost:ei(t)});d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(Jo(m))}),n.post("/v1/sessions/:id/fork",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=u.body??{},m={};if(l.forkAt!==void 0){if(typeof l.forkAt!="string"||l.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}m.forkAt=l.forkAt}if(l.cwd!==void 0){if(typeof l.cwd!="string"||l.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}m.cwd=Y(l.cwd)}if(l.agentId!==void 0){if(typeof l.agentId!="string"||l.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}m.agentId=l.agentId}if(l.title!==void 0){if(typeof l.title!="string"){d.code(400).send({error:"title must be a string"});return}m.title=l.title}if(l.mode!==void 0){if(l.mode!=="verbatim"&&l.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}m.mode=l.mode}if(l.model!==void 0){if(typeof l.model!="string"||l.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}m.model=l.model}try{let g=await e.forkSession(p,m);d.code(201).send(g)}catch(g){let h=g;if(h.code===I.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===I.InvalidParams||h.code===I.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),n.post("/v1/sessions/import",async(u,d)=>{let f=u.body??{};if(f.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let p;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}p=f.cwd}let l;try{l=mo(f.bundle)}catch(m){d.code(400).send({error:"invalid bundle",details:m.message});return}try{let m=await e.importBundle(l,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});d.code(201).send(m)}catch(m){let g=m;if(g.code===I.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:g.existingSessionId});return}d.code(500).send({error:g.message})}}),n.get("/v1/sessions/:id/compact/status",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p),m;if(l?m=l.summarizedThroughEntry:m=await e.getSummarizedThroughEntry(p),m===void 0&&!await e.hasRecord(p))return d.code(404).send({error:"session not found"}),d;let g=await e.getCompactionState(p),h=await e.getRollbackBreadcrumb(p),v=!1,y,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=m??0,x=b.length,T=b.slice(A).reduce((P,j)=>P+JSON.stringify(j.params).length,0);y=ws(T);let _=l?.currentModel,U=b.at(-1).recordedAt,$=l?.currentUsage;v=Fo({summarizedThroughEntry:A,totalEntries:x,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:m??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:v,...y!=null?{approxTokens:y}:{},...g!=null?{compactionState:g}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(e.get(p)){e.scheduleCompaction(p),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(p),d.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(p),d.code(202).send({rolledBack:!0})}catch(l){let m=l instanceof Error?l.message:String(l);d.code(409).send({error:m})}}),n.get("/v1/sessions/:id/history",async(u,d)=>{let f=u.params.id,p=u.query,l=p?.follow==="1"||p?.follow==="true",m=await e.resolveCanonicalId(f)??f,g=e.get(m),h,v,y=!1,w=1e4,b=[];if(g){l&&(v=g.onBroadcast(x=>{d.raw.writableEnded||(y?d.raw.write(JSON.stringify(x)+`
|
|
141
|
-
`):(b.push(x),b.length>w&&b.shift()))})),u.raw.on("close",()=>{v?.(),d.raw.writableEnded||d.raw.end()});try{h=await g.getHistorySnapshot()}catch(x){throw v?.(),x}}else{let x=await e.getHistory(m);if(x===void 0)return d.code(404).send({error:"session not found"}),d;h=x}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let A=new Set;for(let x of h??[]){d.raw.write(JSON.stringify(x)+`
|
|
133
|
+
`)};function ms(n){It=n??(e=>process.stderr.write(e+`
|
|
134
|
+
`))}async function So(n,e){let t=le();if(!t)return;let s=await n.load(),r=new Map;for(let u of s.agents)r.set(u.id,u.version??"current");let o=e.activeAgentVersions(),i=tn.join(k.agentsDir(),t),a;try{a=await St.readdir(i,{withFileTypes:!0})}catch(u){let l=u;if(l.code==="ENOENT")return;It(`hydra-acp: prune: failed to read ${i}: ${l.message}`);return}for(let u of a){if(!u.isDirectory())continue;let l=u.name,d=r.get(l);if(d===void 0)continue;let f=o.get(l)??new Set,p=tn.join(i,l),c;try{c=await St.readdir(p,{withFileTypes:!0})}catch(g){It(`hydra-acp: prune: failed to read ${p}: ${g.message}`);continue}for(let g of c){if(!g.isDirectory())continue;let m=g.name;if(m===d||f.has(m)||m.includes(".partial-"))continue;let h=tn.join(p,m);try{await St.rm(h,{recursive:!0,force:!0}),It(`hydra-acp: pruned stale ${l} ${m} (${h})`)}catch(v){It(`hydra-acp: prune: failed to remove ${h}: ${v.message}`)}}}}function ko(n){let e,t=!1,s=0,r=(a,u)=>{n.logger&&n.logger[a](`agent-sync: ${u}`)},o=async()=>{let a=[];try{let d=await n.registry.load();for(let f of d.agents)await Fn(f)==="yes"&&a.push(f.id)}catch(d){return r("warn",`registry load failed: ${d.message}`),n.intervalMs}if(a.length===0)return n.intervalMs;let u=s%a.length;s=(s+1)%a.length;let l=a[u];try{let{synced:d,skipped:f}=await n.manager.syncFromAgent(l);r("info",`${l}: synced ${d.length}, skipped ${f}`)}catch(d){r("warn",`${l}: ${d.message}`)}return Math.max(1,Math.floor(n.intervalMs/a.length))},i=a=>{t||(e=setTimeout(()=>{o().then(u=>{i(u)}).catch(u=>{r("warn",`tick crashed: ${u.message}`),i(n.intervalMs)})},a),e.unref())};return i(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}async function hs(n){let e=n.maxDeletions??200,t=(c,g)=>{n.logger&&n.logger[c](`session-gc: ${g}`)},s=Date.now(),r=n.maxAgeMs>0?s-n.maxAgeMs:Number.POSITIVE_INFINITY,o=await n.manager.list({includeNonInteractive:!0}).catch(c=>(t("warn",`manager.list failed: ${c.message}`),[])),i=[];for(let c of o){if(c.status!=="cold")continue;if((n.selection??"explicit")==="explicit"){if(c.interactive!==!1)continue}else if(c.interactive===!0)continue;let m=Date.parse(c.updatedAt);Number.isFinite(m)&&(n.maxAgeMs>0&&m>r||i.push({sessionId:c.sessionId,lastUsedMs:m}))}if(i.length===0)return n.verbose&&t("info","no candidates"),{considered:0,deleted:0,failed:0,deferred:0};i.sort((c,g)=>c.lastUsedMs-g.lastUsedMs);let a=i.slice(0,e),u=a[0]?.lastUsedMs,l=0,d=0;for(let{sessionId:c}of a)try{await n.manager.deleteRecord(c,"expired")&&(l+=1)}catch(g){d+=1,t("warn",`delete ${c} failed: ${g.message}`)}let f=i.length-a.length;if(n.verbose||l>0||d>0){let c=(n.selection??"explicit")==="unpromoted"?"unpromoted":"non-interactive";t("info",`swept ${l} ${c} session(s) older than ${nc(n.maxAgeMs)}`+(d>0?`; ${d} failed`:"")+(f>0?`; ${f} deferred to next sweep`:""))}let p={considered:i.length,deleted:l,failed:d,deferred:f};return u!==void 0&&(p.oldestLastUsedMs=u),p}function Ao(n){let e,t=!1,s=!1,r=o=>{t||(e=setTimeout(()=>{(async()=>{if(!s){s=!0;try{await hs({manager:n.manager,maxAgeMs:n.maxAgeMs,selection:"unpromoted",...n.maxDeletionsPerSweep!==void 0?{maxDeletions:n.maxDeletionsPerSweep}:{},...n.logger?{logger:n.logger}:{}})}finally{s=!1}}})().catch(a=>{n.logger?.warn(`session-gc: sweep crashed: ${a.message}`)}).finally(()=>{r(n.intervalMs)})},o),e.unref())};return r(n.intervalMs),()=>{t=!0,e&&(clearTimeout(e),e=void 0)}}function nc(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 sc}from"crypto";function ys(n){if(Array.isArray(n))return n.map(ys);if(n!==null&&typeof n=="object"){let e={};for(let t of Object.keys(n).sort())e[t]=ys(n[t]);return e}return n}function Co(n){let{tui:e,...t}=n,s=JSON.stringify(ys(t));return sc("sha256").update(s).digest("hex").slice(0,16)}import*as Ro from"path";import{createHash as rc,randomBytes as oc,timingSafeEqual as ic}from"crypto";var Eo="hydra_session_",ac=3600*24*30,xo=12,dc=32,cc=50;function uc(){return Ro.join(k.home(),"session-tokens.json")}function Mo(n){return rc("sha256").update(n).digest("hex")}function Po(n){return oc(n).toString("hex")}function lc(){return Po(xo).slice(0,xo*2)}function fc(){return`${Eo}${Po(dc)}`}var nn=class n{records=new Map;writeTimer=null;writeInflight=null;filePath;constructor(e,t){this.filePath=t;for(let s of e)this.records.set(s.hash,s)}static async load(){let e=[],t=uc(),s=await ue(t);s&&Array.isArray(s.records)&&(e=s.records.filter(pc));let r=new n(e,t);return r.sweepExpired(new Date)>0&&await r.flush(),r}async issue(e={}){let t=fc(),s=Mo(t),r=lc(),o=new Date,i=e.ttlSec&&e.ttlSec>0?e.ttlSec:ac,a=new Date(o.getTime()+i*1e3),u={id:r,hash:s,label:e.label,createdAt:o.toISOString(),expiresAt:a.toISOString(),lastUsedAt:o.toISOString()};return this.records.set(s,u),this.scheduleWrite(),{id:r,token:t,expiresAt:u.expiresAt}}async verify(e){if(typeof e!="string"||!e.startsWith(Eo))return;let t=Mo(e),s=this.records.get(t);if(!s)return;let r=Buffer.from(s.hash,"hex"),o=Buffer.from(t,"hex");if(r.length!==o.length||!ic(r,o))return;let i=new Date;if(new Date(s.expiresAt).getTime()<=i.getTime()){this.records.delete(t),this.scheduleWrite();return}return s.lastUsedAt=i.toISOString(),this.scheduleWrite(),s.id}async revoke(e){for(let[t,s]of this.records)if(s.id===e)return this.records.delete(t),this.scheduleWrite(),!0;return!1}async revokeAll(){let e=this.records.size;return this.records.clear(),this.scheduleWrite(),e}list(){return Array.from(this.records.values()).map(({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})=>({id:e,label:t,createdAt:s,expiresAt:r,lastUsedAt:o})).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sweepExpired(e=new Date){let t=0;for(let[s,r]of this.records)new Date(r.expiresAt).getTime()<=e.getTime()&&(this.records.delete(s),t+=1);return t>0&&this.scheduleWrite(),t}async flush(){this.writeTimer&&(clearTimeout(this.writeTimer),this.writeTimer=null),await this.persist()}scheduleWrite(){this.writeTimer||(this.writeTimer=setTimeout(()=>{this.writeTimer=null,this.persist().catch(()=>{})},cc))}persist(){let e=(this.writeInflight??Promise.resolve()).catch(()=>{}).then(()=>de(this.filePath,{records:Array.from(this.records.values())},{mode:384}));return this.writeInflight=e,e.catch(()=>{}).finally(()=>{this.writeInflight===e&&(this.writeInflight=null)}),e}};function pc(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.id=="string"&&typeof e.hash=="string"&&typeof e.createdAt=="string"&&typeof e.expiresAt=="string"&&typeof e.lastUsedAt=="string"&&(e.label===void 0||typeof e.label=="string")}var To="Bearer ",sn=class{constructor(e){this.token=e}token;async validate(e){return gc(e,this.token)?"service":void 0}},rn=class{constructor(e){this.store=e}store;async validate(e){return this.store.verify(e)}},on=class{constructor(e){this.validators=e}validators;async validate(e){for(let t of this.validators){let s=await t.validate(e);if(s!==void 0)return s}}};function _o(n){return async function(t,s){let r=t.headers.authorization;if(!r||!r.startsWith(To)){s.code(401).send({error:"Missing bearer token"});return}let o=r.slice(To.length).trim(),i=await n.validator.validate(o);if(!i){s.code(403).send({error:"Invalid token"});return}t.authIdentity=i}}function $o(n){let e=n.headers["sec-websocket-protocol"],t=Array.isArray(e)?e.join(","):e;if(t)for(let s of t.split(",")){let r=s.trim(),o="hydra-acp-token.";if(r.startsWith(o))return r.slice(o.length)}if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{return}}var an=class{tokens=new Map;mint(e,t){let s=Et();return this.tokens.set(s,{name:e,kind:t}),s}revoke(e){for(let[t,s]of this.tokens)s.name===e&&this.tokens.delete(t)}resolve(e){return this.tokens.get(e)}async validate(e){let t=this.tokens.get(e);if(t)return`${t.kind}:${t.name}`}};function gc(n,e){if(n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s+=1)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}var dn=class{entries=new Map;maxFails;windowMs;constructor(e=10,t=900*1e3){this.maxFails=e,this.windowMs=t}isBlocked(e){let t=this.entries.get(e);return t?Date.now()-t.windowStart>this.windowMs?(this.entries.delete(e),!1):t.fails>=this.maxFails:!1}recordFailure(e){let t=Date.now(),s=this.entries.get(e);if(!s||t-s.windowStart>this.windowMs){this.entries.set(e,{fails:1,windowStart:t});return}s.fails+=1}recordSuccess(e){this.entries.delete(e)}sweepExpired(){let e=Date.now();for(let[t,s]of this.entries)e-s.windowStart>this.windowMs&&this.entries.delete(t)}};import*as Ss from"fs";import*as Ct from"os";import*as ni from"path";import*as ks from"readline";function ws(n){return Math.floor(n/4)}function Fo(n){if(n.compactionInFlight||n.totalEntries===0)return!1;let e;if(typeof n.agentReportedUsed=="number"&&typeof n.agentReportedSize=="number"&&n.agentReportedSize>0)e=n.agentReportedUsed/n.agentReportedSize;else{let s=ws(n.unsummarizedChars),r=n.currentModel!==void 0?n.config.modelContextWindows[n.currentModel]??n.config.absoluteFallback:n.config.absoluteFallback;e=s/r}if(e>=n.config.hardCeilingFraction)return!0;let t=n.nowMs-n.lastActivityMs;return e>=n.config.contextFraction&&t>=n.config.idleBeforePromptMs}import{posix as mc}from"path";import hc from"strip-ansi";function kt(n){if(!n||typeof n!="object")return;let e=n;return typeof e.workerTaskId=="string"?e.workerTaskId:void 0}var yc=/[\x00-\x08\x0b-\x1f\x7f]/g;function ie(n){return hc(n).replace(yc,"")}function W(n){return ie(n).replace(/[\n\t]+/g," ").replace(/ +/g," ").trim()}function No(n,e={}){if(!n||typeof n!="object")return null;let t=n,s=t.sessionUpdate??t.kind;if(typeof s!="string")return null;switch(s){case"agent_message_chunk":return Ac(t);case"agent_thought_chunk":case"agent_thought":return Cc(t);case"user_message_chunk":return xc(t);case"prompt_received":return Mc(t);case"tool_call":return Rc(t,e);case"tool_call_update":return $c(t,e);case"plan":return Hc(t);case"current_mode_update":return Nc(t);case"current_model_update":return jc(t);case"turn_complete":return Bc(t);case"usage_update":return kc(t);case"available_commands_update":return Ic(t);case"available_modes_update":return Sc(t);case"session_info_update":return vc(t);case"config_option_update":return wc(t);default:return{kind:"unknown",sessionUpdate:s,raw:n}}}function wc(n){let e=n.configOptions;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||typeof r.currentValue!="string"||!Array.isArray(r.options))continue;let o=[];for(let i of r.options){if(!i||typeof i!="object")continue;let a=i;typeof a.value=="string"&&o.push({value:a.value,name:typeof a.name=="string"?a.name:a.value,...typeof a.description=="string"?{description:a.description}:{}})}t.push({id:r.id,name:typeof r.name=="string"?r.name:r.id,type:"select",currentValue:r.currentValue,options:o,...typeof r.category=="string"?{category:r.category}:{}})}return{kind:"config-options",options:t}}function vc(n){let e=J(n,"title"),t=e!==void 0?W(e):void 0,s=n._meta,r,o;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=s["hydra-acp"];if(a&&typeof a=="object"&&!Array.isArray(a)){let u=a.agentId;if(typeof u=="string"&&(r=u),"pendingAgentSwap"in a){let l=a.pendingAgentSwap;typeof l=="string"?o=l:l===null&&(o=null)}}}if(t===void 0&&r===void 0&&o===void 0)return null;let i={kind:"session-info"};return t!==void 0&&(i.title=t),r!==void 0&&(i.agentId=r),o!==void 0&&(i.pendingAgentSwap=o),i}function bc(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){if(!t||typeof t!="object")continue;let s=t;if(typeof s.name!="string"||s.name.length===0)continue;let r=s.name.startsWith("/")?s.name:`/${s.name}`,o={name:W(r)};typeof s.description=="string"&&(o.description=W(s.description)),e.push(o)}return e}function Ic(n){let e=n.availableCommands??n.commands;return Array.isArray(e)?{kind:"available-commands",commands:bc(e)}:null}function Sc(n){let e=n.availableModes;if(!Array.isArray(e))return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.id!="string"||r.id.length===0)continue;let o={id:W(r.id)};typeof r.name=="string"&&(o.name=W(r.name)),typeof r.description=="string"&&(o.description=W(r.description)),t.push(o)}return{kind:"available-modes",modes:t}}function kc(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 Ac(n){let e=At(n.content);return e===null?null:{kind:"agent-text",text:e,workerTaskId:kt(n)}}function Cc(n){let e=typeof n.text=="string"?ie(n.text):At(n.content);return e===null?null:{kind:"agent-thought",text:e,workerTaskId:kt(n)}}function xc(n){let e=n._meta;if(e&&typeof e=="object"&&!Array.isArray(e)){let s=e["hydra-acp"];if(s&&typeof s=="object"&&!Array.isArray(s)&&s.compatFor==="prompt_received")return null}let t=At(n.content);return t===null?null:{kind:"user-text",text:t}}function Mc(n){let e=Uc(n.prompt);return e===null?null:{kind:"user-text",text:e}}function jo(n){return n?n.toLowerCase().replace(/[_\s-]/g,"")==="exitplanmode":!1}function Oo(n){if(typeof n=="string")return{text:n};if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n;if(typeof e.__hydraBlob=="string")return{ref:{hash:e.__hydraBlob,bytes:typeof e.bytes=="number"?e.bytes:0}}}}function cn(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(r.type!=="diff")continue;let o=Oo(r.oldText),i=Oo(r.newText);if(o===void 0&&i===void 0)continue;let a=typeof r.path=="string"?r.path:void 0;return{...a!==void 0?{path:a}:{},oldText:o?.text??"",newText:i?.text??"",...o?.ref?{oldRef:o.ref}:{},...i?.ref?{newRef:i.ref}:{}}}let t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let s=t,r=typeof s.file_path=="string"?s.file_path:typeof s.path=="string"?s.path:void 0;if(typeof s.old_string=="string"&&typeof s.new_string=="string")return{...r!==void 0?{path:r}:{},oldText:s.old_string,newText:s.new_string};if(typeof s.content=="string")return{...r!==void 0?{path:r}:{},oldText:"",newText:s.content}}return null}function Bo(n){let e=n.rawInput;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.plan;return typeof t!="string"||t.length===0?null:ie(t)}function Rc(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title")??J(n,"name")??J(n,"label")??"tool call",r=J(n,"name")??J(n,"title");if(jo(r)){let g=Bo(n);if(g!==null){let m=J(n,"status"),h={kind:"exit-plan-mode",toolCallId:t,plan:g};return m!==void 0&&(h.status=m),h}}let o=Lo(W(s),n,e),i=J(n,"status"),a=J(n,"kind"),u={kind:"tool-call",toolCallId:t,title:o};i!==void 0&&(u.status=i),a!==void 0&&(u.rawKind=a);let l=cn(n);l!==null&&(u.editDiff=l);let d=Do(n);d!==void 0&&(u.detail=d);let f=vs(n);f!==void 0&&(u.detailFull=f);let p=Uo(n);p!==void 0&&(u.locations=p);let c=kt(n);return c!==void 0&&(u.workerTaskId=c),u}function Uo(n){let e=n.locations;if(!Array.isArray(e))return;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s;if(typeof r.path!="string"||r.path.length===0)continue;let o={path:r.path};typeof r.line=="number"&&Number.isFinite(r.line)&&r.line>=1&&(o.line=Math.floor(r.line)),t.push(o)}return t.length>0?t:void 0}var Ho=64;function Do(n){let e=vs(n);if(e===void 0)return;let t=W(e),s=n.rawInput;return s&&typeof s.command=="string"?Tc(t,Ho):_c(t,Ho)}function vs(n){let e=n.rawInput;if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(typeof t.command=="string"&&t.command.trim().length>0)return ie(t.command).trim().replace(/^cd\s+\S+\s+&&\s+/,"");let s=typeof t.file_path=="string"?t.file_path:typeof t.filePath=="string"?t.filePath:typeof t.path=="string"?t.path:void 0;if(s!==void 0&&s.length>0)return Me(W(s))}if(Array.isArray(n.locations)){for(let t of n.locations)if(t&&typeof t=="object"){let s=t.path;if(typeof s=="string"&&s.length>0)return Me(W(s))}}}var Ec=["home/","Users/","root/","tmp/","var/","opt/","etc/","usr/","mnt/","private/"];function Pc(n){for(let e of Ec)if(n.startsWith(e))return!0;return!1}function Lo(n,e,t={}){if(n.length===0)return n;if(n.startsWith("/"))return Me(n);if(n.startsWith("~")||!n.includes("/")||/\s/.test(n))return n;let s=e.rawInput;if(s&&typeof s=="object"&&!Array.isArray(s)){let r=s,o=[r.file_path,r.filePath,r.path];for(let i of o)if(!(typeof i!="string"||i.length===0)&&(i===`/${n}`||i.endsWith(`/${n}`)||i===n))return Me(i)}return Pc(n)?Me(`/${n}`):t.cwd&&t.cwd.length>0?Me(mc.resolve(t.cwd,n)):n}function Tc(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function _c(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 $c(n,e={}){let t=J(n,"toolCallId")??J(n,"id");if(!t)return null;let s=J(n,"title"),r=s!==void 0?Lo(W(s),n,e):void 0,o=J(n,"status"),i=cn(n),a=Do(n);if(!(r!==void 0||i!==null||a!==void 0||o==="completed"||o==="failed"||o==="rejected"||o==="cancelled"))return null;let l=J(n,"name")??s;if(jo(l)){let g={kind:"exit-plan-mode",toolCallId:t},m=Bo(n);return m!==null&&(g.plan=m),o!==void 0&&(g.status=o),g}let d={kind:"tool-call-update",toolCallId:t};r!==void 0&&(d.title=r),a!==void 0&&(d.detail=a);let f=vs(n);f!==void 0&&(d.detailFull=f);let p=Uo(n);if(p!==void 0&&(d.locations=p),o!==void 0&&(d.status=o),i!==null&&(d.editDiff=i),o==="failed"){let g=Fc(n);g!==null&&(d.errorText=g),Oc(n,g)&&(d.upstreamInterrupted=!0)}let c=kt(n);return c!==void 0&&(d.workerTaskId=c),d}function Fc(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=At(s.content);if(o!==null&&o.length>0)return o}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"&&s.length>0)return ie(s)}return null}function Oc(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 Hc(n){let e=n.entries;if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let s of e){if(!s||typeof s!="object")continue;let r=s,o=typeof r.content=="string"?W(r.content):void 0;if(!o)continue;let i={content:o};typeof r.status=="string"&&(i.status=r.status),typeof r.priority=="string"&&(i.priority=r.priority),t.push(i)}return{kind:"plan",entries:t}}function Nc(n){let e=J(n,"currentModeId")??J(n,"currentMode")??J(n,"mode");return e?{kind:"mode-changed",mode:W(e)}:null}function jc(n){let e=J(n,"currentModel")??J(n,"model");if(!e)return null;let t=n.availableModels,s=Array.isArray(t)?t.map(r=>typeof r=="object"&&r!==null?r.modelId:typeof r=="string"?r:void 0).filter(r=>typeof r=="string"&&r.length>0):void 0;return{kind:"model-changed",model:W(e),...s&&s.length>0?{availableModels:s}:{}}}function Bc(n){let e=J(n,"stopReason"),t=n._meta,s=t?.["hydra-acp"]?.amended!==void 0&&t["hydra-acp"].amended!==null,r={kind:"turn-complete"};return e!==void 0&&(r.stopReason=e),s&&(r.amended=!0),r}function At(n){if(typeof n=="string")return ie(n);if(!n||typeof n!="object")return null;let e=n;return e.type==="text"&&typeof e.text=="string"||typeof e.text=="string"?ie(e.text):null}function Uc(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){let s=At(t);s!==null&&e.push(s)}return e.length===0?null:e.join("")}function J(n,e){let t=n[e];return typeof t=="string"?t:void 0}function qo(n){let e=new Map,t=new Map;for(let r of n){let i=r.params?.update;if(!i||typeof i!="object")continue;let a=i.sessionUpdate;if(a!=="tool_call"&&a!=="tool_call_update")continue;let u=typeof i.toolCallId=="string"&&i.toolCallId.length>0?i.toolCallId:void 0,l=Lc(i);if(l.length===0)continue;let d=l;if(u!==void 0){let f=e.get(u)??[],p=[];for(let c of l)f.some(g=>g.path===c.path&&g.oldText===c.oldText&&g.newText===c.newText)||p.push(c);if(p.length===0)continue;e.set(u,[...f,...p]),d=p}for(let f of d)Dc(t,f)}let s=[];for(let[r,o]of t)s.push({path:r,hunks:o.hunks,created:o.created});return s}function zo(n){let e=[];for(let t of n){let s=-1;for(let o=e.length-1;o>=0;o--)if(e[o].newText===t.oldText){s=o;break}if(s===-1){e.push(t);continue}let r=e[s];e.splice(s,1,{oldText:r.oldText,newText:t.newText})}return e}function Dc(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 Lc(n){let e=[],t=n.rawInput;if(t&&typeof t=="object"&&!Array.isArray(t)){let o=t,i=typeof o.file_path=="string"?o.file_path:typeof o.path=="string"?o.path:void 0,a=o.edits;if(i!==void 0&&Array.isArray(a)){for(let u of a){if(!u||typeof u!="object")continue;let l=u,d=typeof l.old_string=="string"?l.old_string:void 0,f=typeof l.new_string=="string"?l.new_string:void 0;d===void 0||f===void 0||e.push({path:i,oldText:d,newText:f})}if(e.length>0)return e}}let s=n.content;if(Array.isArray(s)){for(let o of s){if(!o||typeof o!="object")continue;let i=o;if(i.type!=="diff")continue;let a=typeof i.path=="string"?i.path:void 0;if(a===void 0)continue;let u=typeof i.oldText=="string"?i.oldText:"",l=typeof i.newText=="string"?i.newText:"";e.push({path:a,oldText:u,newText:l})}if(e.length>0)return e}let r=cn(n);return r&&r.path&&e.push({path:r.path,oldText:r.oldText,newText:r.newText}),e}function Wo(n,e={}){let t=qc(n),s=zc(t),r=[];Jc(r,n),Wc(r,t,s,e.includeTools??!1);let o=r.join(`
|
|
135
|
+
`);return o.endsWith(`
|
|
136
|
+
`)||(o+=`
|
|
137
|
+
`),o}function qc(n){let e=[];for(let t of n.history){if(t.method!=="session/update")continue;let s=t.params;if(!s||typeof s!="object")continue;let r=No(s.update,{cwd:n.session.cwd});r!==null&&e.push({event:r,recordedAt:t.recordedAt})}return e}function zc(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 Jc(n,e){let t=e.session,s=Nr(t.sessionId),r=t.title?.trim()||`Hydra session ${s}`;n.push(`# ${Xe(r)}`),n.push("");let o=[];o.push(`- **Session:** \`${s}\` (lineage \`${t.lineageId}\`)`);let i=[t.agentId];t.currentModel&&i.push(`model: ${t.currentModel}`),t.currentMode&&i.push(`mode: ${t.currentMode}`),o.push(`- **Agent:** ${i.filter(Boolean).join(" \xB7 ")}`),o.push(`- **Cwd:** ${t.cwd}`),o.push(`- **Exported:** ${e.exportedAt} from ${e.exportedFrom.machine} (hydra ${e.exportedFrom.hydraVersion})`);let a=t.currentUsage;if(a&&(a.used!==void 0||a.costAmount!==void 0)){let u=[];if(a.used!==void 0){let l=a.size!==void 0?`${bs(a.size)}`:void 0;u.push(l?`${bs(a.used)} / ${l} tokens`:`${bs(a.used)} tokens`)}if(a.costAmount!==void 0){let l=a.costCurrency??"USD";u.push(`$${a.costAmount.toFixed(2)} ${l}`)}o.push(`- **Usage:** ${u.join(" \xB7 ")}`)}n.push(o.join(`
|
|
138
|
+
`)),n.push("")}function Wc(n,e,t,s){if(!e.some(c=>Qc(c.event))){n.push("_No conversation history recorded._"),n.push("");return}let r=0,o="",i="",a=[],u=new Set,l=!1,d=()=>{if(a.length!==0){for(let c of a)n.push(c);n.push(""),a=[]}},f=()=>{d(),i.length>0&&(Jo(n,i.trimEnd(),"*"),n.push(""),i=""),o.length!==0&&(n.push(o.trimEnd()),n.push(""),o="")},p=()=>{l||(l=!0)};for(let{event:c}of e)switch(c.kind){case"user-text":{f(),n.push("---"),n.push(""),r+=1,Jo(n,c.text,"**"),n.push(""),l=!0;break}case"agent-text":p(),o+=c.text;break;case"agent-thought":{p(),o.length>0&&(n.push(o.trimEnd()),n.push(""),o=""),i+=c.text;break}case"tool-call":{if(!s||(p(),(o.length>0||i.length>0)&&f(),u.has(c.toolCallId)))break;u.add(c.toolCallId);let g=t.get(c.toolCallId)??{title:c.title,status:c.status??"pending"};a.push(`- ${Kc(g.status)} ${Vc(g)}`);break}case"tool-call-update":break;case"plan":{p(),f(),n.push("**Plan:**"),n.push("");for(let g of c.entries){let m=g.status==="completed"?"[x]":"[ ]";n.push(`- ${m} ${Xe(g.content)}`)}n.push("");break}case"mode-changed":p(),f(),n.push(`_mode: ${Xe(c.mode)}_`),n.push("");break;case"model-changed":p(),f(),n.push(`_model: ${Xe(c.model)}_`),n.push("");break;case"turn-complete":f();break;case"usage-update":case"available-commands":case"session-info":case"unknown":break}f()}function Qc(n){switch(n.kind){case"usage-update":case"available-commands":case"session-info":case"unknown":case"turn-complete":return!1;default:return!0}}function Vc(n){let e=n.status,t=e==="completed"||e===void 0?"":` _(${e})_`;return`${Xe(n.title)}${t}`}function Kc(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 Jo(n,e,t){let s=e.split(/\n\s*\n/);for(let r=0;r<s.length;r++){let o=s[r];if(o.trim().length===0)continue;let i=o.split(`
|
|
139
|
+
`);for(let a=0;a<i.length;a++){let u=i[a],l=Xe(u);n.push(a===0&&a===i.length-1?`${t}${l}${t}`:a===0?`${t}${l}`:a===i.length-1?`${l}${t}`:l)}r<s.length-1&&n.push("")}}function Xe(n){return n.replace(/</g,"<").replace(/>/g,">")}function bs(n){return n.toLocaleString("en-US")}function Qo(n){return n==="127.0.0.1"||n==="::1"||n==="localhost"||n==="[::1]"}function Gc(n){let e=n.trim();if(e.length===0)return{operator:"OR",terms:[]};let t=/\w+:"[^"]*"|"[^"]*"|\S+/g,s=[],r;for(;(r=t.exec(e))!==null;)s.push(r[0]);let o="OR",i=!1,a=!1,u=[];for(let d of s){let f=d.toUpperCase();f==="AND"?i=!0:f==="OR"?a=!0:u.push(d)}i?o="AND":a&&(o="OR");let l=u.map(d=>Yc(d)).filter(d=>d.term.length>0);return{operator:o,terms:l}}function Yc(n){let e=/^(\w+):"([^"]*)"$/.exec(n);if(e)return{scope:Vo(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:Vo(s[1]),term:s[2].trim()}:{scope:"all",term:n.trim()}}function Vo(n){switch(n.toLowerCase()){case"prompt":return"user";case"response":return"agent";case"tool":return"tool";default:return"all"}}function Xc(n,e){return n==="all"?!0:n==="user"?e==="user":n==="agent"?e==="agent"||e==="thought":e==="tool"||e==="tool-input"}var Zc=5,eu=200,Ko=30;async function Xo(n,e,t={}){let s=Gc(e);if(s.terms.length===0)return{query:e,truncated:!1,results:[]};let r=t.maxSnippetsPerSession??Zc,o=t.maxSessions??eu,i=t.sessionIds?new Set(t.sessionIds):null,a=await n.list(),u=i?a.filter(f=>i.has(f.sessionId)):a,l=[],d=!1;for(let f of u){if(l.length>=o){d=!0;break}let p=await n.loadHistory(f.sessionId).catch(()=>[]),c=tu(p,s,r);if(c.snippets.length===0)continue;let g={sessionId:f.sessionId,cwd:f.cwd,status:f.status,updatedAt:f.updatedAt,totalMatches:c.totalMatches,snippets:c.snippets};f.title!==void 0&&(g.title=f.title),l.push(g)}return{query:e,truncated:d,results:l}}function tu(n,e,t){if(e.terms.length===0)return{totalMatches:0,snippets:[]};let s=0,r=[];for(let{scope:o,term:i}of e.terms){let a=nu(n,i,o,t-r.length);if(e.operator==="AND"&&a.totalMatches===0)return{totalMatches:0,snippets:[]};s+=a.totalMatches,r.push(...a.snippets)}return{totalMatches:s,snippets:r}}function nu(n,e,t,s){let r=e.toLowerCase(),o=0,i=[];for(let a of n){let u=su(a).filter(l=>Xc(t,l.kind));for(let l of u){let d=l.text.toLowerCase(),f=d.indexOf(r);if(f===-1)continue;let p=0;for(;f!==-1;)p++,f=d.indexOf(r,f+r.length);if(o+=p,i.length<s){let c=d.indexOf(r),g={kind:l.kind,text:du(l.text,c,r.length),recordedAt:a.recordedAt};l.toolName!==void 0&&(g.toolName=l.toolName),i.push(g)}}}return{totalMatches:o,snippets:i}}function su(n){if(n.method!=="session/update")return[];let e=n.params;if(!e||typeof e!="object"||Array.isArray(e))return[];let t=e.update;if(!t||typeof t!="object"||Array.isArray(t))return[];let s=t,r=typeof s.sessionUpdate=="string"?s.sessionUpdate:s.kind;if(typeof r!="string")return[];switch(r){case"agent_message_chunk":{let o=un(s.content);return o?[{kind:"agent",text:o}]:[]}case"agent_thought":case"agent_thought_chunk":{let o=typeof s.text=="string"?ie(s.text):un(s.content);return o?[{kind:"thought",text:o}]:[]}case"user_message_chunk":{if(iu(s))return[];let o=un(s.content);return o?[{kind:"user",text:o}]:[]}case"prompt_received":{let o=au(s.prompt);return o?[{kind:"user",text:o}]:[]}case"tool_call":case"tool_call_update":return ru(s);default:return[]}}function ru(n){let e=Go(n,"name"),t=Go(n,"title"),s=[];if(t!==void 0){let a=W(t);if(a.length>0){let u={kind:"tool",text:a};e!==void 0&&(u.toolName=e),s.push(u)}}if(e!==void 0&&e!==t){let a=W(e);a.length>0&&s.push({kind:"tool",toolName:e,text:a})}let r=n.rawInput;if(r&&typeof r=="object"){let a=Yo(r);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let o=n.locations;if(Array.isArray(o)&&o.length>0){let a=Yo(o);if(a.length>0){let u={kind:"tool-input",text:W(a)};e!==void 0&&(u.toolName=e),s.push(u)}}let i=ou(n);if(i!==null){let a={kind:"tool",text:i};e!==void 0&&(a.toolName=e),s.push(a)}return s}function ou(n){let e=n.content;if(Array.isArray(e))for(let s of e){if(!s||typeof s!="object")continue;let o=s.content;if(!o||typeof o!="object")continue;let i=o;if(i.type==="text"&&typeof i.text=="string"){let a=W(i.text);if(a.length>0)return a}}let t=n.rawOutput;if(t&&typeof t=="object"){let s=t.error;if(typeof s=="string"){let r=W(s);if(r.length>0)return r}}return null}function iu(n){let e=n._meta;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e["hydra-acp"];return!t||typeof t!="object"||Array.isArray(t)?!1:t.compatFor==="prompt_received"}function un(n){if(typeof n=="string")return ie(n);if(!n||typeof n!="object"||Array.isArray(n))return"";let e=n;return typeof e.text=="string"?ie(e.text):""}function au(n){if(!Array.isArray(n))return"";let e=[];for(let t of n){let s=un(t);s.length>0&&e.push(s)}return e.join("")}function Go(n,e){let t=n[e];return typeof t=="string"?t:void 0}function Yo(n){try{return JSON.stringify(n)}catch{return""}}function du(n,e,t){let s=n.replace(/\s+/g," ").trim();if(s.length===0)return"";let r=s.toLowerCase(),o=n.slice(e,e+t).toLowerCase().replace(/\s+/g," ").trim(),i=o.length>0?r.indexOf(o):0;i===-1&&(i=0);let a=Math.max(0,i-Ko),u=Math.min(s.length,i+o.length+Ko),l=a>0?"\u2026":"",d=u<s.length?"\u2026":"";return`${l}${s.slice(a,u)}${d}`}import{randomBytes as ei}from"crypto";function Zo(n){let e=ei(32).toString("hex");return n.tokenRegistry.reserve(e).complete(n.session),n.session.onClose(()=>{n.tokenRegistry.unbind(e)}),{name:n.name,type:"http",url:`${n.getOrigin()}/mcp/${n.name}`,headers:[{name:"Authorization",value:`Bearer ${e}`}]}}function Is(n){if(n.deps.mcpTokenRegistry===void 0||n.deps.getDaemonOrigin===void 0)return;let e=n.deps.mcpTokenRegistry,t=n.deps.getDaemonOrigin;return async s=>{let r=[...n.baselineMcpServers??[]];n.stdinEnabled&&r.push(Zo({name:"hydra-acp-stdin",session:s,tokenRegistry:e,getOrigin:t})),r.push(Zo({name:"hydra-acp-recall",session:s,tokenRegistry:e,getOrigin:t}));let o=Ze(n.deps);return o!==void 0&&(o.bindToSession(s),r=[...r,...o.descriptors]),r}}function Ze(n){if(n.extensionMcp===void 0||n.mcpTokenRegistry===void 0||n.getDaemonOrigin===void 0)return;let e=n.extensionMcp.list();if(e.length===0)return;let t=ei(32).toString("hex"),s=n.mcpTokenRegistry.reserve(t),r=n.getDaemonOrigin(),o=e.map(a=>({name:a,type:"http",url:`${r}/mcp/${a}`,headers:[{name:"Authorization",value:`Bearer ${t}`}]})),i=n.mcpTokenRegistry;return{descriptors:o,bindToSession:a=>{s.complete(a),a.onClose(()=>{i.unbind(t)})},abandon:a=>s.abandon(a)}}var ln=new Set(["usage_update","tool_call","tool_call_update","prompt_received","turn_complete","permission_resolved"]);function ti(n){if(n.publicHost&&n.publicHost.length>0)return n.publicHost;if(n.host&&!Qo(n.host))return n.port!==void 0?`${n.host}:${n.port}`:n.host}function si(n,e,t,s={}){n.get("/v1/sessions",async l=>{let d=l.query,f=d?.includeNonInteractive==="1"||d?.includeNonInteractive==="true";return{sessions:await e.list({cwd:d?.cwd,includeNonInteractive:f})}}),n.get("/v1/sessions/:id",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=await e.getOne(p);return c||(d.code(404).send({error:"session not found"}),d)}),n.post("/v1/sessions/search",async(l,d)=>{let f=l.body??{},p=typeof f.q=="string"?f.q:"";if(p.trim().length===0)return d.code(400).send({error:"q is required"}),d;let c=Array.isArray(f.sessionIds)?f.sessionIds.filter(m=>typeof m=="string"&&m.length>0):void 0;return await Xo(e,p,{sessionIds:c})}),n.post("/v1/sessions",async(l,d)=>{let f=l.body??{},p=Y(f.cwd??t.cwd),c=f.agentId??t.agentId,g=Ze(s),m=g!==void 0?[...f.mcpServers??[],...g.descriptors]:f.mcpServers;try{let h=await e.create({cwd:p,agentId:c,mcpServers:m});g!==void 0&&g.bindToSession(h),d.code(201).send({sessionId:h.sessionId,agentId:h.agentId,cwd:h.cwd})}catch(h){g!==void 0&&g.abandon(h instanceof Error?h:void 0),d.code(500).send({error:h.message})}}),n.post("/v1/sessions/collect",async(l,d)=>{let f=l.body??{},p=typeof f.maxAgeDays=="number"&&f.maxAgeDays>0?f.maxAgeDays*24*60*60*1e3:0,c=typeof f.limit=="number"&&f.limit>0?f.limit:1e3,g=f.selection==="explicit"||f.selection==="unpromoted"?f.selection:"unpromoted";try{let m=await hs({manager:e,maxAgeMs:p,maxDeletions:c,selection:g,verbose:!1});d.code(200).send(m)}catch(m){d.code(500).send({error:m.message})}}),n.post("/v1/sessions/:id/kill",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p);if(c){c.close({deleteRecord:!1}).catch(()=>{}),d.code(202).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.post("/v1/sessions/:id/stdin/open",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p);if(!c)return d.code(404).send({error:"session not found"}),d;let g=l.body??{},m={};(g.mode==="memory"||g.mode==="file")&&(m.mode=g.mode),typeof g.capacityBytes=="number"&&(m.capacityBytes=g.capacityBytes),typeof g.fileCapBytes=="number"&&(m.fileCapBytes=g.fileCapBytes),(m.mode??"memory")==="file"&&(m.filePathFor=h=>ni.join(Ct.tmpdir(),`hydra-acp-stdin-${h}.log`));try{return c.openStream(m)}catch(h){return d.code(409).send({error:h.message}),d}}),n.post("/v1/sessions/:id/stdin",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p);if(!c)return d.code(404).send({error:"session not found"}),d;let g=l.body??{},m=typeof g.chunk=="string"?g.chunk:"",h=g.eof===!0;try{return c.streamWrite(m,h)}catch(v){return d.code(409).send({error:v.message}),d}}),n.patch("/v1/sessions/:id",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=l.body??{};if(c.priority!==void 0){let m=c.priority,h;if(m===null||m===0)h=void 0;else if(typeof m=="number"&&Number.isInteger(m)&&m>0)h=m;else{d.code(400).send({error:"priority must be a non-negative integer (or null to clear)"});return}if(!await e.setPriority(p,h)){d.code(404).send({error:"session not found"});return}d.code(204).send();return}if(c.regen===!0){if(!(e.get(p)!==void 0||await e.hasRecord(p))){d.code(404).send({error:"session not found"});return}e.scheduleSynopsis(p),d.code(202).send();return}if(typeof c.title!="string"||c.title.trim().length===0){d.code(400).send({error:"title must be a non-empty string"});return}if(!await e.setTitle(p,c.title)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.delete("/v1/sessions/:id",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p);if(c){await c.close({deleteRecord:!0}),await e.waitForDeletion(p),await e.hasRecord(p)&&await e.deleteRecord(p),d.code(204).send();return}if(!await e.deleteRecord(p)){d.code(404).send({error:"session not found"});return}d.code(204).send()}),n.get("/v1/sessions/:id/export",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=l.query?.tools,g=c==="references"?"references":ro(c),m=await e.exportBundle(p,g==="references"?{tools:"references"}:{});if(!m){d.code(404).send({error:"session not found"});return}let h=mt({record:m.record,history:g==="summary"?oo(m.history,"summary"):m.history,promptHistory:m.promptHistory.length>0?m.promptHistory:void 0,...m.toolBlobs!==void 0?{toolBlobs:m.toolBlobs}:{},hydraVersion:K,machine:Ct.hostname(),hydraHost:ti(t)}),v=new Date().toISOString().replace(/[:.]/g,"-");d.header("Content-Disposition",`attachment; filename="${p}-${v}.hydra"`),d.code(200).send(h)}),n.get("/v1/sessions/:id/diff",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=await e.exportBundle(p);if(!c){d.code(404).send({error:"session not found"});return}let g=l.query??{},m=g.fold==="true"||g.fold==="1",h=typeof g.paths=="string"&&g.paths.length>0?new Set(g.paths.split(",").map(y=>y.trim()).filter(y=>y.length>0)):void 0,v=qo(c.history);h&&(v=v.filter(y=>h.has(y.path))),m&&(v=v.map(y=>({...y,hunks:zo(y.hunks)}))),d.code(200).send(v)}),n.get("/v1/sessions/:id/tools/:hash",async(l,d)=>{let f=l.params,p=await e.resolveCanonicalId(f.id)??f.id,c=await e.loadToolBlob(p,f.hash);if(c===null){d.code(404).send({error:"tool blob not found"});return}d.header("Content-Type","text/plain; charset=utf-8"),d.code(200).send(c)}),n.get("/v1/sessions/:id/transcript",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=await e.exportBundle(p);if(!c){d.code(404).send({error:"session not found"});return}let g=mt({record:c.record,history:c.history,promptHistory:c.promptHistory.length>0?c.promptHistory:void 0,hydraVersion:K,machine:Ct.hostname(),hydraHost:ti(t)}),m=l.query,h=m?.tools==="1"||m?.tools==="true"||m?.tools==="yes";d.header("Content-Type","text/markdown; charset=utf-8"),d.code(200).send(Wo(g,{includeTools:h}))}),n.post("/v1/sessions/:id/fork",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=l.body??{},g={};if(c.forkAt!==void 0){if(typeof c.forkAt!="string"||c.forkAt.length===0){d.code(400).send({error:"forkAt must be a non-empty string"});return}g.forkAt=c.forkAt}if(c.cwd!==void 0){if(typeof c.cwd!="string"||c.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}g.cwd=Y(c.cwd)}if(c.agentId!==void 0){if(typeof c.agentId!="string"||c.agentId.length===0){d.code(400).send({error:"agentId must be a non-empty string"});return}g.agentId=c.agentId}if(c.title!==void 0){if(typeof c.title!="string"){d.code(400).send({error:"title must be a string"});return}g.title=c.title}if(c.mode!==void 0){if(c.mode!=="verbatim"&&c.mode!=="synthesis"){d.code(400).send({error:'mode must be "verbatim" or "synthesis"'});return}g.mode=c.mode}if(c.model!==void 0){if(typeof c.model!="string"||c.model.length===0){d.code(400).send({error:"model must be a non-empty string"});return}g.model=c.model}try{let m=await e.forkSession(p,g);d.code(201).send(m)}catch(m){let h=m;if(h.code===S.SessionNotFound){d.code(404).send({error:h.message});return}if(h.code===S.InvalidParams||h.code===S.AgentNotInstalled){d.code(400).send({error:h.message});return}d.code(500).send({error:h.message})}}),n.post("/v1/sessions/import",async(l,d)=>{let f=l.body??{};if(f.bundle===void 0){d.code(400).send({error:"missing bundle"});return}let p;if(f.cwd!==void 0){if(typeof f.cwd!="string"||f.cwd.length===0){d.code(400).send({error:"cwd must be a non-empty string"});return}p=f.cwd}let c;try{c=go(f.bundle)}catch(g){d.code(400).send({error:"invalid bundle",details:g.message});return}try{let g=await e.importBundle(c,{replace:f.replace===!0,...p!==void 0?{cwd:p}:{}});d.code(201).send(g)}catch(g){let m=g;if(m.code===S.BundleAlreadyImported){d.code(409).send({error:"bundle already imported",existingSessionId:m.existingSessionId});return}d.code(500).send({error:m.message})}}),n.get("/v1/sessions/:id/compact/status",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p),g;if(c?g=c.summarizedThroughEntry:g=await e.getSummarizedThroughEntry(p),g===void 0&&!await e.hasRecord(p))return d.code(404).send({error:"session not found"}),d;let m=await e.getCompactionState(p),h=await e.getRollbackBreadcrumb(p),v=!1,y,b=await e.getHistory(p).catch(()=>[])??[];if(b.length>0&&t.compaction){let A=g??0,x=b.length,T=b.slice(A).reduce((P,j)=>P+JSON.stringify(j.params).length,0);y=ws(T);let _=c?.currentModel,U=b.at(-1).recordedAt,$=c?.currentUsage;v=Fo({summarizedThroughEntry:A,totalEntries:x,unsummarizedChars:T,compactionInFlight:e.getCompactionInFlight(),currentModel:_,lastActivityMs:U,nowMs:Date.now(),config:t.compaction,...typeof $?.used=="number"?{agentReportedUsed:$.used}:{},...typeof $?.size=="number"?{agentReportedSize:$.size}:{}})}return{summarizedThroughEntry:g??void 0,inFlight:e.getCompactionInFlight(),shouldCompact:v,...y!=null?{approxTokens:y}:{},...m!=null?{compactionState:m}:{},...h!=null?{rollbackBreadcrumb:h}:{}}}),n.post("/v1/sessions/:id/compact",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f;if(e.get(p)){e.scheduleCompaction(p),d.code(202).send({scheduled:!0});return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}e.scheduleCompaction(p),d.code(202).send({scheduled:!0})}),n.post("/v1/sessions/:id/compact/rollback",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f;if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}try{await e.performUncompact(p),d.code(202).send({rolledBack:!0})}catch(c){let g=c instanceof Error?c.message:String(c);d.code(409).send({error:g})}}),n.get("/v1/sessions/:id/history",async(l,d)=>{let f=l.params.id,p=l.query,c=p?.follow==="1"||p?.follow==="true",g=await e.resolveCanonicalId(f)??f,m=e.get(g),h,v,y=!1,w=1e4,b=[];if(m){c&&(v=m.onBroadcast(x=>{d.raw.writableEnded||(y?d.raw.write(JSON.stringify(x)+`
|
|
140
|
+
`):(b.push(x),b.length>w&&b.shift()))})),l.raw.on("close",()=>{v?.(),d.raw.writableEnded||d.raw.end()});try{h=await m.getHistorySnapshot()}catch(x){throw v?.(),x}}else{let x=await e.getHistory(g);if(x===void 0)return d.code(404).send({error:"session not found"}),d;h=x}d.raw.setHeader("Content-Type","application/x-ndjson"),d.raw.setHeader("Cache-Control","no-cache"),d.raw.statusCode=200;let A=new Set;for(let x of h??[]){d.raw.write(JSON.stringify(x)+`
|
|
142
141
|
`);let C=x;typeof C.recordedAt=="number"&&A.add(String(C.recordedAt))}for(;b.length>0;){let x=b.splice(0,b.length);for(let C of x){let T=C,_=typeof T.recordedAt=="number"?String(T.recordedAt):"";_&&A.has(_)||d.raw.write(JSON.stringify(C)+`
|
|
143
|
-
`)}}return y=!0,v||d.raw.end(),d});function r(
|
|
144
|
-
`),await
|
|
145
|
-
`)}}catch(x){if(x.code==="ENOENT")return d.raw.end(),d;throw x}return d.raw.end(),d}),n.get("/v1/sessions/:id/attention",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,l=e.get(p);return!l&&!await e.hasRecord(p)?(d.code(404).send({error:"session not found"}),d):l?{flags:l.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(u,d)=>{let f=u.query;if(!f.source||f.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let p=await e.list({includeNonInteractive:!0}),l=[];for(let m of p){let g=e.get(m.sessionId),h;g?h=g.listAttentionFlags():h=(await e.store.read(m.sessionId))?.attentionFlags??[];for(let v of h)v.source===f.source&&l.push({...v,sessionId:m.sessionId})}return{flags:l}}),n.post("/v1/sessions/:id/attention/clear",async(u,d)=>{let f=u.params.id,p=await e.resolveCanonicalId(f)??f,m=u.body??{},g=typeof m.source=="string"?m.source:"",h=typeof m.reason=="string"?m.reason:"";if((g.length>0||h.length>0)&&!(g.length>0&&h.length>0)){d.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}g.length===0&&h.length;let v=e.get(p);if(v){if(g.length>0&&h.length>0)v.clearAttentionFlag(g,h);else{let x=Array.from(v.listAttentionFlags()).map(C=>`${C.source}::${C.reason}`);for(let C of x)v.clearAttentionFlag(C.split("::")[0],C.split("::").slice(1).join("::"))}d.code(204).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}let y=e.store,w=await y.read(p);if(!w){d.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(g.length>0&&h.length>0){let x=`${g}::${h}`;A=b.filter(C=>`${C.source}::${C.reason}`!==x)}else A=[];if(A.length===b.length&&A.every((x,C)=>x.source===b[C].source&&x.reason===b[C].reason)){d.code(204).send();return}await y.write({...w,attentionFlags:A}),d.code(204).send()})}function si(n,e,t,s={}){n.get("/v1/agents",async()=>je(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let c=await te(a,[],{npmRegistry:s.npmRegistry}),u=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:c.version,distribution:u,installed:!0,command:c.command})}catch(c){o.code(500).send({error:c.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:c}=await t.syncFromAgent(i);return{synced:a.map(u=>({sessionId:u.sessionId,upstreamSessionId:u.upstreamSessionId,agentId:u.agentId,cwd:u.cwd,title:u.title,updatedAt:u.updatedAt})),skipped:c}}catch(a){let c=a;if(c.code===I.AgentNotInstalled){o.code(404).send({error:c.message});return}o.code(409).send({error:c.message})}})}function ri(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var au=/^[A-Za-z0-9._-]+$/;function fn(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,c=t.get(a);if(!c){i.code(404).send({error:`unknown ${e}: ${a}`});return}return c}),n.post(r,async(o,i)=>{let a=o.body??{},c=du(a);if("error"in c){i.code(400).send({error:c.error});return}try{let u=t.register(c.config);i.code(201).send(u)}catch(u){xt(i,u)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(c){xt(i,c)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let c=await t.startByName(a);i.code(200).send(c)}catch(c){xt(i,c)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let c=await t.stopByName(a);i.code(200).send(c)}catch(c){xt(i,c)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let c=await t.restartByName(a);i.code(200).send(c)}catch(c){xt(i,c)}})}function xt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function du(n){let e=n.name;if(typeof e!="string"||!au.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function oi(n,e){fn(n,"extension",e)}function ii(n,e){fn(n,"transformer",e)}function ai(n,e){n.get("/v1/config",async()=>e)}import{z as tt}from"zod";import*as et from"fs/promises";import*as di from"path";import{randomBytes as kg,scrypt as cu,timingSafeEqual as uu}from"crypto";import{promisify as lu}from"util";var fu=lu(cu);function ci(){return di.join(S.home(),"password-hash")}var pu=128*1024*1024;async function ui(){try{return(await et.readFile(ci(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function li(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await et.readFile(ci(),"utf8")).trim()}catch(u){if(u.code==="ENOENT")return!1;throw u}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let c=await fu(n,i,a.length,{N:s,r,p:o,maxmem:pu});return c.length!==a.length?!1:uu(c,a)}var mu=tt.object({password:tt.string().min(1),label:tt.string().min(1).max(256).optional(),ttlSec:tt.number().int().positive().optional()}),gu=tt.object({id:tt.string().optional()}).optional();function fi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=hu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=mu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await ui())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await li(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=gu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function hu(n){return n.ip||"unknown"}import{nanoid as Cs}from"nanoid";function As(n){let e=[],t=[],s=!1,r=o=>{if(!s){s=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let c=JSON.parse(a);for(let u of e)u(c)}catch(c){for(let u of e)u({jsonrpc:"2.0",id:null,error:{code:I.ParseError,message:`Failed to parse WS frame: ${c.message}`}})}}),n.on("close",()=>r()),n.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,c)=>{n.send(i,u=>{if(u){c(u);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){s||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(c),o())},c=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as mi}from"crypto";import*as gi from"os";import*as hi from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function Iu(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,o=s.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=s.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let c=a;if(typeof c.text=="string"&&(r+=c.text.length),c.content&&typeof c.content=="object"){let u=c.content;typeof u.text=="string"&&(r+=u.text.length)}}return r}function se(n,e,t){let s=n.get(e);if(!s)throw E(I.SessionNotFound,t??`session ${e} not found`);return s}async function pn(n,e){let t=Ze(n),s,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=mi(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],c=Is({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),u;try{u=await n.manager.resurrect({...e,mcpServers:a,...c?{mintMcpServersForSwap:c}:{}})}catch(d){throw t!==void 0&&t.abandon(d instanceof Error?d:void 0),r!==void 0&&r.abandon(d instanceof Error?d:void 0),d}if(t!==void 0&&t.bindToSession(u),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let d=s,f=n.mcpTokenRegistry;r.complete(u),u.onClose(()=>{f.unbind(d)})}return Pu(u,n),wi(u.sessionId,n),u}function yi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=$o({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=As(t),a=new Ee(i),c={clientId:`hydra_client_${Cs(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of c.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);c.attached.clear()});let u=(f,p)=>{if(c.attached.get(f)?.readonly)throw E(I.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=ar.parse(f??{});p.clientInfo?.name&&(c.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let l=p.clientInfo?.version;return l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l)),Eu()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let l=p??{},m=Array.isArray(l.commands)?l.commands.map(g=>{if(!g||typeof g!="object")return;let h=g;if(typeof h.verb!="string")return;let v={verb:h.verb};return typeof h.argsHint=="string"&&(v.argsHint=h.argsHint),typeof h.description=="string"&&(v.description=h.description),v}).filter(g=>g!==void 0):[];return f.register(o.name,a,m),{ok:!0,registered:m.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async l=>{let m=l??{},g=typeof m.instructions=="string"?m.instructions:void 0,h=Array.isArray(m.tools)?m.tools.map(v=>{if(!v||typeof v!="object")return;let y=v;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let w={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(w.outputSchema=y.outputSchema),w}).filter(v=>v!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,g,h),{ok:!0,registered:h.length}});let p=l=>{let m=l??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw E(I.InvalidParams,"sessionId is required");return m.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(m,o.name,g.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async l=>{let m=p(l);if(!e.manager)throw E(I.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(m,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(g.value===void 0)throw E(I.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(I.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(m,o.name,g.key,g.value)}catch(h){throw E(I.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async l=>{let m=p(l),g=l??{};if(typeof g.key!="string"||g.key.length===0)throw E(I.InvalidParams,"key is required");if(!e.manager)throw E(I.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(m,o.name,g.key),{ok:!0}}),e.extensionMcpControls){let l=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async m=>{let g=m??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(I.InvalidParams,"refresh_session requires sessionId");return await l.notifyToolListChanged(g.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let l=p??{},m=Array.isArray(l.intercepts)?l.intercepts.filter(g=>typeof g=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,m),e.manager?.defaultTransformers.includes(o.name))){let g=e.transformers.resolveChain([o.name])[0];if(g)for(let h of e.manager.liveSessions())h.addTransformer(g)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0,g=typeof l.method=="string"?l.method:void 0,h=l.envelope,v=l.route;if(!m)throw E(-32602,"emit_message requires sessionId");if(!g&&v!=="client_broadcast")throw E(-32602,"emit_message requires method");let y=se(e.manager,m),w=typeof l.respondsTo=="string"?l.respondsTo:void 0;if(w)return y.dischargeClaim(w,h),{ok:!0};if(v==="chain")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="queue"){if(g!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,h)}}if(v==="daemon")return{ok:!0,response:await y.emitToChain(o.name,g,h)};if(v==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(v)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let l=p??{},m=typeof l.sessionId=="string"?l.sessionId:void 0;if(!m)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,m).requestPermissionFromClients(l)}),a.onRequest("hydra-acp/transformer/attach",async p=>Cu(p,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let l=p??{},m=typeof l.agentId=="string"?l.agentId:e.defaultAgent,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.parentSessionId=="string"?l.parentSessionId:void 0,v=l._meta&&typeof l._meta=="object"?l._meta:void 0,y=v&&v["hydra-acp"]&&typeof v["hydra-acp"]=="object"?v["hydra-acp"]:void 0,w=y&&typeof y.title=="string"?y.title:void 0,b=y&&typeof y.model=="string"?y.model:void 0;if(!g&&h){let C=e.manager.get(h);C&&(g=C.cwd)}if(!g)throw E(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof l.interactive=="boolean"?l.interactive:!1;return{childSessionId:(await e.manager.create({agentId:m,cwd:g,parentSessionId:h,interactive:A,transformChain:[],title:w,model:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"fork_session requires sessionId");let m=typeof l.forkAt=="string"?l.forkAt:void 0,g=typeof l.cwd=="string"?l.cwd:void 0,h=typeof l.agentId=="string"?l.agentId:void 0,v=typeof l.mode=="string"&&(l.mode==="verbatim"||l.mode==="synthesis")?l.mode:void 0,y=typeof l.model=="string"&&l.model.length>0?l.model:void 0;return await e.manager.forkSession(l.sessionId,{...m!==void 0?{forkAt:m}:{},...g!==void 0?{cwd:g}:{},...h!==void 0?{agentId:h}:{},...v!==void 0?{mode:v}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("session/fork",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/fork requires sessionId");let m=typeof l.cwd=="string"?l.cwd:void 0;return{sessionId:(await e.manager.forkSession(l.sessionId,{...m!==void 0?{cwd:m}:{},mode:"verbatim"})).sessionId}});let f=async(p,l)=>{let m=p??{};if(typeof m.sessionId!="string")throw E(I.InvalidParams,`${l} requires sessionId`);let g=await e.manager.resolveCanonicalId(m.sessionId)??m.sessionId,h=e.manager.get(g);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(g),await e.manager.hasRecord(g)&&await e.manager.deleteRecord(g),{id:g,existed:!0};let v=await e.manager.deleteRecord(g);return{id:g,existed:v}};a.onRequest("session/delete",async p=>(await f(p,"session/delete"),{})),a.onRequest("session/close",async p=>{let l=p??{};if(typeof l.sessionId!="string")throw E(I.InvalidParams,"session/close requires sessionId");u(l.sessionId,"session/close");let m=await e.manager.resolveCanonicalId(l.sessionId)??l.sessionId,g=e.manager.get(m);if(g)return await g.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(m))return{};throw E(I.SessionNotFound,`session ${m} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:l,existed:m}=await f(p,"hydra-acp/session/delete");if(!m)throw E(I.SessionNotFound,`session ${l} not found`);return{deleted:!0,sessionId:l}}),a.onRequest("hydra-acp/child_session/await",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0,g=l.until==="idle"?"idle":"turn_complete",h=typeof l.timeoutMs=="number"?Math.min(l.timeoutMs,18e5):3e5;if(!m)throw E(-32602,"await_child requires childSessionId");let v=se(e.manager,m,`child session ${m} not found`);return new Promise(y=>{let A=[],x=[],C=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(j),_?.(),U?.(),y(T?{entries:A,truncated:!0}:{entries:A}))};_=v.onBroadcast(z=>{let oe=Iu(z);for(A.push(z),x.push(oe),C+=oe;A.length>0&&(A.length>1e3||C>1048576);)A.shift(),C-=x.shift()??0,T=!0;g==="turn_complete"&&z.params?.update?.sessionUpdate==="turn_complete"&&P()});let j=setTimeout(P,h);typeof j.unref=="function"&&j.unref(),U=v.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let l=p??{},m=typeof l.childSessionId=="string"?l.childSessionId:void 0;if(!m)throw E(-32602,"close_child_session requires childSessionId");let g=e.manager.get(m);return g&&await g.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async p=>xu(p,o.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>Mu(p,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let l=p??{},m=typeof l.token=="string"?l.token:void 0,g=typeof l.sessionId=="string"?l.sessionId:void 0,h=typeof l.estimatedRemainingMs=="number"?l.estimatedRemainingMs:void 0;return m&&g&&e.manager.get(g)?.keepAliveClaim(m,h),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let p=f??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw E(I.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let l=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,m=await e.manager.loadToolBlob(l,p.hash);if(m===null)throw E(I.SessionNotFound,"tool content not found");return{content:m}}),a.onRequest("authenticate",async f=>Su(f,e)),a.onRequest("logout",async f=>ku(f,e)),a.onRequest("session/new",async f=>{let p=dr.parse(f),l=at(f?._meta),m=Array.isArray(l.transformers)&&l.transformers.every(P=>typeof P=="string")?l.transformers:e.manager.defaultTransformers??[],g=e.transformers?.resolveChain(m)??[],h,v,y=p.mcpServers;if(l.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=mi(32).toString("hex"),v=e.mcpTokenRegistry.reserve(h);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};y=[...p.mcpServers??[],j]}let w,b,A=Ze(e);A!==void 0&&(y=[...y??[],...A.descriptors]);let x=Is({baselineMcpServers:p.mcpServers,stdinEnabled:l.mcpStdin===!0,deps:e}),C;try{C=await e.manager.create({cwd:p.cwd,agentId:l.agentId??e.defaultAgent,mcpServers:y,title:l.title,agentArgs:l.agentArgs,model:l.model,onInstallProgress:pi(a),transformChain:g,originatingClient:c.clientInfo,...l.interactive!==void 0?{interactive:l.interactive}:{},...l.env!==void 0?{forwardedEnv:l.env}:{},...x?{mintMcpServersForSwap:x}:{}})}catch(P){throw v!==void 0&&v.abandon(P instanceof Error?P:void 0),b!==void 0&&b.abandon(P instanceof Error?P:void 0),A!==void 0&&A.abandon(P instanceof Error?P:void 0),P}if(h!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,j=e.mcpTokenRegistry;v.complete(C),C.onClose(()=>{j.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,j=e.mcpTokenRegistry;b.complete(C),C.onClose(()=>{j.unbind(P)})}A!==void 0&&A.bindToSession(C),wi(C.sessionId,e);let T,_;try{yn(c,C,C.sessionId),T=Mt(a,C,c),{entries:_}=await C.attach(T,"full")}catch(P){throw await C.close({deleteRecord:!1}).catch(()=>{}),P}c.attached.set(C.sessionId,{sessionId:C.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=mn(C),$=gn(C);return{sessionId:C.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:C.buildConfigOptions(),_meta:hn(e.manager,C,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=ur.parse(f),l=p.clientInfo?.version;l&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,l):e.onTransformerVersion?.(o.name,l));let m=at(p._meta),g=m.resume,h=m.readonly===!0,v=m.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!g} readonly=${h}`);let y=g?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(y);if(!w&&h){let $=await e.manager.loadFromDisk(y);if(!$)throw E(I.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(y),j=p.clientId??`cli_${Cs(8)}`;c.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${j} attachedCount=${c.attached.size} replayed=${P.length}`);for(let z of P)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:P.length,_meta:Ru($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(y),P=$;if(g&&(P={...$,hydraSessionId:p.sessionId,upstreamSessionId:g.upstreamSessionId,agentId:g.agentId,cwd:g.cwd,...g.title!==void 0?{title:g.title}:{},...g.agentArgs!==void 0?{agentArgs:g.agentArgs}:{}}),!P)throw E(I.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(I.SessionNotFound,`session ${p.sessionId} was deleted`);let j=P.originatingClient?P:{...P,originatingClient:c.clientInfo},z=v!==void 0?{...j,forwardedEnv:v}:j;w=await pn(e,{...z,onInstallProgress:pi(a)})}yn(c,w,w.sessionId);let A=Mt(a,w,c,p.clientInfo,p.clientId),x=m.replayMode==="drip",{entries:C,appliedPolicy:T}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:x,...m.toolContent!==void 0?{toolContent:m.toolContent}:{}});if(c.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),v!==void 0&&await e.manager.setForwardedEnv(w.sessionId,v).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${c.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${C.length} readonly=${h}${x?" replayMode=drip":""}`),x){let $=m.dripSpeed&&m.dripSpeed>0?m.dripSpeed:1,P=750;(async()=>{let j=null;for(let z of C){let oe=typeof z.recordedAt=="number"?z.recordedAt:null;if(j!==null&&oe!==null){let $e=Math.min(P,Math.max(0,(oe-j)/$));$e>0&&await new Promise(Rt=>setTimeout(Rt,$e))}oe!==null&&(j=oe);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let $=0;$<C.length&&!a.isClosed();$++){let P=C[$],j=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await j}w.replayPendingPermissions(A);let _=mn(w),U=gn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:C.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:hn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=lr.parse(f),l=c.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"client not attached to that session");let m=e.manager.get(p.sessionId);return m?.detach(l.clientId),c.attached.delete(p.sessionId),m&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[it]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=fr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Lt).map(pr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(I.InternalError,"agent registry unavailable");return je(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let p=f??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw E(I.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(p.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let p=mr.parse(f);u(p.sessionId,"session/prompt");let l=c.attached.get(p.sessionId);if(!l)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...c.attached.keys()].join(",")}]`),E(I.SessionNotFound,"not attached to session");let m=e.manager.get(p.sessionId);if(!m){let g=await e.manager.loadFromDisk(p.sessionId);if(!g)throw E(I.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),m=await pn(e,g);let h=Mt(a,m,c,void 0,l.clientId);await m.attach(h,"none")}return m.prompt(l.clientId,p)});let d=f=>{let p;try{p=Ot.parse(f)}catch(g){n.log.warn(`session/cancel: invalid params: ${g.message}`);return}let l=c.attached.get(p.sessionId);if(!l)return;if(l.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let m=e.manager.get(p.sessionId);m&&m.cancel(l.clientId).catch(g=>{n.log.warn(`session/cancel for ${p.sessionId}: ${g.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async f=>{let p=Ot.parse(f);return u(p.sessionId,"session/cancel"),d(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=hr.parse(f);return u(p.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=Ot.parse(f);return u(p.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=yr.parse(f);return u(p.sessionId,"hydra-acp/prompt/update"),se(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let p=wr.parse(f);u(p.sessionId,"hydra-acp/prompt/amend");let l=c.attached.get(p.sessionId);if(!l)throw E(I.SessionNotFound,"not attached to session");return se(e.manager,p.sessionId).amendPrompt(l.clientId,p)}),a.onRequest("session/resume",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/resume requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let w=await e.manager.loadFromDisk(m);if(!w)throw E(I.SessionNotFound,`session ${l} not found in memory or on disk`);g=await pn(e,w)}yn(c,g,g.sessionId);let h=Mt(a,g,c);await g.attach(h,"pending_only"),c.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1}),g.replayPendingPermissions(h);let v=mn(g),y=gn(g);return{sessionId:g.sessionId,...v?{modes:v}:{},...y?{models:y}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/load",async f=>{let p=f??{},l=typeof p.sessionId=="string"?p.sessionId:void 0;if(!l)throw E(I.InvalidParams,"session/load requires sessionId");let m=await e.manager.resolveCanonicalId(l)??l,g=e.manager.get(m);if(!g){let b=await e.manager.loadFromDisk(m);if(!b)throw E(I.SessionNotFound,`session ${l} not found in memory or on disk`);g=await pn(e,b)}yn(c,g,g.sessionId);let h=Mt(a,g,c),{entries:v}=await g.attach(h,"pending_only");c.attached.set(g.sessionId,{sessionId:g.sessionId,clientId:h.clientId,readonly:!1});for(let b of v){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}g.replayPendingPermissions(h);let y=mn(g),w=gn(g);return{sessionId:g.sessionId,...y?{modes:y}:{},...w?{models:w}:{},configOptions:g.buildConfigOptions(),_meta:hn(e.manager,g,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&u(p,"session/set_model");let l=Au(f,e.manager);if(l.kind==="error")throw n.log.warn(l.logMessage),E(l.code,l.message);if(l.kind==="no_op")return n.log.warn(l.logMessage),await a.notify("session/update",{sessionId:l.sessionId,update:{sessionUpdate:"current_model_update",currentModel:l.currentModel}}).catch(()=>{}),null;n.log.info(l.logMessage);let{modelId:m}=l,g=await l.session.forwardRequest("session/set_model",{...f,modelId:m});return l.session.applyModelChange(m),g}),a.onRequest("session/set_mode",async f=>{let p=f,l=p?.sessionId;if(typeof l=="string"&&u(l,"session/set_mode"),!p||typeof p.sessionId!="string")throw E(I.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(I.InvalidParams,"session/set_mode requires string modeId");let m=se(e.manager,p.sessionId),g=await m.forwardRequest("session/set_mode",f);return m.applyModeChange(p.modeId),g}),a.onRequest("session/set_config_option",async f=>{let p=f,l=v=>E(I.InvalidParams,v),m=p?.sessionId;if(typeof m=="string"&&u(m,"session/set_config_option"),!p||typeof p.sessionId!="string")throw l("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw l("session/set_config_option requires string configId");if(typeof p.value!="string")throw l("session/set_config_option requires string value");let g=se(e.manager,p.sessionId),h=g.buildConfigOptions().find(v=>v.id===p.configId);if(!h)throw l(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(v=>v.value===p.value))throw l(`value ${JSON.stringify(p.value)} is not valid for configId ${JSON.stringify(p.configId)}`);switch(p.configId){case"model":{p.value!==g.currentModel&&await g.forwardRequest("session/set_model",{sessionId:p.sessionId,modelId:p.value}),g.applyModelChange(p.value);break}case"mode":{p.value!==g.currentMode&&await g.forwardRequest("session/set_mode",{sessionId:p.sessionId,modeId:p.value}),g.applyModeChange(p.value);break}case"agent":{p.value!==g.agentId&&await g.setAgent(p.value);break}default:throw l(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:g.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let l=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),m=p.startsWith("session/"),g=p.startsWith("hydra-acp/");if(!m&&!g||f===null||typeof f!="object"||l.has(p))throw E(I.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(I.MethodNotFound,`Method not found: ${p}`);return u(h,p),se(e.manager,h).forwardRequest(p,f)})})}async function Su(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(I.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let l=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(l)}let c=a.authMethods??[],u=c.find(l=>l.id===s);if(!u){let l=c.map(m=>m.id);throw E(I.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${l.map(m=>JSON.stringify(m)).join(", ")}]`)}let d=u._meta?.type,f=(()=>{let l=u._meta?.["terminal-auth"];if(l&&typeof l=="object"&&!Array.isArray(l))return l})();if((u.type??(d==="agent"||d==="terminal"?d:f!==void 0?"terminal":"agent"))==="terminal"){let l=(w,b)=>{if(!Array.isArray(w))throw E(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw E(I.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be string[]; got non-string entry ${JSON.stringify(A)}`);return w},m=await e.manager.planSpawnForAgent(a.agentId),g,h;if(f?.args!==void 0){let w=typeof f.command=="string"?f.command:void 0;g=w!==void 0&&hi.isAbsolute(w)?w:m.command,h=l(f.args,'_meta["terminal-auth"].args')}else{let w=u.args!==void 0?{raw:u.args,label:"args"}:u._meta?.args!==void 0?{raw:u._meta.args,label:"_meta.args"}:void 0,b=w!==void 0?l(w.raw,w.label):[];g=m.command,h=[...m.args,...b]}let v={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(v[w]=b);Object.assign(v,m.env);let y=gi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:g,args:h,env:v,cwd:y}}try{return await a.connection.request("authenticate",{methodId:s})}catch(l){throw Ce(l,a)}}async function ku(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,o=typeof s?.agentId=="string"?s.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function pi(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(vr,t).catch(()=>{})}}function mn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function gn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function Au(n,e){if(!n||typeof n!="object")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires params",logMessage:"session/set_model rejected: params not an object"};let t=n;if(typeof t.sessionId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string sessionId",logMessage:"session/set_model rejected: missing/non-string sessionId"};if(typeof t.modelId!="string")return{kind:"error",code:I.InvalidParams,message:"session/set_model requires string modelId",logMessage:`session/set_model rejected: missing/non-string modelId sessionId=${t.sessionId}`};let s=e.get(t.sessionId);if(!s)return{kind:"error",code:I.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=ze(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(c=>c.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:I.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function Cu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(I.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(I.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw E(I.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function xu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(I.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function Mu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(I.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw E(I.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function Ru(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[it]:Ft(e,t)}}function hn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return ot(e.agentMeta,Ft(s,r))}function Eu(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:ot(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function Pu(n,e){if(!(!e.transformers||!e.manager))for(let t of e.manager.defaultTransformers){let s=e.transformers.resolveChain([t])[0];s&&n.addTransformer(s)}}function wi(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Mt(n,e,t,s,r){return{clientId:r??`cli_${Cs(8)}`,connection:n,clientInfo:s}}function yn(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var wn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((i,a)=>{t=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as Tu}from"crypto";import{McpServer as _u}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as $u}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as G}from"zod";function*xs(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;if(s.method!=="session/update")continue;let o=s.params?.update;!o||typeof o.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:o.sessionUpdate,update:o})}}function re(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var vi="Bearer ";function nt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(vi))return;let t=e.slice(vi.length).trim();return t.length>0?t:void 0}function Fu(n){let e=new _u({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:G.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return re(s)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:G.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return re(s)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:G.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:G.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:G.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let o=await n.streamRead(t,s,r);return re(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:G.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:G.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),o=n.streamInfo();return re({outcome:r,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:G.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:G.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:G.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:G.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:G.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:G.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:G.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:G.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:G.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return re(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return re(t)}),e}var Ou=1e4;function bi(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let u=Fu(a),d=new $u({sessionIdGenerator:()=>Tu()});await u.connect(d);let f={server:u,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await u.close()}catch{}}),d}async function r(i,a){let c=nt(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(c);if(u===void 0){a.code(404).send({error:"unknown stdin token"});return}let d;if(u.session!==void 0)d=u.session;else{let p,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Ou)}),m=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0){a.code(503).send({error:"session not ready"});return}d=m}let f=await s(c,d);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as Hu}from"crypto";import{McpServer as Nu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as ju}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function Bu(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Uu(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function Du(n){let e=new Nu({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:xe.string().min(1).describe("Case-insensitive substring to search for."),limit:xe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:xe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=await o.getHistorySnapshot(),a=[];for(let{entryId:u,entry:d,kind:f}of xs(i)){if(f==="tool_call"&&!r)continue;let p=Je([d]),l=p.toLowerCase().indexOf(t.toLowerCase());if(l<0)continue;let m=Bu(f),g=Uu(p,l),h=typeof d.recordedAt=="number"?String(d.recordedAt):void 0;if(a.push({entryId:u,speaker:m,snippet:g,timestamp:h}),a.length>=s)break}let c=a.length>=s&&a.length<i.length;return re({matches:a,total_matched:a.length,truncated:c})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:xe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:xe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return re({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let o=s-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getHistorySnapshot(),a=Math.min(t,i.length-1),c=Math.min(s,i.length-1),u=a>t||c<s;if(a>c)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:u}};let d=i.slice(a,c+1),f=Je(d);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:d.length,truncated:u}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:xe.string().optional(),file_path:xe.string().optional(),limit:xe.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let i=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!i&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let c=await o.getHistorySnapshot(),u=[],d=new Map;for(let{entryId:l,entry:m,kind:g,update:h}of xs(c)){if(g!=="tool_call"&&g!=="tool_call_update")continue;let v=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${l}`,y=d.get(v);y||(y={entryId:l,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,y),u.push(v)),typeof h.name=="string"&&h.name.length>0?y.toolName=h.name:(y.toolName==="(unnamed)"||g==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(y.toolName=h.title);let w=h.rawInput;if(w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0)for(let[b,A]of Object.entries(w))y.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!y.locations.includes(A)&&y.locations.push(A)}typeof h.status=="string"&&(y.status=h.status),m.recordedAt!==void 0&&y.timestamp===void 0&&(y.timestamp=String(m.recordedAt))}let f=[];for(let l of u){let m=d.get(l);if(t!==void 0&&m.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),v=["file_path","filePath","path"],y=!1;for(let w of v){let b=m.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){y=!0;break}}if(!y){for(let w of m.locations)if(w.toLowerCase().includes(h)){y=!0;break}}if(!y)continue}let g={};for(let[h,v]of Object.entries(m.rawInput))typeof v=="string"?g[h]=v.length>500?v.slice(0,497)+"\u2026":v:(typeof v=="number"||typeof v=="boolean")&&(g[h]=v);if(m.locations.length>0&&g.locations===void 0&&(g.locations=m.locations),f.push({entryId:m.entryId,tool:m.toolName,args:g,status:m.status,timestamp:m.timestamp}),f.length>=r)break}let p=f.length>=r;return re({calls:f,truncated:p})}),e}var Lu=1e4;function Ii(n,e){let t=new Map;async function s(i,a){let c=t.get(i);if(c!==void 0)return c.transport;let u=Du(a),d=new ju({sessionIdGenerator:()=>Hu()});await u.connect(d);let f={server:u,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await u.close()}catch{}}),d}async function r(i,a){let c=nt(i);if(c===void 0){a.code(401).send({error:"missing bearer token"});return}let u=e.lookup(c);if(u===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(c,async()=>{if(u.session!==void 0)return u.session;let p,l=new Promise(g=>{p=setTimeout(()=>g(void 0),Lu)}),m=await Promise.race([u.sessionReady.catch(()=>{}),l]);if(p!==void 0&&clearTimeout(p),m===void 0)throw new Error("recall: session not ready");return m});a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var vn=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Gu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Yu}from"crypto";import{Server as qu}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as zu,ListToolsRequestSchema as Ju}from"@modelcontextprotocol/sdk/types.js";function Si(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,o=new qu({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(Ju,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let c=await s.fetchSessionTools(a);if(c!==void 0)return{tools:c.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(zu,async(a,c)=>{let u=a.params.name,d=c._meta?.progressToken??c.requestId,f=Qu(d,c.sendNotification);try{let p=await r(),l=await Vu(e.connection,n,u,a.params.arguments??{},p);return Ku(l,u)}catch(p){return Ms(p instanceof Error?p.message:String(p))}finally{f()}}),o}var Wu=15e3;function Qu(n,e,t=Wu){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function Vu(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function Ku(n,e){if(n===null||typeof n!="object")return Ms(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Ms(`extension ${e} omitted content array`)}function Ms(n){return{content:[{type:"text",text:n}],isError:!0}}var Xu=1e4;function ki(n,e,t){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function o(d){for(let f of s.values()){let p=f.get(d);p!==void 0&&(f.delete(d),r(p))}}async function i(d,f){for(let[p,l]of s){if(e.lookup(p)?.session?.sessionId!==d)continue;let g=l.get(f);if(g!==void 0)try{await g.server.sendToolListChanged()}catch{}}}t.onChange(d=>{o(d)});async function a(d,f){let p=s.get(d);p===void 0&&(p=new Map,s.set(d,p),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let A of b.values())await r(A)}}));let l=p.get(f);if(l!==void 0)return l.transport;let m=t.lookup(f);if(m===void 0)return;let y=Si(f,m,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,x=new Promise(T=>{A=setTimeout(()=>T(void 0),Xu)}),C=await Promise.race([b.sessionReady.catch(()=>{}),x]);if(A!==void 0&&clearTimeout(A),C===void 0)throw new Error("session not ready");return C.sessionId},{peekSessionId:()=>e.lookup(d)?.session?.sessionId,fetchSessionTools:async b=>{let A=await m.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!A||typeof A!="object")return;let x=A.tools;if(!Array.isArray(x))return;let C=[];for(let T of x){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),C.push(U)}return C}}),w=new Gu({sessionIdGenerator:()=>Yu()});return await y.connect(w),p.set(f,{server:y,transport:w}),w}async function c(d,f){let p=nt(d);if(p===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(p)===void 0){f.code(404).send({error:"unknown mcp token"});return}let m=d.params.name,g=await a(p,m);if(g===void 0){f.code(404).send({error:`unknown mcp server: ${m}`});return}f.hijack(),await g.handleRequest(d.raw,f.raw,d.body)}let u={config:{skipAuth:!0}};return n.post("/mcp/:name",u,async(d,f)=>{await c(d,f)}),n.get("/mcp/:name",u,async(d,f)=>{await c(d,f)}),n.delete("/mcp/:name",u,async(d,f)=>{await c(d,f)}),{notifyToolListChanged:i}}async function nl(n,e){ol(n);let t=n.daemon.tls?await st.readFile(Y(n.daemon.tls.key)):void 0,s=n.daemon.tls?await st.readFile(Y(n.daemon.tls.cert)):void 0;await st.mkdir(S.home(),{recursive:!0});let{stream:r,fileStream:o}=await sl(n.daemon.logLevel),i=Zu({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(el,{options:{handleProtocols:_s}}),En(O=>{i.log.info(O)}),_n(O=>{i.log.info(O)});let a=await nn.load(),c=new dn,u=new an,d=new on([new sn(e),new rn(a),u]),f=_o({validator:d});i.addHook("onRequest",async(O,ce)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,ce)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let l=setInterval(()=>{c.sweepExpired()},300*1e3);l.unref();let m=new rt(n,{onFetched:()=>{So(m,y)}});gs(O=>i.log.info(O));let g={info:O=>i.log.info(O),warn:O=>i.log.warn(O)},h=O=>he.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:g});Ws(n.compressToolContent);let v=new en,y=new vt(m,h,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:g,npmRegistry:n.npmRegistry,extensionCommands:v,defaultCwd:n.defaultCwd}),w=new Xt(Bs(n),void 0,{tokenRegistry:u}),b=new Zt(Us(n),void 0,{tokenRegistry:u});ri(i,K,Co(n));let A=new wn,x=new vn,C,T=()=>{if(C!==void 0)return C;let O=i.server.address();return C=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,C};ni(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:x,mcpTokenRegistry:A,getDaemonOrigin:T}),si(i,m,y,{npmRegistry:n.npmRegistry}),oi(i,w),ii(i,b),ai(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),fi(i,{store:a,rateLimiter:c}),bi(i,A),Ii(i,A);let _=ki(i,A,x);yi(i,{validator:d,manager:y,defaultAgent:n.defaultAgent,processRegistry:u,onExtensionVersion:(O,ce)=>w.reportVersion(O,ce),onTransformerVersion:(O,ce)=>b.reportVersion(O,ce),transformers:b,extensionCommands:v,mcpTokenRegistry:A,extensionMcp:x,extensionMcpControls:_,getDaemonOrigin:T,registry:m});let U=!!n.daemon.tls;await i.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=i.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,j,z=n.daemon.host,oe=P;if(U&&t&&s){j=rl({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:i.log});let O=j.address();O&&typeof O=="object"&&(oe=O.port)}await st.mkdir(S.home(),{recursive:!0}),await Io({pid:process.pid,host:z,port:oe,loopbackPort:P,startedAt:new Date().toISOString()});let $e={daemonUrl:`http://127.0.0.1:${P}`,daemonHost:"127.0.0.1",daemonPort:P,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${P}/acp`,hydraHome:S.home()};w.setContext($e),b.setContext($e),await w.start(),await b.start();try{await y.reconcilePermissionFlags()}catch(O){i.log.warn(`permission flag reconcile failed: ${O.message}`)}y.resurrectPendingQueues().catch(O=>{i.log.warn(`queue replay scan failed: ${O.message}`)}),y.resumePendingCompactions().catch(O=>{i.log.warn(`compaction resume scan failed: ${O.message}`)}),y.resumePendingAgentSwaps().catch(O=>{i.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Rs=Rt>0?ko({registry:m,manager:y,intervalMs:Rt,logger:g}):void 0,Es=n.daemon.sessionGcIntervalMinutes*60*1e3,Ri=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ps=Es>0?Ao({manager:y,intervalMs:Es,maxAgeMs:Ri,logger:g}):void 0;return{app:i,manager:y,registry:m,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:x,processRegistry:u,shutdown:async()=>{Ps&&Ps(),Rs&&Rs(),clearInterval(p),clearInterval(l);let O=async(ce,Ei)=>{try{await Ei()}catch(bn){i.log.warn(`shutdown step ${ce} failed: ${bn instanceof Error?bn.message:String(bn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>y.closeAll()),await O("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>y.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),En(null),_n(null),gs(null),j&&await O("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await O("app.close",()=>i.close());try{Ci.unlinkSync(S.pidFile())}catch{}await O("fileStream.flushSync",()=>o.flushSync())}}}async function sl(n){let e=await tl({file:S.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=Ai.destination(2);return{stream:Ai.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function rl(n){let e=Mi.createServer(n.tlsOptions,t=>{let s=xi.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",o),s.on("error",o),t.on("close",()=>o()),s.on("close",()=>o()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function ol(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{he as AgentInstance,Ee as JsonRpcConnection,rt as Registry,Pe as Session,vt as SessionManager,Gi as defaultConfig,$i as ensureServiceToken,Et as generateServiceToken,Ls as loadConfig,_i as loadServiceToken,Hn as ndjsonStreamFromStdio,S as paths,te as planSpawn,nl as startDaemon,Ki as writeConfig,As as wsToMessageStream};
|
|
142
|
+
`)}}return y=!0,v||d.raw.end(),d});function r(l,d,f){let p=typeof l=="string"?l.trim():"";if(p.length===0)return null;let c;try{c=JSON.parse(p)}catch{return console.debug("events endpoint: skipping malformed JSONL line"),null}if(!c||typeof c!="object"||Array.isArray(c))return console.debug("events endpoint: skipping non-object JSONL line"),null;let g=c;if(typeof g.recordedAt!="number"||f!==void 0&&g.recordedAt<f||typeof g.params!="object"||g.params===null||Array.isArray(g.params))return null;let m=g.params;if(typeof m.update!="object"||m.update===null||Array.isArray(m.update))return null;let v=m.update.sessionUpdate;return typeof v!="string"||!d.has(v)?null:{recordedAt:g.recordedAt,entry:c}}function o(l,d,f){let c=d.params.update,g={sessionId:l,ts:new Date(d.recordedAt).toISOString(),kind:f,update:c};return c.messageId!==void 0&&c.messageId!==null&&(g.messageId=c.messageId),g}async function*i(l,d,f,p){for await(let c of d){let g=r(c,f,p);if(g){let m=g.entry.params.update.sessionUpdate;yield{ts:g.recordedAt,row:o(l,g.entry,m)}}}}async function a(l,d,f,p){let c=ks.createInterface({input:Ss.createReadStream(d),crlfDelay:1/0}),g=i(l,c,f,p),m=await g.next(),h=m.done?null:m.value;return{sessionId:l,rl:c,gen:g,current:h,exhausted:h===null}}async function u(l){let d=await l.gen.next();d.done?(l.exhausted=!0,l.current=null):l.current=d.value}n.get("/v1/sessions/events",async(l,d)=>{let f=l.query,p=f.kinds;if(!p||p.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let c=p.split(",").map(w=>w.trim());if(c.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let w of c)if(!ln.has(w))return d.code(400).send({error:`kind "${w}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let g=new Set(c),m;if(f.since!==void 0&&f.since.trim().length>0){let w=new Date(f.since);if(isNaN(w.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;m=w.getTime()}let h=await e.list({includeNonInteractive:!0}),v=m!==void 0?h.filter(w=>new Date(w.updatedAt).getTime()>=m):h;d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;let y=[];for(let w of v)try{let b=k.historyFile(w.sessionId),A=await a(w.sessionId,b,g,m);A.exhausted||y.push(A)}catch(b){if(b.code==="ENOENT")continue;throw b}l.raw.on("close",()=>{for(let w of y)try{w.rl.close()}catch{}d.raw.writableEnded||d.raw.end()});try{for(;y.length>0;){let w=-1,b=1/0;for(let x=0;x<y.length;x++){let C=y[x];C.current!==null&&C.current.ts<b&&(b=C.current.ts,w=x)}if(w===-1)break;let A=y[w];if(d.raw.write(JSON.stringify(A.current.row)+`
|
|
143
|
+
`),await u(A),A.exhausted){try{A.rl.close()}catch{}y.splice(w,1)}}}catch(w){for(let b of y)try{b.rl.close()}catch{}throw w}return d.raw.end(),d}),n.get("/v1/sessions/:id/events",async(l,d)=>{let f=l.params.id,p=l.query,c=await e.resolveCanonicalId(f)??f;if(!e.get(c)&&!await e.hasRecord(c))return d.code(404).send({error:"session not found"}),d;let m=p.kinds;if(!m||m.trim().length===0)return d.code(400).send({error:"kinds parameter is required"}),d;let h=m.split(",").map(x=>x.trim());if(h.length===0)return d.code(400).send({error:"kinds parameter is required"}),d;for(let x of h)if(!ln.has(x))return d.code(400).send({error:`kind "${x}" is not queryable; allowed kinds: ${[...ln].join(", ")}`}),d;let v=new Set(h),y;if(p.since!==void 0&&p.since.trim().length>0){let x=new Date(p.since);if(isNaN(x.getTime()))return d.code(400).send({error:"since is not a valid ISO-8601 timestamp"}),d;y=x.getTime()}let w=k.historyFile(c),b=Ss.createReadStream(w),A=ks.createInterface({input:b,crlfDelay:1/0});d.raw.setHeader("content-type","application/x-ndjson"),d.raw.statusCode=200;try{for await(let x of A){let C=typeof x=="string"?x.trim():"";if(C.length===0)continue;let T;try{T=JSON.parse(C)}catch{console.debug("events endpoint: skipping malformed JSONL line in %s",w);continue}if(!T||typeof T!="object"||Array.isArray(T)){console.debug("events endpoint: skipping non-object JSONL line in %s",w);continue}let _=T;if(typeof _.recordedAt!="number"||typeof _.params!="object"||_.params===null||Array.isArray(_.params))continue;let U=_.params;if(typeof U.update!="object"||U.update===null||Array.isArray(U.update))continue;let $=U.update,P=$.sessionUpdate;if(typeof P!="string"||!v.has(P)||y!==void 0&&_.recordedAt<y)continue;let j={ts:new Date(_.recordedAt).toISOString(),kind:P,update:$};$.messageId!==void 0&&$.messageId!==null&&(j.messageId=$.messageId),d.raw.write(JSON.stringify(j)+`
|
|
144
|
+
`)}}catch(x){if(x.code==="ENOENT")return d.raw.end(),d;throw x}return d.raw.end(),d}),n.get("/v1/sessions/:id/attention",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,c=e.get(p);return!c&&!await e.hasRecord(p)?(d.code(404).send({error:"session not found"}),d):c?{flags:c.listAttentionFlags()}:{flags:(await e.store.read(p))?.attentionFlags??[]}}),n.get("/v1/sessions/attention",async(l,d)=>{let f=l.query;if(!f.source||f.source.trim().length===0)return d.code(400).send({error:"source query parameter is required"}),d;let p=await e.list({includeNonInteractive:!0}),c=[];for(let g of p){let m=e.get(g.sessionId),h;m?h=m.listAttentionFlags():h=(await e.store.read(g.sessionId))?.attentionFlags??[];for(let v of h)v.source===f.source&&c.push({...v,sessionId:g.sessionId})}return{flags:c}}),n.post("/v1/sessions/:id/attention/clear",async(l,d)=>{let f=l.params.id,p=await e.resolveCanonicalId(f)??f,g=l.body??{},m=typeof g.source=="string"?g.source:"",h=typeof g.reason=="string"?g.reason:"";if((m.length>0||h.length>0)&&!(m.length>0&&h.length>0)){d.code(400).send({error:"both source and reason are required to clear a specific flag, or omit both to clear all"});return}m.length===0&&h.length;let v=e.get(p);if(v){if(m.length>0&&h.length>0)v.clearAttentionFlag(m,h);else{let x=Array.from(v.listAttentionFlags()).map(C=>`${C.source}::${C.reason}`);for(let C of x)v.clearAttentionFlag(C.split("::")[0],C.split("::").slice(1).join("::"))}d.code(204).send();return}if(!await e.hasRecord(p)){d.code(404).send({error:"session not found"});return}let y=e.store,w=await y.read(p);if(!w){d.code(404).send({error:"session not found"});return}let b=w.attentionFlags??[],A;if(m.length>0&&h.length>0){let x=`${m}::${h}`;A=b.filter(C=>`${C.source}::${C.reason}`!==x)}else A=[];if(A.length===b.length&&A.every((x,C)=>x.source===b[C].source&&x.reason===b[C].reason)){d.code(204).send();return}await y.write({...w,attentionFlags:A}),d.code(204).send()})}function ri(n,e,t,s={}){n.get("/v1/agents",async()=>Ne(e)),n.get("/v1/registry",async()=>e.load()),n.post("/v1/registry/refresh",async()=>{let r=await e.refresh();return{version:r.version,agentCount:r.agents.length}}),n.post("/v1/agents/:id/install",async(r,o)=>{let i=r.params.id,a=await e.getAgent(i);if(!a){o.code(404).send({error:`agent ${i} not found in registry`});return}if(a.distribution.uvx&&!a.distribution.npx&&!a.distribution.binary){o.send({agentId:a.id,version:a.version??"current",distribution:"uvx",installed:!1,message:"uvx agents resolve on first run; nothing to pre-install."});return}try{let u=await te(a,[],{npmRegistry:s.npmRegistry}),l=a.distribution.npx?"npx":a.distribution.binary?"binary":"unknown";o.send({agentId:a.id,version:u.version,distribution:l,installed:!0,command:u.command})}catch(u){o.code(500).send({error:u.message})}}),n.post("/v1/agents/:id/sync",async(r,o)=>{let i=r.params.id;try{let{synced:a,skipped:u}=await t.syncFromAgent(i);return{synced:a.map(l=>({sessionId:l.sessionId,upstreamSessionId:l.upstreamSessionId,agentId:l.agentId,cwd:l.cwd,title:l.title,updatedAt:l.updatedAt})),skipped:u}}catch(a){let u=a;if(u.code===S.AgentNotInstalled){o.code(404).send({error:u.message});return}o.code(409).send({error:u.message})}})}function oi(n,e,t){n.get("/v1/health",{config:{skipAuth:!0}},async()=>({status:"ok",version:e,configDigest:t}))}var cu=/^[A-Za-z0-9._-]+$/;function fn(n,e,t){let s=e==="extension"?"extensions":"transformers",r=`/v1/${s}`;n.get(r,async()=>({[s]:t.list()})),n.get(`${r}/:name`,async(o,i)=>{let a=o.params.name,u=t.get(a);if(!u){i.code(404).send({error:`unknown ${e}: ${a}`});return}return u}),n.post(r,async(o,i)=>{let a=o.body??{},u=uu(a);if("error"in u){i.code(400).send({error:u.error});return}try{let l=t.register(u.config);i.code(201).send(l)}catch(l){xt(i,l)}}),n.delete(`${r}/:name`,async(o,i)=>{let a=o.params.name;try{await t.unregister(a),i.code(204).send()}catch(u){xt(i,u)}}),n.post(`${r}/:name/start`,async(o,i)=>{let a=o.params.name;try{let u=await t.startByName(a);i.code(200).send(u)}catch(u){xt(i,u)}}),n.post(`${r}/:name/stop`,async(o,i)=>{let a=o.params.name;try{let u=await t.stopByName(a);i.code(200).send(u)}catch(u){xt(i,u)}}),n.post(`${r}/:name/restart`,async(o,i)=>{let a=o.params.name;try{let u=await t.restartByName(a);i.code(200).send(u)}catch(u){xt(i,u)}})}function xt(n,e){let t=e.code,s=e.message??"unknown error";if(t==="NOT_FOUND"){n.code(404).send({error:s});return}if(t==="CONFLICT"){n.code(409).send({error:s});return}n.code(500).send({error:s})}function uu(n){let e=n.name;if(typeof e!="string"||!cu.test(e))return{error:"name must match [A-Za-z0-9._-]+"};let t=n.command;if(t!==void 0&&(!Array.isArray(t)||t.some(i=>typeof i!="string")))return{error:"command must be string[]"};let s=n.args;if(s!==void 0&&(!Array.isArray(s)||s.some(i=>typeof i!="string")))return{error:"args must be string[]"};let r=n.env;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))return{error:"env must be an object of string\u2192string"};if(r&&Object.values(r).some(i=>typeof i!="string"))return{error:"env values must be strings"};let o=n.enabled;return o!==void 0&&typeof o!="boolean"?{error:"enabled must be a boolean"}:{config:{name:e,command:t??[],args:s??[],env:r??{},enabled:o===void 0?!0:o}}}function ii(n,e){fn(n,"extension",e)}function ai(n,e){fn(n,"transformer",e)}function di(n,e){n.get("/v1/config",async()=>e)}import{z as tt}from"zod";import*as et from"fs/promises";import*as ci from"path";import{randomBytes as Cm,scrypt as lu,timingSafeEqual as fu}from"crypto";import{promisify as pu}from"util";var gu=pu(lu);function ui(){return ci.join(k.home(),"password-hash")}var mu=128*1024*1024;async function li(){try{return(await et.readFile(ui(),"utf8")).trim().length>0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fi(n){if(typeof n!="string"||n.length===0)return!1;let e;try{e=(await et.readFile(ui(),"utf8")).trim()}catch(l){if(l.code==="ENOENT")return!1;throw l}let t=e.split("$");if(t.length!==6||t[0]!=="scrypt")return!1;let s=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);if(!Number.isFinite(s)||!Number.isFinite(r)||!Number.isFinite(o))return!1;let i=Buffer.from(t[4],"hex"),a=Buffer.from(t[5],"hex");if(i.length===0||a.length===0)return!1;let u=await gu(n,i,a.length,{N:s,r,p:o,maxmem:mu});return u.length!==a.length?!1:fu(u,a)}var hu=tt.object({password:tt.string().min(1),label:tt.string().min(1).max(256).optional(),ttlSec:tt.number().int().positive().optional()}),yu=tt.object({id:tt.string().optional()}).optional();function pi(n,e){n.post("/v1/auth/login",{config:{skipAuth:!0}},async(t,s)=>{let r=wu(t);if(e.rateLimiter.isBlocked(r))return s.code(429).send({error:"Too many failed attempts; try again later."});let o;try{o=hu.parse(t.body)}catch{return s.code(400).send({error:"Invalid request body"})}if(!await li())return s.code(403).send({error:"No password configured. Run `hydra-acp auth password` on the daemon host."});if(!await fi(o.password))return e.rateLimiter.recordFailure(r),s.code(401).send({error:"Invalid password"});e.rateLimiter.recordSuccess(r);let a=await e.store.issue({label:o.label,ttlSec:o.ttlSec});return s.code(200).send({session_token:a.token,id:a.id,expires_at:a.expiresAt})}),n.post("/v1/auth/logout",async(t,s)=>{let r;try{r=yu.parse(t.body??void 0)}catch{return s.code(400).send({error:"Invalid request body"})}let o=r?.id??t.authIdentity;if(!o||o==="service")return s.code(200).send({revoked:!1});let i=await e.store.revoke(o);return s.code(200).send({revoked:i})}),n.get("/v1/auth/verify",async(t,s)=>s.code(200).send({ok:!0})),n.get("/v1/auth/sessions",async(t,s)=>s.code(200).send({sessions:e.store.list()})),n.delete("/v1/auth/sessions/:id",async(t,s)=>{let r=t.params.id;return await e.store.revoke(r)?s.code(204).send():s.code(404).send({error:"Not found"})})}function wu(n){return n.ip||"unknown"}import{nanoid as Cs}from"nanoid";function As(n){let e=[],t=[],s=!1,r=o=>{if(!s){s=!0;for(let i of t)i(o)}};return n.on("message",(o,i)=>{if(i)return;let a=o.toString("utf8");try{let u=JSON.parse(a);for(let l of e)l(u)}catch(u){for(let l of e)l({jsonrpc:"2.0",id:null,error:{code:S.ParseError,message:`Failed to parse WS frame: ${u.message}`}})}}),n.on("close",()=>r()),n.on("error",o=>r(o)),{async send(o){if(s)throw new Error("ws is closed");let i=JSON.stringify(o);await new Promise((a,u)=>{n.send(i,l=>{if(l){u(l);return}a()})})},onMessage(o){e.push(o)},onClose(o){t.push(o)},async close(){s||(await new Promise(o=>{let i=!1,a=()=>{i||(i=!0,clearTimeout(u),o())},u=setTimeout(a,5e3);n.once("close",a);try{n.close()}catch{a()}}),r())}}}import{randomBytes as mi}from"crypto";import*as hi from"os";import*as yi from"path";function E(n,e,t){let s=new Error(e);return s.code=n,t!==void 0&&(s.data=t),s}function ku(n){if(!n||typeof n!="object")return 512;let s=n.params?.update;if(!s)return 512;let r=512,o=s.content;if(typeof o=="string")r+=o.length;else if(o&&typeof o=="object"){let a=o;typeof a.text=="string"&&(r+=a.text.length),typeof a.data=="string"&&(r+=a.data.length)}let i=s.toolCall;if(i&&(typeof i.rawInput=="string"?r+=i.rawInput.length:i.rawInput&&typeof i.rawInput=="object"&&(r+=256),typeof i.rawOutput=="string"?r+=i.rawOutput.length:i.rawOutput&&typeof i.rawOutput=="object"&&(r+=256),Array.isArray(i.content)))for(let a of i.content){if(!a||typeof a!="object")continue;let u=a;if(typeof u.text=="string"&&(r+=u.text.length),u.content&&typeof u.content=="object"){let l=u.content;typeof l.text=="string"&&(r+=l.text.length)}}return r}function se(n,e,t){let s=n.get(e);if(!s)throw E(S.SessionNotFound,t??`session ${e} not found`);return s}async function pn(n,e){let t=Ze(n),s,r,o;typeof e.summarizedThroughEntry=="number"&&e.summarizedThroughEntry>0&&n.mcpTokenRegistry!==void 0&&n.getDaemonOrigin!==void 0&&(s=mi(32).toString("hex"),r=n.mcpTokenRegistry.reserve(s),o={name:"hydra-acp-recall",type:"http",url:`${n.getDaemonOrigin()}/mcp/hydra-acp-recall`,headers:[{name:"Authorization",value:`Bearer ${s}`}]});let a=[...t?.descriptors??[],...o!==void 0?[o]:[]],u=Is({baselineMcpServers:void 0,stdinEnabled:!1,deps:n}),l;try{l=await n.manager.resurrect({...e,mcpServers:a,...u?{mintMcpServersForSwap:u}:{}})}catch(d){throw t!==void 0&&t.abandon(d instanceof Error?d:void 0),r!==void 0&&r.abandon(d instanceof Error?d:void 0),d}if(t!==void 0&&t.bindToSession(l),s!==void 0&&r!==void 0&&n.mcpTokenRegistry!==void 0){let d=s,f=n.mcpTokenRegistry;r.complete(l),l.onClose(()=>{f.unbind(d)})}return _u(l,n),vi(l.sessionId,n),l}function wi(n,e){n.get("/acp",{websocket:!0},async(t,s)=>{let r=$o({headers:s.headers,url:s.url});if(!r||!await e.validator.validate(r)){t.close(4401,"Unauthorized");return}let o=e.processRegistry?.resolve(r),i=As(t),a=new Ee(i),u={clientId:`hydra_client_${Cs(12)}`,processIdentity:o,attached:new Map};a.onClose(()=>{for(let f of u.attached.values())e.manager.get(f.sessionId)?.detach(f.clientId);u.attached.clear()});let l=(f,p)=>{if(u.attached.get(f)?.readonly)throw E(S.PermissionDenied,`${p} not permitted on a read-only attachment`)};if(a.onRequest("initialize",async f=>{let p=ar.parse(f??{});p.clientInfo?.name&&(u.clientInfo={name:p.clientInfo.name,...p.clientInfo.version!==void 0?{version:p.clientInfo.version}:{}});let c=p.clientInfo?.version;return c&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,c):e.onTransformerVersion?.(o.name,c)),Tu()}),o&&e.extensionCommands){let f=e.extensionCommands;a.onRequest("hydra-acp/commands/register",async p=>{let c=p??{},g=Array.isArray(c.commands)?c.commands.map(m=>{if(!m||typeof m!="object")return;let h=m;if(typeof h.verb!="string")return;let v={verb:h.verb};return typeof h.argsHint=="string"&&(v.argsHint=h.argsHint),typeof h.description=="string"&&(v.description=h.description),v}).filter(m=>m!==void 0):[];return f.register(o.name,a,g),{ok:!0,registered:g.length}}),a.onClose(()=>{f.clear(o.name)})}if(o&&e.extensionMcp){let f=e.extensionMcp;a.onRequest("hydra-acp/mcp_tools/register",async c=>{let g=c??{},m=typeof g.instructions=="string"?g.instructions:void 0,h=Array.isArray(g.tools)?g.tools.map(v=>{if(!v||typeof v!="object")return;let y=v;if(typeof y.name!="string"||y.name.length===0||typeof y.description!="string"||y.inputSchema===null||typeof y.inputSchema!="object")return;let w={name:y.name,description:y.description,inputSchema:y.inputSchema};return y.outputSchema!==null&&typeof y.outputSchema=="object"&&(w.outputSchema=y.outputSchema),w}).filter(v=>v!==void 0):[];if(h.length===0)throw new Error("register_mcp_tools requires at least one tool");return f.register(o.name,a,m,h),{ok:!0,registered:h.length}});let p=c=>{let g=c??{};if(typeof g.sessionId!="string"||g.sessionId.length===0)throw E(S.InvalidParams,"sessionId is required");return g.sessionId};if(a.onRequest("hydra-acp/session/extension_state/get",async c=>{let g=p(c),m=c??{};if(typeof m.key!="string"||m.key.length===0)throw E(S.InvalidParams,"key is required");if(!e.manager)throw E(S.InternalError,"manager not wired");return{value:await e.manager.getExtensionStateKey(g,o.name,m.key)??null}}),a.onRequest("hydra-acp/session/extension_state/list",async c=>{let g=p(c);if(!e.manager)throw E(S.InternalError,"manager not wired");return{state:await e.manager.getExtensionState(g,o.name)}}),a.onRequest("hydra-acp/session/extension_state/set",async c=>{let g=p(c),m=c??{};if(typeof m.key!="string"||m.key.length===0)throw E(S.InvalidParams,"key is required");if(m.value===void 0)throw E(S.InvalidParams,"value is required (use extension_state/delete to remove)");if(!e.manager)throw E(S.InternalError,"manager not wired");try{await e.manager.setExtensionStateKey(g,o.name,m.key,m.value)}catch(h){throw E(S.InvalidParams,h.message)}return{ok:!0}}),a.onRequest("hydra-acp/session/extension_state/delete",async c=>{let g=p(c),m=c??{};if(typeof m.key!="string"||m.key.length===0)throw E(S.InvalidParams,"key is required");if(!e.manager)throw E(S.InternalError,"manager not wired");return await e.manager.deleteExtensionStateKey(g,o.name,m.key),{ok:!0}}),e.extensionMcpControls){let c=e.extensionMcpControls;a.onRequest("hydra-acp/mcp_tools/refresh_session",async g=>{let m=g??{};if(typeof m.sessionId!="string"||m.sessionId.length===0)throw E(S.InvalidParams,"refresh_session requires sessionId");return await c.notifyToolListChanged(m.sessionId,o.name),{ok:!0}})}a.onClose(()=>{f.clear(o.name)})}if(o?.kind==="transformer"){a.onRequest("hydra-acp/transformer/initialize",async p=>{let c=p??{},g=Array.isArray(c.intercepts)?c.intercepts.filter(m=>typeof m=="string"):[];if(e.transformers&&(e.transformers.registerConnection(o.name,a,g),e.manager?.defaultTransformers.includes(o.name))){let m=e.transformers.resolveChain([o.name])[0];if(m)for(let h of e.manager.liveSessions())h.addTransformer(m)}return{ack:!0}}),a.onClose(()=>{e.transformers?.deregisterConnection(o.name)}),a.onRequest("hydra-acp/message/emit",async p=>{let c=p??{},g=typeof c.sessionId=="string"?c.sessionId:void 0,m=typeof c.method=="string"?c.method:void 0,h=c.envelope,v=c.route;if(!g)throw E(-32602,"emit_message requires sessionId");if(!m&&v!=="client_broadcast")throw E(-32602,"emit_message requires method");let y=se(e.manager,g),w=typeof c.respondsTo=="string"?c.respondsTo:void 0;if(w)return y.dischargeClaim(w,h),{ok:!0};if(v==="chain")return{ok:!0,response:await y.emitToChain(o.name,m,h)};if(v==="queue"){if(m!=="session/prompt")throw E(-32602,'route "queue" only supports method "session/prompt"');return{ok:!0,response:await y.emitToQueue(o.name,h)}}if(v==="daemon")return{ok:!0,response:await y.emitToChain(o.name,m,h)};if(v==="client_broadcast"){if(!h||typeof h!="object")throw E(-32602,"client_broadcast requires an envelope object");return y.broadcastClientUpdate(h),{ok:!0}}throw E(-32602,`unsupported route: ${JSON.stringify(v)}`)}),a.onRequest("hydra-acp/session/request_permission",async p=>{let c=p??{},g=typeof c.sessionId=="string"?c.sessionId:void 0;if(!g)throw E(-32602,"hydra-acp/session/request_permission requires sessionId");return se(e.manager,g).requestPermissionFromClients(c)}),a.onRequest("hydra-acp/transformer/attach",async p=>Mu(p,o.name,e)),a.onRequest("hydra-acp/child_session/spawn",async p=>{let c=p??{},g=typeof c.agentId=="string"?c.agentId:e.defaultAgent,m=typeof c.cwd=="string"?c.cwd:void 0,h=typeof c.parentSessionId=="string"?c.parentSessionId:void 0,v=c._meta&&typeof c._meta=="object"?c._meta:void 0,y=v&&v["hydra-acp"]&&typeof v["hydra-acp"]=="object"?v["hydra-acp"]:void 0,w=y&&typeof y.title=="string"?y.title:void 0,b=y&&typeof y.model=="string"?y.model:void 0;if(!m&&h){let C=e.manager.get(h);C&&(m=C.cwd)}if(!m)throw E(-32602,"child_session/spawn requires cwd (or a parentSessionId pointing at a live session whose cwd we can inherit)");let A=typeof c.interactive=="boolean"?c.interactive:!1;return{childSessionId:(await e.manager.create({agentId:g,cwd:m,parentSessionId:h,interactive:A,transformChain:[],title:w,model:b})).sessionId}}),a.onRequest("hydra-acp/session/fork",async p=>{let c=p??{};if(typeof c.sessionId!="string")throw E(S.InvalidParams,"fork_session requires sessionId");let g=typeof c.forkAt=="string"?c.forkAt:void 0,m=typeof c.cwd=="string"?c.cwd:void 0,h=typeof c.agentId=="string"?c.agentId:void 0,v=typeof c.mode=="string"&&(c.mode==="verbatim"||c.mode==="synthesis")?c.mode:void 0,y=typeof c.model=="string"&&c.model.length>0?c.model:void 0;return await e.manager.forkSession(c.sessionId,{...g!==void 0?{forkAt:g}:{},...m!==void 0?{cwd:m}:{},...h!==void 0?{agentId:h}:{},...v!==void 0?{mode:v}:{},...y!==void 0?{model:y}:{}})}),a.onRequest("session/fork",async p=>{let c=p??{};if(typeof c.sessionId!="string")throw E(S.InvalidParams,"session/fork requires sessionId");let g=typeof c.cwd=="string"?c.cwd:void 0;return{sessionId:(await e.manager.forkSession(c.sessionId,{...g!==void 0?{cwd:g}:{},mode:"verbatim"})).sessionId}});let f=async(p,c)=>{let g=p??{};if(typeof g.sessionId!="string")throw E(S.InvalidParams,`${c} requires sessionId`);let m=await e.manager.resolveCanonicalId(g.sessionId)??g.sessionId,h=e.manager.get(m);if(h)return await h.close({deleteRecord:!0}),await e.manager.waitForDeletion(m),await e.manager.hasRecord(m)&&await e.manager.deleteRecord(m),{id:m,existed:!0};let v=await e.manager.deleteRecord(m);return{id:m,existed:v}};a.onRequest("session/delete",async p=>(await f(p,"session/delete"),{})),a.onRequest("session/close",async p=>{let c=p??{};if(typeof c.sessionId!="string")throw E(S.InvalidParams,"session/close requires sessionId");l(c.sessionId,"session/close");let g=await e.manager.resolveCanonicalId(c.sessionId)??c.sessionId,m=e.manager.get(g);if(m)return await m.close({deleteRecord:!1}),{};if(await e.manager.hasRecord(g))return{};throw E(S.SessionNotFound,`session ${g} not found`)}),a.onRequest("hydra-acp/session/delete",async p=>{let{id:c,existed:g}=await f(p,"hydra-acp/session/delete");if(!g)throw E(S.SessionNotFound,`session ${c} not found`);return{deleted:!0,sessionId:c}}),a.onRequest("hydra-acp/child_session/await",async p=>{let c=p??{},g=typeof c.childSessionId=="string"?c.childSessionId:void 0,m=c.until==="idle"?"idle":"turn_complete",h=typeof c.timeoutMs=="number"?Math.min(c.timeoutMs,18e5):3e5;if(!g)throw E(-32602,"await_child requires childSessionId");let v=se(e.manager,g,`child session ${g} not found`);return new Promise(y=>{let A=[],x=[],C=0,T=!1,_,U,$=!1,P=()=>{$||($=!0,clearTimeout(j),_?.(),U?.(),y(T?{entries:A,truncated:!0}:{entries:A}))};_=v.onBroadcast(z=>{let oe=ku(z);for(A.push(z),x.push(oe),C+=oe;A.length>0&&(A.length>1e3||C>1048576);)A.shift(),C-=x.shift()??0,T=!0;m==="turn_complete"&&z.params?.update?.sessionUpdate==="turn_complete"&&P()});let j=setTimeout(P,h);typeof j.unref=="function"&&j.unref(),U=v.onClose(()=>P())})}),a.onRequest("hydra-acp/child_session/close",async p=>{let c=p??{},g=typeof c.childSessionId=="string"?c.childSessionId:void 0;if(!g)throw E(-32602,"close_child_session requires childSessionId");let m=e.manager.get(g);return m&&await m.close({deleteRecord:!1}),{ok:!0}}),a.onRequest("hydra-acp/attention/set",async p=>Ru(p,o.name,e)),a.onRequest("hydra-acp/attention/clear",async p=>Eu(p,o.name,e)),a.onRequest("hydra-acp/connection/keep_alive",async p=>{let c=p??{},g=typeof c.token=="string"?c.token:void 0,m=typeof c.sessionId=="string"?c.sessionId:void 0,h=typeof c.estimatedRemainingMs=="number"?c.estimatedRemainingMs:void 0;return g&&m&&e.manager.get(m)?.keepAliveClaim(g,h),{ok:!0}})}a.onRequest("hydra-acp/session/tool_content",async f=>{let p=f??{};if(typeof p.sessionId!="string"||typeof p.hash!="string")throw E(S.InvalidParams,"hydra-acp/session/tool_content requires sessionId and hash");let c=await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,g=await e.manager.loadToolBlob(c,p.hash);if(g===null)throw E(S.SessionNotFound,"tool content not found");return{content:g}}),a.onRequest("authenticate",async f=>Au(f,e)),a.onRequest("logout",async f=>Cu(f,e)),a.onRequest("session/new",async f=>{let p=dr.parse(f),c=at(f?._meta),g=Array.isArray(c.transformers)&&c.transformers.every(P=>typeof P=="string")?c.transformers:e.manager.defaultTransformers??[],m=e.transformers?.resolveChain(g)??[],h,v,y=p.mcpServers;if(c.mcpStdin===!0&&e.mcpTokenRegistry!==void 0&&e.getDaemonOrigin!==void 0){h=mi(32).toString("hex"),v=e.mcpTokenRegistry.reserve(h);let j={name:"hydra-acp-stdin",type:"http",url:`${e.getDaemonOrigin()}/mcp/hydra-acp-stdin`,headers:[{name:"Authorization",value:`Bearer ${h}`}]};y=[...p.mcpServers??[],j]}let w,b,A=Ze(e);A!==void 0&&(y=[...y??[],...A.descriptors]);let x=Is({baselineMcpServers:p.mcpServers,stdinEnabled:c.mcpStdin===!0,deps:e}),C;try{C=await e.manager.create({cwd:p.cwd,agentId:c.agentId??e.defaultAgent,mcpServers:y,title:c.title,agentArgs:c.agentArgs,model:c.model,onInstallProgress:gi(a),transformChain:m,originatingClient:u.clientInfo,...c.interactive!==void 0?{interactive:c.interactive}:{},...c.env!==void 0?{forwardedEnv:c.env}:{},...x?{mintMcpServersForSwap:x}:{}})}catch(P){throw v!==void 0&&v.abandon(P instanceof Error?P:void 0),b!==void 0&&b.abandon(P instanceof Error?P:void 0),A!==void 0&&A.abandon(P instanceof Error?P:void 0),P}if(h!==void 0&&v!==void 0&&e.mcpTokenRegistry!==void 0){let P=h,j=e.mcpTokenRegistry;v.complete(C),C.onClose(()=>{j.unbind(P)})}if(w!==void 0&&b!==void 0&&e.mcpTokenRegistry!==void 0){let P=w,j=e.mcpTokenRegistry;b.complete(C),C.onClose(()=>{j.unbind(P)})}A!==void 0&&A.bindToSession(C),vi(C.sessionId,e);let T,_;try{yn(u,C,C.sessionId),T=Mt(a,C,u),{entries:_}=await C.attach(T,"full")}catch(P){throw await C.close({deleteRecord:!1}).catch(()=>{}),P}u.attached.set(C.sessionId,{sessionId:C.sessionId,clientId:T.clientId,readonly:!1}),setImmediate(()=>{(async()=>{for(let P of _){if(a.isClosed())break;await a.notify(P.method,P.params).catch(()=>{})}})()});let U=gn(C),$=mn(C);return{sessionId:C.sessionId,...U?{modes:U}:{},...$?{models:$}:{},configOptions:C.buildConfigOptions(),_meta:hn(e.manager,C,{clientId:T.clientId})}}),a.onRequest("session/attach",async f=>{let p=ur.parse(f),c=p.clientInfo?.version;c&&o&&(o.kind==="extension"?e.onExtensionVersion?.(o.name,c):e.onTransformerVersion?.(o.name,c));let g=at(p._meta),m=g.resume,h=g.readonly===!0,v=g.env;n.log.info(`session/attach sessionId=${p.sessionId} hasResumeHints=${!!m} readonly=${h}`);let y=m?p.sessionId:await e.manager.resolveCanonicalId(p.sessionId)??p.sessionId,w=e.manager.get(y);if(!w&&h){let $=await e.manager.loadFromDisk(y);if(!$)throw E(S.SessionNotFound,`session ${p.sessionId} not found`);let P=await e.manager.loadHistory(y),j=p.clientId??`cli_${Cs(8)}`;u.attached.set($.hydraSessionId,{sessionId:$.hydraSessionId,clientId:j,readonly:!0}),n.log.info(`session/attach OK (viewer) sessionId=${$.hydraSessionId} clientId=${j} attachedCount=${u.attached.size} replayed=${P.length}`);for(let z of P)await a.notify(z.method,z.params).catch(()=>{});return{sessionId:$.hydraSessionId,clientId:j,connectedClients:[j],historyPolicy:"full",replayed:P.length,_meta:Pu($)}}let b=!w;if(!w){let $=await e.manager.loadFromDisk(y),P=$;if(m&&(P={...$,hydraSessionId:p.sessionId,upstreamSessionId:m.upstreamSessionId,agentId:m.agentId,cwd:m.cwd,...m.title!==void 0?{title:m.title}:{},...m.agentArgs!==void 0?{agentArgs:m.agentArgs}:{}}),!P)throw E(S.SessionNotFound,`session ${p.sessionId} not found and no resume hints provided`);if(await e.manager.isTombstoned(P.agentId,P.upstreamSessionId))throw E(S.SessionNotFound,`session ${p.sessionId} was deleted`);let j=P.originatingClient?P:{...P,originatingClient:u.clientInfo},z=v!==void 0?{...j,forwardedEnv:v}:j;w=await pn(e,{...z,onInstallProgress:gi(a)})}yn(u,w,w.sessionId);let A=Mt(a,w,u,p.clientInfo,p.clientId),x=g.replayMode==="drip",{entries:C,appliedPolicy:T}=await w.attach(A,p.historyPolicy,{afterMessageId:p.afterMessageId,raw:x,...g.toolContent!==void 0?{toolContent:g.toolContent}:{}});if(u.attached.set(w.sessionId,{sessionId:w.sessionId,clientId:A.clientId,readonly:h}),v!==void 0&&await e.manager.setForwardedEnv(w.sessionId,v).catch(()=>{}),n.log.info(`session/attach OK sessionId=${w.sessionId} clientId=${A.clientId} attachedCount=${u.attached.size} requestedPolicy=${p.historyPolicy} appliedPolicy=${T} replayed=${C.length} readonly=${h}${x?" replayMode=drip":""}`),x){let $=g.dripSpeed&&g.dripSpeed>0?g.dripSpeed:1,P=750;(async()=>{let j=null;for(let z of C){let oe=typeof z.recordedAt=="number"?z.recordedAt:null;if(j!==null&&oe!==null){let _e=Math.min(P,Math.max(0,(oe-j)/$));_e>0&&await new Promise(Rt=>setTimeout(Rt,_e))}oe!==null&&(j=oe);try{await a.notify(z.method,z.params)}catch{return}}})()}else for(let $=0;$<C.length&&!a.isClosed();$++){let P=C[$],j=a.notify(P.method,P.params).catch(()=>{});($+1)%200===0&&await j}w.replayPendingPermissions(A);let _=gn(w),U=mn(w);return{sessionId:w.sessionId,clientId:A.clientId,connectedClients:w.connectedClients(A.clientId),historyPolicy:T,replayed:C.length,..._?{modes:_}:{},...U?{models:U}:{},configOptions:w.buildConfigOptions(),_meta:hn(e.manager,w,{resurrected:b})}}),a.onRequest("session/detach",async f=>{let p=lr.parse(f),c=u.attached.get(p.sessionId);if(!c)throw E(S.SessionNotFound,"client not attached to that session");let g=e.manager.get(p.sessionId);return g?.detach(c.clientId),u.attached.delete(p.sessionId),g&&e.manager.reapIfOrphanedNonInteractive(p.sessionId),{sessionId:p.sessionId,_meta:{[it]:{detachStatus:"detached"}}}}),a.onRequest("session/list",async f=>{let p=fr.parse(f??{});return{sessions:(await e.manager.list({cwd:p.cwd})).filter(h=>h.originatingClient?.name!==Lt).map(pr)}}),a.onRequest("hydra-acp/agents/list",async()=>{if(!e.registry)throw E(S.InternalError,"agent registry unavailable");return Ne(e.registry)}),a.onRequest("hydra-acp/agents/auth_methods",async f=>{let p=f??{};if(typeof p.agentId!="string"||p.agentId.length===0)throw E(S.InvalidParams,"hydra-acp/agents/auth_methods requires a non-empty agentId string");return{authMethods:(await e.manager.bootstrapAgentForAuth(p.agentId)).authMethods??[]}}),a.onRequest("session/prompt",async f=>{let p=gr.parse(f);l(p.sessionId,"session/prompt");let c=u.attached.get(p.sessionId);if(!c)throw n.log.warn(`session/prompt rejected: not attached sessionId=${p.sessionId} attachedKeys=[${[...u.attached.keys()].join(",")}]`),E(S.SessionNotFound,"not attached to session");let g=e.manager.get(p.sessionId);if(!g){let m=await e.manager.loadFromDisk(p.sessionId);if(!m)throw E(S.SessionNotFound,`session ${p.sessionId} not found`);n.log.info(`session/prompt auto-resurrecting cold sessionId=${p.sessionId}`),g=await pn(e,m);let h=Mt(a,g,u,void 0,c.clientId);await g.attach(h,"none")}return g.prompt(c.clientId,p)});let d=f=>{let p;try{p=Ot.parse(f)}catch(m){n.log.warn(`session/cancel: invalid params: ${m.message}`);return}let c=u.attached.get(p.sessionId);if(!c)return;if(c.readonly){n.log.warn(`session/cancel dropped (readonly attachment) sessionId=${p.sessionId}`);return}let g=e.manager.get(p.sessionId);g&&g.cancel(c.clientId).catch(m=>{n.log.warn(`session/cancel for ${p.sessionId}: ${m.message}`)})};a.onNotification("session/cancel",d),a.onRequest("session/cancel",async f=>{let p=Ot.parse(f);return l(p.sessionId,"session/cancel"),d(f),null}),a.onRequest("hydra-acp/prompt/cancel",async f=>{let p=hr.parse(f);return l(p.sessionId,"hydra-acp/prompt/cancel"),se(e.manager,p.sessionId).cancelQueuedPrompt(p.messageId)}),a.onRequest("hydra-acp/session/force_cancel",async f=>{let p=Ot.parse(f);return l(p.sessionId,"hydra-acp/session/force_cancel"),se(e.manager,p.sessionId).forceCancel()}),a.onRequest("hydra-acp/prompt/update",async f=>{let p=yr.parse(f);return l(p.sessionId,"hydra-acp/prompt/update"),se(e.manager,p.sessionId).updateQueuedPrompt(p.messageId,p.prompt)}),a.onRequest("hydra-acp/prompt/amend",async f=>{let p=wr.parse(f);l(p.sessionId,"hydra-acp/prompt/amend");let c=u.attached.get(p.sessionId);if(!c)throw E(S.SessionNotFound,"not attached to session");return se(e.manager,p.sessionId).amendPrompt(c.clientId,p)}),a.onRequest("session/resume",async f=>{let p=f??{},c=typeof p.sessionId=="string"?p.sessionId:void 0;if(!c)throw E(S.InvalidParams,"session/resume requires sessionId");let g=await e.manager.resolveCanonicalId(c)??c,m=e.manager.get(g);if(!m){let w=await e.manager.loadFromDisk(g);if(!w)throw E(S.SessionNotFound,`session ${c} not found in memory or on disk`);m=await pn(e,w)}yn(u,m,m.sessionId);let h=Mt(a,m,u);await m.attach(h,"pending_only"),u.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1}),m.replayPendingPermissions(h);let v=gn(m),y=mn(m);return{sessionId:m.sessionId,...v?{modes:v}:{},...y?{models:y}:{},configOptions:m.buildConfigOptions(),_meta:hn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/load",async f=>{let p=f??{},c=typeof p.sessionId=="string"?p.sessionId:void 0;if(!c)throw E(S.InvalidParams,"session/load requires sessionId");let g=await e.manager.resolveCanonicalId(c)??c,m=e.manager.get(g);if(!m){let b=await e.manager.loadFromDisk(g);if(!b)throw E(S.SessionNotFound,`session ${c} not found in memory or on disk`);m=await pn(e,b)}yn(u,m,m.sessionId);let h=Mt(a,m,u),{entries:v}=await m.attach(h,"pending_only");u.attached.set(m.sessionId,{sessionId:m.sessionId,clientId:h.clientId,readonly:!1});for(let b of v){if(a.isClosed())break;await a.notify(b.method,b.params).catch(()=>{})}m.replayPendingPermissions(h);let y=gn(m),w=mn(m);return{sessionId:m.sessionId,...y?{modes:y}:{},...w?{models:w}:{},configOptions:m.buildConfigOptions(),_meta:hn(e.manager,m,{clientId:h.clientId})}}),a.onRequest("session/set_model",async f=>{let p=f?.sessionId;typeof p=="string"&&l(p,"session/set_model");let c=xu(f,e.manager);if(c.kind==="error")throw n.log.warn(c.logMessage),E(c.code,c.message);if(c.kind==="no_op")return n.log.warn(c.logMessage),await a.notify("session/update",{sessionId:c.sessionId,update:{sessionUpdate:"current_model_update",currentModel:c.currentModel}}).catch(()=>{}),null;n.log.info(c.logMessage);let{modelId:g}=c,m=await c.session.forwardRequest("session/set_model",{...f,modelId:g});return c.session.applyModelChange(g),m}),a.onRequest("session/set_mode",async f=>{let p=f,c=p?.sessionId;if(typeof c=="string"&&l(c,"session/set_mode"),!p||typeof p.sessionId!="string")throw E(S.InvalidParams,"session/set_mode requires string sessionId");if(typeof p.modeId!="string")throw E(S.InvalidParams,"session/set_mode requires string modeId");let g=se(e.manager,p.sessionId),m=await g.forwardRequest("session/set_mode",f);return g.applyModeChange(p.modeId),m}),a.onRequest("session/set_config_option",async f=>{let p=f,c=v=>E(S.InvalidParams,v),g=p?.sessionId;if(typeof g=="string"&&l(g,"session/set_config_option"),!p||typeof p.sessionId!="string")throw c("session/set_config_option requires string sessionId");if(typeof p.configId!="string")throw c("session/set_config_option requires string configId");if(typeof p.value!="string")throw c("session/set_config_option requires string value");let m=se(e.manager,p.sessionId),h=m.buildConfigOptions().find(v=>v.id===p.configId);if(!h)throw c(`unknown configId ${JSON.stringify(p.configId)} for this session`);if(!h.options.some(v=>v.value===p.value))throw c(`value ${JSON.stringify(p.value)} is not valid for configId ${JSON.stringify(p.configId)}`);switch(p.configId){case"model":{p.value!==m.currentModel&&await m.forwardRequest("session/set_model",{sessionId:p.sessionId,modelId:p.value}),m.applyModelChange(p.value);break}case"mode":{p.value!==m.currentMode&&await m.forwardRequest("session/set_mode",{sessionId:p.sessionId,modeId:p.value}),m.applyModeChange(p.value);break}case"agent":{p.value!==m.agentId&&await m.setAgent(p.value);break}default:throw c(`configId ${JSON.stringify(p.configId)} is not settable`)}return{configOptions:m.buildConfigOptions()}}),a.setDefaultHandler(async(f,p)=>{let c=new Set(["hydra-acp/attention/set","hydra-acp/attention/clear"]),g=p.startsWith("session/"),m=p.startsWith("hydra-acp/");if(!g&&!m||f===null||typeof f!="object"||c.has(p))throw E(S.MethodNotFound,`Method not found: ${p}`);let h=f.sessionId;if(typeof h!="string")throw E(S.MethodNotFound,`Method not found: ${p}`);return l(h,p),se(e.manager,h).forwardRequest(p,f)})})}async function Au(n,e){let t=n??{};if(typeof t.methodId!="string"||t.methodId.length===0)throw E(S.InvalidParams,"authenticate requires a non-empty methodId string");let s=t.methodId,r=t._meta?.["hydra-acp"],o=typeof r?.sessionId=="string"?r.sessionId:void 0,i=typeof r?.agentId=="string"?r.agentId:void 0,a=o!==void 0?e.manager.getAgentForSession(o):void 0;if(!a||!a.isAlive()){let c=i??e.defaultAgent;a=await e.manager.bootstrapAgentForAuth(c)}let u=a.authMethods??[],l=u.find(c=>c.id===s);if(!l){let c=u.map(g=>g.id);throw E(S.InvalidParams,`authenticate: methodId ${JSON.stringify(s)} is not advertised by agent ${a.agentId}; valid: [${c.map(g=>JSON.stringify(g)).join(", ")}]`)}let d=l._meta?.type,f=(()=>{let c=l._meta?.["terminal-auth"];if(c&&typeof c=="object"&&!Array.isArray(c))return c})();if((l.type??(d==="agent"||d==="terminal"?d:f!==void 0?"terminal":"agent"))==="terminal"){let c=(w,b)=>{if(!Array.isArray(w))throw E(S.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be a string[]; got ${w===null?"null":typeof w}`);for(let A of w)if(typeof A!="string")throw E(S.InvalidParams,`authenticate: method ${JSON.stringify(s)} ${b} must be string[]; got non-string entry ${JSON.stringify(A)}`);return w},g=await e.manager.planSpawnForAgent(a.agentId),m,h;if(f?.args!==void 0){let w=typeof f.command=="string"?f.command:void 0;m=w!==void 0&&yi.isAbsolute(w)?w:g.command,h=c(f.args,'_meta["terminal-auth"].args')}else{let w=l.args!==void 0?{raw:l.args,label:"args"}:l._meta?.args!==void 0?{raw:l._meta.args,label:"_meta.args"}:void 0,b=w!==void 0?c(w.raw,w.label):[];m=g.command,h=[...g.args,...b]}let v={};for(let[w,b]of Object.entries(process.env))typeof b=="string"&&(v[w]=b);Object.assign(v,g.env);let y=hi.homedir();return console.error(`[authenticate] terminal-auth requested agentId=${a.agentId} methodId=${s}`),{kind:"terminal",command:m,args:h,env:v,cwd:y}}try{return await a.connection.request("authenticate",{methodId:s})}catch(c){throw Ce(c,a)}}async function Cu(n,e){let s=(n??{})._meta?.["hydra-acp"],r=typeof s?.sessionId=="string"?s.sessionId:void 0,o=typeof s?.agentId=="string"?s.agentId:void 0,i=r!==void 0?e.manager.getAgentForSession(r):void 0;if(!i||!i.isAlive()){let a=o??e.defaultAgent;i=await e.manager.bootstrapAgentForAuth(a)}return await i.connection.request("logout",{})}function gi(n){return e=>{let t={agentId:e.agentId,version:e.version,source:e.source,phase:e.phase};"receivedBytes"in e&&(t.receivedBytes=e.receivedBytes),"totalBytes"in e&&(t.totalBytes=e.totalBytes),"packageSpec"in e&&(t.packageSpec=e.packageSpec),n.notify(vr,t).catch(()=>{})}}function gn(n){let e=n.availableModes();if(e.length===0)return;let t=e.map(r=>{let o={id:r.id,name:r.name??r.id};return r.description!==void 0&&(o.description=r.description),o});return{currentModeId:n.currentMode??e[0].id,availableModes:t}}function mn(n){let e=n.availableModels();if(e.length===0)return;let t=e.map(r=>{let o={modelId:r.modelId};return r.name!==void 0&&(o.name=r.name),r.description!==void 0&&(o.description=r.description),o});return{currentModelId:n.currentModel??e[0].modelId,availableModels:t}}function xu(n,e){if(!n||typeof n!="object")return{kind:"error",code:S.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:S.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:S.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:S.SessionNotFound,message:`session ${t.sessionId} not found`,logMessage:`session/set_model rejected: session not found sessionId=${t.sessionId}`};let r=s.availableModels(),o=qe(t.modelId,r);if(o.kind==="none")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model passthrough (no availableModels) sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="exact")return{kind:"ok",session:s,modelId:t.modelId,logMessage:`session/set_model accepted sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)}`};if(o.kind==="resolved")return{kind:"ok",session:s,modelId:o.modelId,logMessage:`session/set_model resolved sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} \u2192 ${JSON.stringify(o.modelId)}`};let i=r.map(u=>u.modelId).join(", "),a=o.kind==="ambiguous"?`ambiguous (trailing-segment matches [${o.candidates.join(", ")}])`:"not in availableModels";return s.currentModel!==void 0&&s.currentModel.length>0?{kind:"no_op",session:s,sessionId:t.sessionId,currentModel:s.currentModel,logMessage:`session/set_model no_op (resyncing client) sessionId=${t.sessionId} requested=${JSON.stringify(t.modelId)} ${a} actual=${JSON.stringify(s.currentModel)} agentId=${s.agentId} known=[${i}]`}:{kind:"error",code:S.InvalidParams,message:`model "${t.modelId}" is ${a==="not in availableModels"?"not in this session's availableModels":a} (agent ${s.agentId}); known models: ${i}`,logMessage:`session/set_model rejected sessionId=${t.sessionId} modelId=${JSON.stringify(t.modelId)} ${a} agentId=${s.agentId} known=[${i}] (no current model to fall back to)`}}async function Mu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0;if(!r)throw E(S.InvalidParams,"transformer/attach requires sessionId");if(!t.transformers)throw E(S.InternalError,"transformer manager not configured");let o=t.transformers.resolveChain([e])[0];if(!o)throw E(S.InternalError,`transformer ${e} is not connected (call hydra-acp/transformer/initialize first)`);return se(t.manager,r).addTransformer(o),{ok:!0}}async function Ru(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(S.InvalidParams,"hydra-acp/attention/set requires string sessionId");if(!o)throw E(S.InvalidParams,"hydra-acp/attention/set requires string reason");return se(t.manager,r).setAttentionFlag(e,o,s.payload),{ok:!0}}async function Eu(n,e,t){let s=n??{},r=typeof s.sessionId=="string"?s.sessionId:void 0,o=typeof s.reason=="string"?s.reason:void 0;if(!r)throw E(S.InvalidParams,"hydra-acp/attention/clear requires string sessionId");if(!o)throw E(S.InvalidParams,"hydra-acp/attention/clear requires string reason");return se(t.manager,r).clearAttentionFlag(e,o),{ok:!0}}function Pu(n){let e={sessionId:n.hydraSessionId,upstreamSessionId:n.upstreamSessionId,cwd:n.cwd,title:n.title,agentId:n.agentId,currentModel:n.currentModel,currentUsage:n.currentUsage,forkedFromSessionId:n.forkedFromSessionId,forkedFromMessageId:n.forkedFromMessageId,forkSynthesisState:n.forkSynthesisState,originatingClient:n.originatingClient,interactive:n.interactive,updatedAt:n.createdAt??new Date().toISOString(),attachedClients:0,status:"cold",busy:!1,awaitingInput:!1},t={currentMode:n.currentMode,agentArgs:n.agentArgs,availableCommands:n.agentCommands,availableModes:n.agentModes,availableModels:n.agentModels};return{[it]:Ft(e,t)}}function hn(n,e,t={}){let s=n.liveListEntry(e),r={clientId:t.clientId,currentMode:e.currentMode,agentArgs:e.agentArgs,availableCommands:e.mergedAvailableCommands(),availableModes:e.availableModes(),availableModels:e.availableModels(),turnStartedAt:e.turnStartedAt,agentCapabilities:e.agentCapabilities,queue:e.queueSnapshot(),...t.resurrected===!0?{resurrected:!0}:{}};return ot(e.agentMeta,Ft(s,r))}function Tu(){return{protocolVersion:1,agentInfo:{name:"hydra",version:K},agentCapabilities:{promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,auth:{logout:{}},sessionCapabilities:{attach:{},list:{},resume:{},delete:{},close:{},fork:{}}},authMethods:[{id:"proxy",name:"Hydra proxy",type:"agent",description:"Hydra proxies authentication to the downstream agent selected per session"}],_meta:ot(void 0,{prompt:{queueing:!0,cancelling:!0,updating:!0,amending:!0,pipelining:!1},agents:{list:!0,installProgress:!0},session:{fork:{forkAt:!0,agentSwap:!0,synthesis:!0,model:!0}}})}}function _u(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 vi(n,e){if(!e.transformers)return;let t=e.transformers.interestedIn("lifecycle:session.starting");for(let s of t)s.connection.notify("hydra-acp/transformer/session_event",{event:"session.starting",sessionId:n}).catch(()=>{})}function Mt(n,e,t,s,r){return{clientId:r??`cli_${Cs(8)}`,connection:n,clientInfo:s}}function yn(n,e,t){let s=n.attached.get(t);s&&(e.detach(s.clientId),n.attached.delete(t))}var wn=class{byToken=new Map;reserve(e){if(this.byToken.has(e))throw new Error("mcp token already bound");let t,s,r=new Promise((i,a)=>{t=i,s=a});r.catch(()=>{});let o={session:void 0,sessionReady:r,disposers:[]};return this.byToken.set(e,o),{complete:i=>{o.session=i,t(i)},abandon:i=>{this.byToken.delete(e),s(i??new Error("mcp token reservation abandoned"))}}}bind(e,t){let{complete:s}=this.reserve(e);s(t)}lookup(e){return this.byToken.get(e)}addDisposer(e,t){let s=this.byToken.get(e);s!==void 0&&s.disposers.push(t)}async unbind(e){let t=this.byToken.get(e);if(t!==void 0){this.byToken.delete(e);for(let s of t.disposers)try{await s()}catch{}}}size(){return this.byToken.size}};import{randomUUID as $u}from"crypto";import{McpServer as Fu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Ou}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as G}from"zod";function*xs(n){for(let e=0;e<n.length;e++){let t=n[e];if(!t)continue;let s=t;if(s.method!=="session/update")continue;let o=s.params?.update;!o||typeof o.sessionUpdate!="string"||(yield{entryId:e,entry:s,kind:o.sessionUpdate,update:o})}}function re(n){return{content:[{type:"text",text:JSON.stringify(n)}],structuredContent:n}}var bi="Bearer ";function nt(n){let e=n.headers.authorization;if(typeof e!="string"||!e.startsWith(bi))return;let t=e.slice(bi.length).trim();return t.length>0?t:void 0}function Hu(n){let e=new Fu({name:"hydra-acp-stdin",version:"1.0.0"},{instructions:"Piped input from `hydra cat --stream` is exposed here as a byte stream. Use `tail` for the latest N bytes (good for finding the end of a log), `head` for the first N bytes (good for headers/preamble), `read` for windowed reads against an absolute byte cursor, `wait_for_more` to block until new bytes arrive past a cursor, and `info` for the current cursors/capacity/closed status. Byte payloads come back base64-encoded."});return e.registerTool("tail",{description:"Return the most recent `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means older bytes existed but have been evicted from the ring.",inputSchema:{bytes:G.number().int().min(1).describe("How many trailing bytes to return.")}},async({bytes:t})=>{let s=n.streamTail(t);return re(s)}),e.registerTool("head",{description:"Return the first `bytes` bytes of piped stdin (capped server-side, default 64 KiB max). `truncated:true` means the head has already been evicted from the ring and the returned bytes start at the oldest still-resident cursor.",inputSchema:{bytes:G.number().int().min(1).describe("How many leading bytes to return.")}},async({bytes:t})=>{let s=n.streamHead(t);return re(s)}),e.registerTool("read",{description:"Read up to `max_bytes` bytes starting at absolute byte `cursor`. Returns `{bytes, nextCursor, gap?, eof?}` \u2014 `gap` is the number of bytes silently skipped because the ring had evicted them; `eof:true` means the producer closed and there is nothing left to read.",inputSchema:{cursor:G.number().int().min(0).describe("Absolute byte offset to start reading from. Use 0 to read from the very beginning (may produce a gap if old bytes have been evicted)."),max_bytes:G.number().int().min(1).optional().describe("Optional cap on how many bytes to return. Server caps at 64 KiB regardless."),wait_ms:G.number().int().min(0).optional().describe("If no bytes are available, block up to this many ms for more (capped server-side at 60_000).")}},async({cursor:t,max_bytes:s,wait_ms:r})=>{let o=await n.streamRead(t,s,r);return re(o)}),e.registerTool("wait_for_more",{description:"Block until bytes are available past `cursor`, the stream closes, or `timeout_ms` elapses. Returns one of {data, eof, timeout} plus the current `writeCursor`. Use this when you've consumed everything up to a cursor and want to wait for more without busy-polling.",inputSchema:{cursor:G.number().int().min(0).describe("The cursor you've already consumed up to."),timeout_ms:G.number().int().min(0).describe("Maximum ms to block (server caps at 60_000).")}},async({cursor:t,timeout_ms:s})=>{let r=await n.streamWaitFor(t,s),o=n.streamInfo();return re({outcome:r,writeCursor:o.writeCursor,closed:o.closed})}),e.registerTool("grep",{description:"Scan piped stdin line-by-line and return lines matching `pattern`. Prefer this over `read` when the question is 'find lines that mention X' \u2014 it filters server-side so you don't pull and decode 64 KiB base64 windows. Returns `{matches: [{cursor, line, before?, after?}], truncated, nextCursor, gap?, scannedBytes, eof?}`. Lines come back as decoded UTF-8 strings (not base64). When `truncated:true`, re-call with `cursor: nextCursor` to resume.",inputSchema:{pattern:G.string().min(1).describe("Search pattern. Treated as a JavaScript regular expression by default (set `regex:false` for a literal substring match)."),regex:G.boolean().optional().describe("Default true. Pass false to treat `pattern` as a literal substring."),case_insensitive:G.boolean().optional().describe("Default false. Pass true for case-insensitive matching."),invert:G.boolean().optional().describe("Default false. Pass true to return lines that do NOT match the pattern."),max_matches:G.number().int().min(1).optional().describe("Default 100. Capped server-side at 1000."),max_bytes:G.number().int().min(1).optional().describe("Default 64 KiB output. Capped server-side at 256 KiB."),context_before:G.number().int().min(0).optional().describe("Default 0. Number of lines before each match to include (capped at 20)."),context_after:G.number().int().min(0).optional().describe("Default 0. Number of lines after each match to include (capped at 20)."),cursor:G.number().int().min(0).optional().describe("Optional absolute byte offset to start scanning from. Omit to scan from the oldest still-resident byte. Pass the `nextCursor` from a previous truncated call to resume.")}},async t=>{let s={pattern:t.pattern};t.regex!==void 0&&(s.regex=t.regex),t.case_insensitive!==void 0&&(s.caseInsensitive=t.case_insensitive),t.invert!==void 0&&(s.invert=t.invert),t.max_matches!==void 0&&(s.maxMatches=t.max_matches),t.max_bytes!==void 0&&(s.maxBytes=t.max_bytes),t.context_before!==void 0&&(s.contextBefore=t.context_before),t.context_after!==void 0&&(s.contextAfter=t.context_after),t.cursor!==void 0&&(s.cursor=t.cursor);let r=n.streamGrep(s);return re(r)}),e.registerTool("info",{description:"Report cursor / capacity / closed state of the stdin ring. Cheap; safe to call repeatedly.",inputSchema:{}},async()=>{let t=n.streamInfo();return re(t)}),e}var Nu=1e4;function Ii(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let l=Hu(a),d=new Ou({sessionIdGenerator:()=>$u()});await l.connect(d);let f={server:l,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await l.close()}catch{}}),d}async function r(i,a){let u=nt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let l=e.lookup(u);if(l===void 0){a.code(404).send({error:"unknown stdin token"});return}let d;if(l.session!==void 0)d=l.session;else{let p,c=new Promise(m=>{p=setTimeout(()=>m(void 0),Nu)}),g=await Promise.race([l.sessionReady.catch(()=>{}),c]);if(p!==void 0&&clearTimeout(p),g===void 0){a.code(503).send({error:"session not ready"});return}d=g}let f=await s(u,d);a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-stdin",o,async(i,a)=>{await r(i,a)})}import{randomUUID as ju}from"crypto";import{McpServer as Bu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Uu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{z as xe}from"zod";function Du(n){switch(n){case"prompt_received":return"user";case"tool_call":case"tool_call_update":return"tool";default:return"agent"}}function Lu(n,e){if(n.length<=148)return n;let r=Math.floor(148/2),o=e-r;o<0&&(o=0);let i=o+148;i>n.length&&(o=n.length-148,o<0&&(o=0));let a=n.slice(o,i);return o>0&&(a="\u2026"+a),i<n.length&&(a=a+"\u2026"),a}function qu(n){let e=new Bu({name:"hydra-acp-recall",version:"1.0.0"},{instructions:"Search and retrieve detail from this session's pre-compaction history. After a compaction summary replaces earlier conversation in working memory, these tools let you page back specifics on demand. Use `search` to find entries by keyword, `range` to pull a contiguous slice verbatim, and `tool_calls` to enumerate prior tool invocations. These tools only return results once the session has been compacted at least once."});return e.registerTool("search",{description:"Search this session's prior conversation history (the part that was compacted out of your working memory) by keyword. Returns matching entry ids with short snippets so you can decide which to pull in full via `range`. Use this when the compaction summary mentions something but you need the verbatim detail.",inputSchema:{query:xe.string().min(1).describe("Case-insensitive substring to search for."),limit:xe.number().int().min(1).max(50).optional().describe("Maximum number of matches to return (default 10, max 50)."),include_tool_calls:xe.boolean().optional().describe("Whether to include tool_call entries in the search (default true).")}},async({query:t,limit:s=10,include_tool_calls:r=!0})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({matches:[],total_matched:0,truncated:!1,note:"This session has no compacted history. `search` retrieves detail from entries that were summarized out of the working conversation; nothing has been summarized yet."});let i=await o.getHistorySnapshot(),a=[];for(let{entryId:l,entry:d,kind:f}of xs(i)){if(f==="tool_call"&&!r)continue;let p=ze([d]),c=p.toLowerCase().indexOf(t.toLowerCase());if(c<0)continue;let g=Du(f),m=Lu(p,c),h=typeof d.recordedAt=="number"?String(d.recordedAt):void 0;if(a.push({entryId:l,speaker:g,snippet:m,timestamp:h}),a.length>=s)break}let u=a.length>=s&&a.length<i.length;return re({matches:a,total_matched:a.length,truncated:u})}),e.registerTool("range",{description:"Pull a contiguous range of prior conversation entries verbatim from this session's pre-compaction history. Use after `search` narrows in on what you need. Capped at 50 entries per call.",inputSchema:{from_entry:xe.number().int().min(0).describe("Zero-based index of the first entry to include (inclusive)."),to_entry:xe.number().int().min(0).describe("Zero-based index of the last entry to include (inclusive).")}},async({from_entry:t,to_entry:s})=>{let r=await n();if(!r.summarizedThroughEntry||r.summarizedThroughEntry===0)return re({text:"",entry_count:0,truncated:!1,note:"This session has no compacted history. `range` retrieves verbatim entries from the pre-compaction transcript; nothing has been compacted yet."});if(s<t)throw new Error(`range: to_entry (${s}) must be >= from_entry (${t})`);let o=s-t+1;if(o>50)throw new Error(`range: range size (${o}) exceeds maximum of 50 entries`);let i=await r.getHistorySnapshot(),a=Math.min(t,i.length-1),u=Math.min(s,i.length-1),l=a>t||u<s;if(a>u)return{content:[{type:"text",text:""}],structuredContent:{text:"",entry_count:0,truncated:l}};let d=i.slice(a,u+1),f=ze(d);return{content:[{type:"text",text:f}],structuredContent:{text:f,entry_count:d.length,truncated:l}}}),e.registerTool("tool_calls",{description:"Search this session's prior tool invocations by tool name and/or file path. Returns when each tool was called, the arguments, and the result status. Use this to recall which files were read/edited, what shell commands ran, etc.",inputSchema:{tool_name:xe.string().optional(),file_path:xe.string().optional(),limit:xe.number().int().min(1).max(100).optional()}},async({tool_name:t,file_path:s,limit:r=20})=>{let o=await n();if(!o.summarizedThroughEntry||o.summarizedThroughEntry===0)return re({calls:[],truncated:!1,note:"This session has no compacted history. `tool_calls` retrieves tool invocations from the pre-compaction transcript; nothing has been compacted yet."});let i=typeof t=="string"&&t.length>0,a=typeof s=="string"&&s.length>0;if(!i&&!a)throw new Error("tool_calls: at least one of tool_name or file_path must be provided");let u=await o.getHistorySnapshot(),l=[],d=new Map;for(let{entryId:c,entry:g,kind:m,update:h}of xs(u)){if(m!=="tool_call"&&m!=="tool_call_update")continue;let v=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:`__noid_${c}`,y=d.get(v);y||(y={entryId:c,toolName:"(unnamed)",rawInput:{},locations:[],status:"in_progress"},d.set(v,y),l.push(v)),typeof h.name=="string"&&h.name.length>0?y.toolName=h.name:(y.toolName==="(unnamed)"||m==="tool_call")&&typeof h.title=="string"&&h.title.length>0&&(y.toolName=h.title);let w=h.rawInput;if(w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0)for(let[b,A]of Object.entries(w))y.rawInput[b]=A;if(Array.isArray(h.locations))for(let b of h.locations){let A=b?.path;typeof A=="string"&&A.length>0&&!y.locations.includes(A)&&y.locations.push(A)}typeof h.status=="string"&&(y.status=h.status),g.recordedAt!==void 0&&y.timestamp===void 0&&(y.timestamp=String(g.recordedAt))}let f=[];for(let c of l){let g=d.get(c);if(t!==void 0&&g.toolName.toLowerCase()!==t.toLowerCase())continue;if(a){let h=s.toLowerCase(),v=["file_path","filePath","path"],y=!1;for(let w of v){let b=g.rawInput[w];if(typeof b=="string"&&b.toLowerCase().includes(h)){y=!0;break}}if(!y){for(let w of g.locations)if(w.toLowerCase().includes(h)){y=!0;break}}if(!y)continue}let m={};for(let[h,v]of Object.entries(g.rawInput))typeof v=="string"?m[h]=v.length>500?v.slice(0,497)+"\u2026":v:(typeof v=="number"||typeof v=="boolean")&&(m[h]=v);if(g.locations.length>0&&m.locations===void 0&&(m.locations=g.locations),f.push({entryId:g.entryId,tool:g.toolName,args:m,status:g.status,timestamp:g.timestamp}),f.length>=r)break}let p=f.length>=r;return re({calls:f,truncated:p})}),e}var zu=1e4;function Si(n,e){let t=new Map;async function s(i,a){let u=t.get(i);if(u!==void 0)return u.transport;let l=qu(a),d=new Uu({sessionIdGenerator:()=>ju()});await l.connect(d);let f={server:l,transport:d};return t.set(i,f),e.addDisposer(i,async()=>{t.delete(i);try{await d.close()}catch{}try{await l.close()}catch{}}),d}async function r(i,a){let u=nt(i);if(u===void 0){a.code(401).send({error:"missing bearer token"});return}let l=e.lookup(u);if(l===void 0){a.code(404).send({error:"unknown recall token"});return}let f=await s(u,async()=>{if(l.session!==void 0)return l.session;let p,c=new Promise(m=>{p=setTimeout(()=>m(void 0),zu)}),g=await Promise.race([l.sessionReady.catch(()=>{}),c]);if(p!==void 0&&clearTimeout(p),g===void 0)throw new Error("recall: session not ready");return g});a.hijack(),await f.handleRequest(i.raw,a.raw,i.body)}let o={config:{skipAuth:!0}};n.post("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.get("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)}),n.delete("/mcp/hydra-acp-recall",o,async(i,a)=>{await r(i,a)})}var vn=class{byName=new Map;changeHandlers=[];register(e,t,s,r){this.byName.set(e,{connection:t,instructions:s,tools:[...r]}),this.fireChanged(e,"register")}clear(e){this.byName.delete(e)&&this.fireChanged(e,"clear")}lookup(e){return this.byName.get(e)}list(){return Array.from(this.byName.keys())}onChange(e){return this.changeHandlers.push(e),()=>{let t=this.changeHandlers.indexOf(e);t>=0&&this.changeHandlers.splice(t,1)}}fireChanged(e,t){for(let s of this.changeHandlers)try{s(e,t)}catch{}}};import{StreamableHTTPServerTransport as Xu}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Zu}from"crypto";import{Server as Ju}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Wu,ListToolsRequestSchema as Qu}from"@modelcontextprotocol/sdk/types.js";function ki(n,e,t,s){let r=typeof t=="function"?async()=>t():async()=>t,o=new Ju({name:n,version:"1.0.0"},{capabilities:{tools:{listChanged:!0}},...e.instructions!==void 0?{instructions:e.instructions}:{}}),i=a=>({name:a.name,description:a.description,inputSchema:a.inputSchema,...a.outputSchema!==void 0?{outputSchema:a.outputSchema}:{}});return o.setRequestHandler(Qu,async()=>{let a=s?.peekSessionId?.();if(a!==void 0&&s?.fetchSessionTools!==void 0)try{let u=await s.fetchSessionTools(a);if(u!==void 0)return{tools:u.map(i)}}catch{}return{tools:e.tools.map(i)}}),o.setRequestHandler(Wu,async(a,u)=>{let l=a.params.name,d=u._meta?.progressToken??u.requestId,f=Ku(d,u.sendNotification);try{let p=await r(),c=await Gu(e.connection,n,l,a.params.arguments??{},p);return Yu(c,l)}catch(p){return Ms(p instanceof Error?p.message:String(p))}finally{f()}}),o}var Vu=15e3;function Ku(n,e,t=Vu){if(n===void 0)return()=>{};let s=0,r=setInterval(()=>{s+=1,e({method:"notifications/progress",params:{progressToken:n,progress:s}}).catch(()=>{})},t);return r.unref?.(),()=>clearInterval(r)}async function Gu(n,e,t,s,r){return await n.request("hydra-acp/mcp_tools/invoke",{server:e,tool:t,args:s,sessionId:r})}function Yu(n,e){if(n===null||typeof n!="object")return Ms(`extension ${e} returned non-object`);let t=n;return Array.isArray(t.content)?t:Ms(`extension ${e} omitted content array`)}function Ms(n){return{content:[{type:"text",text:n}],isError:!0}}var el=1e4;function Ai(n,e,t){let s=new Map;async function r(d){try{await d.transport.close()}catch{}try{await d.server.close()}catch{}}function o(d){for(let f of s.values()){let p=f.get(d);p!==void 0&&(f.delete(d),r(p))}}async function i(d,f){for(let[p,c]of s){if(e.lookup(p)?.session?.sessionId!==d)continue;let m=c.get(f);if(m!==void 0)try{await m.server.sendToolListChanged()}catch{}}}t.onChange(d=>{o(d)});async function a(d,f){let p=s.get(d);p===void 0&&(p=new Map,s.set(d,p),e.addDisposer(d,async()=>{let b=s.get(d);if(b!==void 0){s.delete(d);for(let A of b.values())await r(A)}}));let c=p.get(f);if(c!==void 0)return c.transport;let g=t.lookup(f);if(g===void 0)return;let y=ki(f,g,async()=>{let b=e.lookup(d);if(b===void 0)throw new Error("mcp token no longer bound");if(b.session!==void 0)return b.session.sessionId;let A,x=new Promise(T=>{A=setTimeout(()=>T(void 0),el)}),C=await Promise.race([b.sessionReady.catch(()=>{}),x]);if(A!==void 0&&clearTimeout(A),C===void 0)throw new Error("session not ready");return C.sessionId},{peekSessionId:()=>e.lookup(d)?.session?.sessionId,fetchSessionTools:async b=>{let A=await g.connection.request("hydra-acp/mcp_tools/list_tools",{sessionId:b});if(!A||typeof A!="object")return;let x=A.tools;if(!Array.isArray(x))return;let C=[];for(let T of x){if(!T||typeof T!="object")continue;let _=T;if(typeof _.name!="string"||_.name.length===0||typeof _.description!="string"||_.inputSchema===null||typeof _.inputSchema!="object")continue;let U={name:_.name,description:_.description,inputSchema:_.inputSchema};_.outputSchema!==null&&typeof _.outputSchema=="object"&&(U.outputSchema=_.outputSchema),C.push(U)}return C}}),w=new Xu({sessionIdGenerator:()=>Zu()});return await y.connect(w),p.set(f,{server:y,transport:w}),w}async function u(d,f){let p=nt(d);if(p===void 0){f.code(401).send({error:"missing bearer token"});return}if(e.lookup(p)===void 0){f.code(404).send({error:"unknown mcp token"});return}let g=d.params.name,m=await a(p,g);if(m===void 0){f.code(404).send({error:`unknown mcp server: ${g}`});return}f.hijack(),await m.handleRequest(d.raw,f.raw,d.body)}let l={config:{skipAuth:!0}};return n.post("/mcp/:name",l,async(d,f)=>{await u(d,f)}),n.get("/mcp/:name",l,async(d,f)=>{await u(d,f)}),n.delete("/mcp/:name",l,async(d,f)=>{await u(d,f)}),{notifyToolListChanged:i}}async function rl(n,e){al(n);let t=n.daemon.tls?await st.readFile(Y(n.daemon.tls.key)):void 0,s=n.daemon.tls?await st.readFile(Y(n.daemon.tls.cert)):void 0;await st.mkdir(k.home(),{recursive:!0});let{stream:r,fileStream:o}=await ol(n.daemon.logLevel),i=tl({logger:{level:n.daemon.logLevel,stream:r},bodyLimit:256*1024*1024});await i.register(nl,{options:{handleProtocols:_s}}),En(O=>{i.log.info(O)}),_n(O=>{i.log.info(O)});let a=await nn.load(),u=new dn,l=new an,d=new on([new sn(e),new rn(a),l]),f=_o({validator:d});i.addHook("onRequest",async(O,ce)=>{O.routeOptions.config?.skipAuth||O.url==="/acp"||O.url?.startsWith("/acp?")||await f(O,ce)});let p=setInterval(()=>{a.sweepExpired()},300*1e3);p.unref();let c=setInterval(()=>{u.sweepExpired()},300*1e3);c.unref();let g=new rt(n,{onFetched:()=>{So(g,y)}});ms(O=>i.log.info(O));let m={info:O=>i.log.info(O),warn:O=>i.log.warn(O)},h=O=>he.spawn({...O,stderrTailBytes:n.daemon.agentStderrTailBytes,logger:m});Ws(n.compressToolContent);let v=new en,y=new vt(g,h,void 0,{idleTimeoutMs:n.daemon.sessionIdleTimeoutSeconds*1e3,defaultModels:n.defaultModels,synopsisAgent:n.synopsisAgent,synopsisModel:n.synopsisModel,compactionAgent:n.compaction?.agent,compactionModel:n.compaction?.model,defaultTransformers:n.defaultTransformers,sessionHistoryMaxEntries:n.daemon.sessionHistoryMaxEntries,logger:m,npmRegistry:n.npmRegistry,extensionCommands:v,defaultCwd:n.defaultCwd}),w=new Xt(Bs(n),void 0,{tokenRegistry:l}),b=new Zt(Us(n),void 0,{tokenRegistry:l});oi(i,K,Co(n));let A=new wn,x=new vn,C,T=()=>{if(C!==void 0)return C;let O=i.server.address();return C=`http://127.0.0.1:${O&&typeof O=="object"?O.port:n.daemon.port}`,C};si(i,y,{agentId:n.defaultAgent,cwd:n.defaultCwd,publicHost:n.daemon.publicHost,host:n.daemon.host,port:n.daemon.port,compaction:n.compaction},{extensionMcp:x,mcpTokenRegistry:A,getDaemonOrigin:T}),ri(i,g,y,{npmRegistry:n.npmRegistry}),ii(i,w),ai(i,b),di(i,{defaultAgent:n.defaultAgent,defaultCwd:n.defaultCwd,defaultModels:{...n.defaultModels},...n.synopsisAgent!==void 0?{synopsisAgent:n.synopsisAgent}:{},...n.synopsisModel!==void 0?{synopsisModel:n.synopsisModel}:{},defaultTransformers:[...n.defaultTransformers]}),pi(i,{store:a,rateLimiter:u}),Ii(i,A),Si(i,A);let _=Ai(i,A,x);wi(i,{validator:d,manager:y,defaultAgent:n.defaultAgent,processRegistry:l,onExtensionVersion:(O,ce)=>w.reportVersion(O,ce),onTransformerVersion:(O,ce)=>b.reportVersion(O,ce),transformers:b,extensionCommands:v,mcpTokenRegistry:A,extensionMcp:x,extensionMcpControls:_,getDaemonOrigin:T,registry:g});let U=!!n.daemon.tls;await i.listen({host:U?"127.0.0.1":n.daemon.host,port:U?0:n.daemon.port});let $=i.server.address(),P=$&&typeof $=="object"?$.port:n.daemon.port,j,z=n.daemon.host,oe=P;if(U&&t&&s){j=il({listenHost:n.daemon.host,listenPort:n.daemon.port,upstreamHost:"127.0.0.1",upstreamPort:P,tlsOptions:{key:t,cert:s},logger:i.log});let O=j.address();O&&typeof O=="object"&&(oe=O.port)}await st.mkdir(k.home(),{recursive:!0}),await Io({pid:process.pid,host:z,port:oe,loopbackPort:P,startedAt:new Date().toISOString()});let _e={daemonUrl:`http://127.0.0.1:${P}`,daemonHost:"127.0.0.1",daemonPort:P,serviceToken:e,daemonWsUrl:`ws://127.0.0.1:${P}/acp`,hydraHome:k.home()};w.setContext(_e),b.setContext(_e),await w.start(),await b.start();try{await y.reconcilePermissionFlags()}catch(O){i.log.warn(`permission flag reconcile failed: ${O.message}`)}y.resurrectPendingQueues().catch(O=>{i.log.warn(`queue replay scan failed: ${O.message}`)}),y.resumePendingCompactions().catch(O=>{i.log.warn(`compaction resume scan failed: ${O.message}`)}),y.resumePendingAgentSwaps().catch(O=>{i.log.warn(`agent-swap resume scan failed: ${O.message}`)});let Rt=n.daemon.agentSyncIntervalMinutes*60*1e3,Rs=Rt>0?ko({registry:g,manager:y,intervalMs:Rt,logger:m}):void 0,Es=n.daemon.sessionGcIntervalMinutes*60*1e3,Ei=n.daemon.sessionGcMaxAgeDays*24*60*60*1e3,Ps=Es>0?Ao({manager:y,intervalMs:Es,maxAgeMs:Ei,logger:m}):void 0;return{app:i,manager:y,registry:g,extensions:w,transformers:b,mcpTokenRegistry:A,extensionMcp:x,processRegistry:l,shutdown:async()=>{Ps&&Ps(),Rs&&Rs(),clearInterval(p),clearInterval(c);let O=async(ce,Pi)=>{try{await Pi()}catch(bn){i.log.warn(`shutdown step ${ce} failed: ${bn instanceof Error?bn.message:String(bn)}`)}};await O("sessionTokenStore.flush",()=>a.flush()),await O("extensions.stop",()=>w.stop()),await O("transformers.stop",()=>b.stop()),await O("manager.closeAll",()=>y.closeAll()),await O("manager.flushSynopsis",()=>y.flushSynopsis(3e4)),await O("manager.shutdownSynopsis",()=>y.shutdownSynopsis()),await O("manager.flushMetaWrites",()=>y.flushMetaWrites()),await O("manager.flushHistoryWrites",()=>y.flushHistoryWrites()),En(null),_n(null),ms(null),j&&await O("tlsTerminator.close",()=>new Promise(ce=>j.close(()=>ce()))),await O("app.close",()=>i.close());try{xi.unlinkSync(k.pidFile())}catch{}await O("fileStream.flushSync",()=>o.flushSync())}}}async function ol(n){let e=await sl({file:k.logFile(),size:"10m",mkdir:!0,symlink:!0,limit:{count:20}}),t=Ci.destination(2);return{stream:Ci.multistream([{stream:e,level:n},{stream:t,level:n}]),fileStream:e}}function il(n){let e=Ri.createServer(n.tlsOptions,t=>{let s=Mi.connect({host:n.upstreamHost,port:n.upstreamPort}),r=!1,o=i=>{if(!r){r=!0,i&&n.logger.warn(`tls terminator forwarder error: ${i.message??String(i)}`);try{t.destroy()}catch{}try{s.destroy()}catch{}}};t.on("error",o),s.on("error",o),t.on("close",()=>o()),s.on("close",()=>o()),t.pipe(s),s.pipe(t)});return e.on("tlsClientError",t=>{n.logger.warn(`tls handshake error: ${t.message}`)}),e.listen({host:n.listenHost,port:n.listenPort}),e}function al(n){let e=n.daemon.host;if(!(e==="127.0.0.1"||e==="::1"||e==="localhost"||e==="[::1]")&&!n.daemon.tls)throw new Error(`Refusing to bind to non-loopback host ${e} without TLS configured.`)}export{he as AgentInstance,Ee as JsonRpcConnection,rt as Registry,Pe as Session,vt as SessionManager,Xi as defaultConfig,Fi as ensureServiceToken,Et as generateServiceToken,Ls as loadConfig,$i as loadServiceToken,Hn as ndjsonStreamFromStdio,k as paths,te as planSpawn,rl as startDaemon,Yi as writeConfig,As as wsToMessageStream};
|